identifier
stringlengths 0
89
| parameters
stringlengths 0
399
| return_statement
stringlengths 0
982
⌀ | docstring
stringlengths 10
3.04k
| docstring_summary
stringlengths 0
3.04k
| function
stringlengths 13
25.8k
| function_tokens
list | start_point
list | end_point
list | argument_list
null | language
stringclasses 3
values | docstring_language
stringclasses 4
values | docstring_language_predictions
stringclasses 4
values | is_langid_reliable
stringclasses 2
values | is_langid_extra_reliable
bool 1
class | type
stringclasses 9
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
p_instrucciones_lista_condiciones_NOT
|
(t)
|
lista_condiciones : NOT lista_condiciones
|
lista_condiciones : NOT lista_condiciones
|
def p_instrucciones_lista_condiciones_NOT(t) :
'lista_condiciones : NOT lista_condiciones'
t[1].append(t[3])
t[0] = t[1]
|
[
"def",
"p_instrucciones_lista_condiciones_NOT",
"(",
"t",
")",
":",
"t",
"[",
"1",
"]",
".",
"append",
"(",
"t",
"[",
"3",
"]",
")",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] |
[
533,
0
] |
[
536,
15
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
AccountMoveReversal.reverse_moves
|
(self)
|
return super(AccountMoveReversal, self).reverse_moves()
|
Forzamos fecha de la factura original para que el amount total de la linea se calcule bien
|
Forzamos fecha de la factura original para que el amount total de la linea se calcule bien
|
def reverse_moves(self):
""" Forzamos fecha de la factura original para que el amount total de la linea se calcule bien"""
self = self.with_context(invoice_date=self.move_id.date)
return super(AccountMoveReversal, self).reverse_moves()
|
[
"def",
"reverse_moves",
"(",
"self",
")",
":",
"self",
"=",
"self",
".",
"with_context",
"(",
"invoice_date",
"=",
"self",
".",
"move_id",
".",
"date",
")",
"return",
"super",
"(",
"AccountMoveReversal",
",",
"self",
")",
".",
"reverse_moves",
"(",
")"
] |
[
7,
4
] |
[
10,
63
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
DominioAGTSP.cruzar
|
(self, sol_a, sol_b)
|
return H1
|
Produce una nueva posible solución cruzando las dos soluciones dadas por parámetro.
Entradas:
sol_a (estructura de datos)
Estructura de datos que modela la solución antecesora A que será cruzada con la B
sol_b (estructura de datos)
Estructura de datos que modela la solución antecesora B que será cruzada con la A
Salidas:
(estructura de datos) Una nueva solución producto del cruzamiento entre las soluciones A y B
|
Produce una nueva posible solución cruzando las dos soluciones dadas por parámetro.
Entradas:
sol_a (estructura de datos)
Estructura de datos que modela la solución antecesora A que será cruzada con la B
sol_b (estructura de datos)
Estructura de datos que modela la solución antecesora B que será cruzada con la A
Salidas:
(estructura de datos) Una nueva solución producto del cruzamiento entre las soluciones A y B
|
def cruzar(self, sol_a, sol_b):
"""Produce una nueva posible solución cruzando las dos soluciones dadas por parámetro.
Entradas:
sol_a (estructura de datos)
Estructura de datos que modela la solución antecesora A que será cruzada con la B
sol_b (estructura de datos)
Estructura de datos que modela la solución antecesora B que será cruzada con la A
Salidas:
(estructura de datos) Una nueva solución producto del cruzamiento entre las soluciones A y B
"""
P1 = sol_a
P2 = sol_b
lenOri = len(sol_a)
H1 = [-1] * lenOri
geneA = 0
geneB = 0
while (geneA == geneB):#para que lo rango no sea igual a vacio
geneA = int(random.random() * lenOri)
geneB = int(random.random() * lenOri)
startGene = min(geneA, geneB)
endGene = max(geneA, geneB)
for i in range(startGene, endGene):
H1[i] = P1[i]
rec = 0#recorrido del padre
recorrido = 0#pos en la que va el nuevo elemento
while (rec < lenOri):
while (H1[recorrido] != -1 and recorrido + 1 < lenOri):
recorrido += 1
if (P2[rec] not in H1):
H1[recorrido] = P2[rec]
rec += 1
return H1
|
[
"def",
"cruzar",
"(",
"self",
",",
"sol_a",
",",
"sol_b",
")",
":",
"P1",
"=",
"sol_a",
"P2",
"=",
"sol_b",
"lenOri",
"=",
"len",
"(",
"sol_a",
")",
"H1",
"=",
"[",
"-",
"1",
"]",
"*",
"lenOri",
"geneA",
"=",
"0",
"geneB",
"=",
"0",
"while",
"(",
"geneA",
"==",
"geneB",
")",
":",
"#para que lo rango no sea igual a vacio\r",
"geneA",
"=",
"int",
"(",
"random",
".",
"random",
"(",
")",
"*",
"lenOri",
")",
"geneB",
"=",
"int",
"(",
"random",
".",
"random",
"(",
")",
"*",
"lenOri",
")",
"startGene",
"=",
"min",
"(",
"geneA",
",",
"geneB",
")",
"endGene",
"=",
"max",
"(",
"geneA",
",",
"geneB",
")",
"for",
"i",
"in",
"range",
"(",
"startGene",
",",
"endGene",
")",
":",
"H1",
"[",
"i",
"]",
"=",
"P1",
"[",
"i",
"]",
"rec",
"=",
"0",
"#recorrido del padre\r",
"recorrido",
"=",
"0",
"#pos en la que va el nuevo elemento\r",
"while",
"(",
"rec",
"<",
"lenOri",
")",
":",
"while",
"(",
"H1",
"[",
"recorrido",
"]",
"!=",
"-",
"1",
"and",
"recorrido",
"+",
"1",
"<",
"lenOri",
")",
":",
"recorrido",
"+=",
"1",
"if",
"(",
"P2",
"[",
"rec",
"]",
"not",
"in",
"H1",
")",
":",
"H1",
"[",
"recorrido",
"]",
"=",
"P2",
"[",
"rec",
"]",
"rec",
"+=",
"1",
"return",
"H1"
] |
[
77,
4
] |
[
113,
17
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
lol_path
|
()
|
return os.path.join(DATASETS_PATH, 'LOL_champions_stats.csv')
|
path de los campeones del lol
|
path de los campeones del lol
|
def lol_path():
"""path de los campeones del lol"""
return os.path.join(DATASETS_PATH, 'LOL_champions_stats.csv')
|
[
"def",
"lol_path",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"DATASETS_PATH",
",",
"'LOL_champions_stats.csv'",
")"
] |
[
17,
0
] |
[
19,
65
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
cars_in_csv
|
()
|
return datos
|
Trae los autos del archivo y los devuelve en formato de lista
|
Trae los autos del archivo y los devuelve en formato de lista
|
def cars_in_csv():
"""Trae los autos del archivo y los devuelve en formato de lista"""
datos = []
with open(cars_path()) as file_cars:
cars = csv.reader(file_cars, delimiter=',')
next(cars)
for elem in cars:
datos.append(elem)
return datos
|
[
"def",
"cars_in_csv",
"(",
")",
":",
"datos",
"=",
"[",
"]",
"with",
"open",
"(",
"cars_path",
"(",
")",
")",
"as",
"file_cars",
":",
"cars",
"=",
"csv",
".",
"reader",
"(",
"file_cars",
",",
"delimiter",
"=",
"','",
")",
"next",
"(",
"cars",
")",
"for",
"elem",
"in",
"cars",
":",
"datos",
".",
"append",
"(",
"elem",
")",
"return",
"datos"
] |
[
9,
0
] |
[
17,
16
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_declaracion3
|
(t)
|
declaracion : ID cualquieridentificador MODULO ROWTYPE PTCOMA
|
declaracion : ID cualquieridentificador MODULO ROWTYPE PTCOMA
|
def p_declaracion3(t):
'''declaracion : ID cualquieridentificador MODULO ROWTYPE PTCOMA'''
t[0] = getdeclaraciones2(t)
|
[
"def",
"p_declaracion3",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"getdeclaraciones2",
"(",
"t",
")"
] |
[
610,
0
] |
[
612,
31
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
Obj_EstadoCuenta.FinDetalle
|
(self)
|
Genera PDF y Crea el campo en labase de datos
|
Genera PDF y Crea el campo en labase de datos
|
def FinDetalle(self):
'''Genera PDF y Crea el campo en labase de datos'''
|
[
"def",
"FinDetalle",
"(",
"self",
")",
":"
] |
[
75,
4
] |
[
76,
59
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
es_divisible
|
(a: int, b: int)
|
return True if a % b == 0 else False
|
Comprueba si un número 'a' es divisible por un número 'b'
:param a: Número a evaluar
:a type: int
:param b: Divisor
:b type: int
:return: True si es divisible, False de lo contrario
:rtype: bool
|
Comprueba si un número 'a' es divisible por un número 'b'
|
def es_divisible(a: int, b: int) -> bool:
"""Comprueba si un número 'a' es divisible por un número 'b'
:param a: Número a evaluar
:a type: int
:param b: Divisor
:b type: int
:return: True si es divisible, False de lo contrario
:rtype: bool
"""
return True if a % b == 0 else False
|
[
"def",
"es_divisible",
"(",
"a",
":",
"int",
",",
"b",
":",
"int",
")",
"->",
"bool",
":",
"return",
"True",
"if",
"a",
"%",
"b",
"==",
"0",
"else",
"False"
] |
[
28,
0
] |
[
38,
40
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
TokenCallback.get_services_allowed
|
(token: str, *, cursor)
|
return services
|
Obtiene los servicios habilitados por un token determinado
|
Obtiene los servicios habilitados por un token determinado
|
async def get_services_allowed(token: str, *, cursor) -> Tuple[str]:
"""Obtiene los servicios habilitados por un token determinado"""
await cursor.execute(
"SELECT services FROM tokens WHERE token = %s LIMIT 1",
(token,)
)
services = await cursor.fetchone()
return services
|
[
"async",
"def",
"get_services_allowed",
"(",
"token",
":",
"str",
",",
"*",
",",
"cursor",
")",
"->",
"Tuple",
"[",
"str",
"]",
":",
"await",
"cursor",
".",
"execute",
"(",
"\"SELECT services FROM tokens WHERE token = %s LIMIT 1\"",
",",
"(",
"token",
",",
")",
")",
"services",
"=",
"await",
"cursor",
".",
"fetchone",
"(",
")",
"return",
"services"
] |
[
448,
4
] |
[
459,
23
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_llamada_funciones2_expresiones
|
(t)
|
llamadafunciones : ID PARIZQ PARDR
|
llamadafunciones : ID PARIZQ PARDR
|
def p_llamada_funciones2_expresiones(t):
'''llamadafunciones : ID PARIZQ PARDR'''
global columna
t[0] = Llamada(2, t[1], None, lexer.lineno, columna)
|
[
"def",
"p_llamada_funciones2_expresiones",
"(",
"t",
")",
":",
"global",
"columna",
"t",
"[",
"0",
"]",
"=",
"Llamada",
"(",
"2",
",",
"t",
"[",
"1",
"]",
",",
"None",
",",
"lexer",
".",
"lineno",
",",
"columna",
")"
] |
[
1761,
0
] |
[
1764,
56
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_lista_condicion_salida
|
(t)
|
condiciones : expresion
|
condiciones : expresion
|
def p_lista_condicion_salida(t) :
'condiciones : expresion'
|
[
"def",
"p_lista_condicion_salida",
"(",
"t",
")",
":"
] |
[
412,
0
] |
[
413,
34
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
UTeslaConnector.execute_command
|
(self, function_name: str, *args, **kwargs)
|
Ejecutar un comando para modificar u obtener un dato de la base de datos
Args:
function_name:
El nombre de la función
*args:
Argumentos variables para la función a ejecutar
**kwargs:
Argumentos claves variables para la función a ejecutar
Returns:
El resultado (si es que tiene) de la función ejecutada
|
Ejecutar un comando para modificar u obtener un dato de la base de datos
Args:
function_name:
El nombre de la función
|
async def execute_command(self, function_name: str, *args, **kwargs) -> Any:
"""Ejecutar un comando para modificar u obtener un dato de la base de datos
Args:
function_name:
El nombre de la función
*args:
Argumentos variables para la función a ejecutar
**kwargs:
Argumentos claves variables para la función a ejecutar
Returns:
El resultado (si es que tiene) de la función ejecutada
"""
if not (hasattr(self.callback, function_name)):
raise RuntimeError(_("La función a llamar no se encuentra"))
result = self.execute(
getattr(self.callback, function_name), *args, **kwargs
)
async for i in _return_coroutine(result):
yield i
|
[
"async",
"def",
"execute_command",
"(",
"self",
",",
"function_name",
":",
"str",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"Any",
":",
"if",
"not",
"(",
"hasattr",
"(",
"self",
".",
"callback",
",",
"function_name",
")",
")",
":",
"raise",
"RuntimeError",
"(",
"_",
"(",
"\"La función a llamar no se encuentra\")",
")",
"",
"result",
"=",
"self",
".",
"execute",
"(",
"getattr",
"(",
"self",
".",
"callback",
",",
"function_name",
")",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"async",
"for",
"i",
"in",
"_return_coroutine",
"(",
"result",
")",
":",
"yield",
"i"
] |
[
840,
4
] |
[
866,
19
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_PROPIETARIO_4
|
(t)
|
PROPIETARIO : owner cadena
|
PROPIETARIO : owner cadena
|
def p_PROPIETARIO_4(t):
'''PROPIETARIO : owner cadena
'''
t[0] = 'owner \'' + str(t[2]) + '\''
listaBNF.append("PROPIETARIO ::= owner " + str(t[2]))
|
[
"def",
"p_PROPIETARIO_4",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"'owner \\''",
"+",
"str",
"(",
"t",
"[",
"2",
"]",
")",
"+",
"'\\''",
"listaBNF",
".",
"append",
"(",
"\"PROPIETARIO ::= owner \"",
"+",
"str",
"(",
"t",
"[",
"2",
"]",
")",
")"
] |
[
1282,
0
] |
[
1286,
57
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_asignaciones
|
(t)
|
asignaciones : asignaciones COMA operacion
|
asignaciones : asignaciones COMA operacion
|
def p_asignaciones(t):
'''asignaciones : asignaciones COMA operacion
'''
a = t[1] + "," + t[3]
t[0] = a
|
[
"def",
"p_asignaciones",
"(",
"t",
")",
":",
"a",
"=",
"t",
"[",
"1",
"]",
"+",
"\",\"",
"+",
"t",
"[",
"3",
"]",
"t",
"[",
"0",
"]",
"=",
"a"
] |
[
2264,
0
] |
[
2269,
12
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
Factoria.get_persona
|
(self, nombre, genero, edad)
|
Metodo que retorna objetos persona segun el genero
|
Metodo que retorna objetos persona segun el genero
|
def get_persona(self, nombre, genero, edad):
"""Metodo que retorna objetos persona segun el genero"""
#genero es el parametro usado por la factoria
#para elegir el obj a crear
if (genero is 'F'):
return Femenino(nombre, edad, genero)
elif (genero is 'M'):
return Masculino(nombre, edad, genero)
|
[
"def",
"get_persona",
"(",
"self",
",",
"nombre",
",",
"genero",
",",
"edad",
")",
":",
"#genero es el parametro usado por la factoria",
"#para elegir el obj a crear",
"if",
"(",
"genero",
"is",
"'F'",
")",
":",
"return",
"Femenino",
"(",
"nombre",
",",
"edad",
",",
"genero",
")",
"elif",
"(",
"genero",
"is",
"'M'",
")",
":",
"return",
"Masculino",
"(",
"nombre",
",",
"edad",
",",
"genero",
")"
] |
[
8,
1
] |
[
16,
41
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
ayuda
|
(update, context)
|
Manda un mensaje cuando el usuario ingresa /ayuda
|
Manda un mensaje cuando el usuario ingresa /ayuda
|
def ayuda(update, context):
"""Manda un mensaje cuando el usuario ingresa /ayuda """
update.message.reply_text('Probá el comando /factoreo para recibir los casos más comunes de factoreo o /derivar funcion para ver la derivada de f(x)!')
|
[
"def",
"ayuda",
"(",
"update",
",",
"context",
")",
":",
"update",
".",
"message",
".",
"reply_text",
"(",
"'Probá el comando /factoreo para recibir los casos más comunes de factoreo o /derivar funcion para ver la derivada de f(x)!')",
""
] |
[
34,
0
] |
[
36,
157
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
TrackingVideo._draw_object_bounding_box_trace
|
(self,
fid: int,
frame: Image,
tracked_object: TrackedObject)
|
return frame
|
Dibuja los trazados del bounding box de un objeto..
:param fid: número del frame.
:param frame: frame.
:param tracked_object: estructura del seguimiento del objeto.
:return: imagen con el seguimiento del objeto.
|
Dibuja los trazados del bounding box de un objeto..
|
def _draw_object_bounding_box_trace(self,
fid: int,
frame: Image,
tracked_object: TrackedObject) -> Image:
"""Dibuja los trazados del bounding box de un objeto..
:param fid: número del frame.
:param frame: frame.
:param tracked_object: estructura del seguimiento del objeto.
:return: imagen con el seguimiento del objeto.
"""
bounding_boxes = [t_obj.object.bounding_box
for t_obj in tracked_object if t_obj.frame <= fid]
# Comprobación de que se ha obtenido al menos una posición.
if len(bounding_boxes) == 0:
return frame
# Dibujar bounding boxes.
color = self._objects_colors[tracked_object.id]
prev_bounding_box = bounding_boxes[0]
for bounding_box in bounding_boxes:
for position_id in range(len(bounding_box)):
position = bounding_box[position_id]
prev_position = prev_bounding_box[position_id]
cv2.line(frame, position, prev_position, color, 1, cv2.LINE_AA)
prev_bounding_box = bounding_box
return frame
|
[
"def",
"_draw_object_bounding_box_trace",
"(",
"self",
",",
"fid",
":",
"int",
",",
"frame",
":",
"Image",
",",
"tracked_object",
":",
"TrackedObject",
")",
"->",
"Image",
":",
"bounding_boxes",
"=",
"[",
"t_obj",
".",
"object",
".",
"bounding_box",
"for",
"t_obj",
"in",
"tracked_object",
"if",
"t_obj",
".",
"frame",
"<=",
"fid",
"]",
"# Comprobación de que se ha obtenido al menos una posición.",
"if",
"len",
"(",
"bounding_boxes",
")",
"==",
"0",
":",
"return",
"frame",
"# Dibujar bounding boxes.",
"color",
"=",
"self",
".",
"_objects_colors",
"[",
"tracked_object",
".",
"id",
"]",
"prev_bounding_box",
"=",
"bounding_boxes",
"[",
"0",
"]",
"for",
"bounding_box",
"in",
"bounding_boxes",
":",
"for",
"position_id",
"in",
"range",
"(",
"len",
"(",
"bounding_box",
")",
")",
":",
"position",
"=",
"bounding_box",
"[",
"position_id",
"]",
"prev_position",
"=",
"prev_bounding_box",
"[",
"position_id",
"]",
"cv2",
".",
"line",
"(",
"frame",
",",
"position",
",",
"prev_position",
",",
"color",
",",
"1",
",",
"cv2",
".",
"LINE_AA",
")",
"prev_bounding_box",
"=",
"bounding_box",
"return",
"frame"
] |
[
286,
4
] |
[
311,
20
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
integral_cv
|
(a)
|
return output
|
Calcula la integral de la funcion gaussiana_cv entre 0 y 1/a.
|
Calcula la integral de la funcion gaussiana_cv entre 0 y 1/a.
|
def integral_cv(a):
"""Calcula la integral de la funcion gaussiana_cv entre 0 y 1/a.
"""
if type(a) == np.ndarray:
output = [quad(gausiana_cv, 0, 1/a_i)[0] for a_i in a]
output = np.array(output)
else:
output = quad(gausiana_cv, 0, 1/a)[0]
return output
|
[
"def",
"integral_cv",
"(",
"a",
")",
":",
"if",
"type",
"(",
"a",
")",
"==",
"np",
".",
"ndarray",
":",
"output",
"=",
"[",
"quad",
"(",
"gausiana_cv",
",",
"0",
",",
"1",
"/",
"a_i",
")",
"[",
"0",
"]",
"for",
"a_i",
"in",
"a",
"]",
"output",
"=",
"np",
".",
"array",
"(",
"output",
")",
"else",
":",
"output",
"=",
"quad",
"(",
"gausiana_cv",
",",
"0",
",",
"1",
"/",
"a",
")",
"[",
"0",
"]",
"return",
"output"
] |
[
54,
0
] |
[
62,
17
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
BcraSmlScraperTestCase.test_parse_from_intermediate_panel
|
(self)
|
Probar parseo desde el archivo intermedio
|
Probar parseo desde el archivo intermedio
|
def test_parse_from_intermediate_panel(self):
"""Probar parseo desde el archivo intermedio"""
start_date = '2019-03-06'
end_date = '2019-03-06'
coins = {
"peso_uruguayo": "Peso Uruguayo",
"real": "Real"
}
url = ''
intermediate_panel_df = MagicMock()
intermediate_panel_df = {
'indice_tiempo': [
'2019-03-06',
'2019-03-06',
'2019-03-06',
'2019-03-06',
'2019-03-06',
'2019-03-06',
'2019-03-06',
'2019-03-06'
],
'coin': [
'real',
'real',
'real',
'real',
'peso_uruguayo',
'peso_uruguayo',
'peso_uruguayo',
'peso_uruguayo'
],
'type': [
'Tipo de cambio de Referencia',
'Tipo de cambio PTAX',
'Tipo de cambio SML Peso Real',
'Tipo de cambio SML Real Peso',
'Tipo de cambio de Referencia',
'Tipo de cambio URINUSCA',
'Tipo de cambio SML Peso Uruguayo',
'Tipo de cambio SML Uruguayo Peso'
],
'value': [
'40.48170',
'3.83000',
'10.56965',
'0.09465',
'40.48170',
'32.68200',
'1.23865',
'0.80735',
]
}
with patch.object(
BCRASMLScraper,
'read_intermediate_panel_dataframe',
return_value=pd.DataFrame(data=intermediate_panel_df)
):
scraper = BCRASMLScraper(url, coins, intermediate_panel_path=None, use_intermediate_panel=True)
content = scraper.parse_from_intermediate_panel(
start_date, end_date,
)
assert content == {
'peso_uruguayo': [
{
'indice_tiempo': '2019-03-06',
'Tipo de cambio de Referencia': '40.48170',
'Tipo de cambio URINUSCA': '32.68200',
'Tipo de cambio SML Peso Uruguayo': '1.23865',
'Tipo de cambio SML Uruguayo Peso': '0.80735'
}
],
'real': [
{
'indice_tiempo': '2019-03-06',
'Tipo de cambio de Referencia': '40.48170',
'Tipo de cambio PTAX': '3.83000',
'Tipo de cambio SML Peso Real': '10.56965',
'Tipo de cambio SML Real Peso': '0.09465'
}
]
}
|
[
"def",
"test_parse_from_intermediate_panel",
"(",
"self",
")",
":",
"start_date",
"=",
"'2019-03-06'",
"end_date",
"=",
"'2019-03-06'",
"coins",
"=",
"{",
"\"peso_uruguayo\"",
":",
"\"Peso Uruguayo\"",
",",
"\"real\"",
":",
"\"Real\"",
"}",
"url",
"=",
"''",
"intermediate_panel_df",
"=",
"MagicMock",
"(",
")",
"intermediate_panel_df",
"=",
"{",
"'indice_tiempo'",
":",
"[",
"'2019-03-06'",
",",
"'2019-03-06'",
",",
"'2019-03-06'",
",",
"'2019-03-06'",
",",
"'2019-03-06'",
",",
"'2019-03-06'",
",",
"'2019-03-06'",
",",
"'2019-03-06'",
"]",
",",
"'coin'",
":",
"[",
"'real'",
",",
"'real'",
",",
"'real'",
",",
"'real'",
",",
"'peso_uruguayo'",
",",
"'peso_uruguayo'",
",",
"'peso_uruguayo'",
",",
"'peso_uruguayo'",
"]",
",",
"'type'",
":",
"[",
"'Tipo de cambio de Referencia'",
",",
"'Tipo de cambio PTAX'",
",",
"'Tipo de cambio SML Peso Real'",
",",
"'Tipo de cambio SML Real Peso'",
",",
"'Tipo de cambio de Referencia'",
",",
"'Tipo de cambio URINUSCA'",
",",
"'Tipo de cambio SML Peso Uruguayo'",
",",
"'Tipo de cambio SML Uruguayo Peso'",
"]",
",",
"'value'",
":",
"[",
"'40.48170'",
",",
"'3.83000'",
",",
"'10.56965'",
",",
"'0.09465'",
",",
"'40.48170'",
",",
"'32.68200'",
",",
"'1.23865'",
",",
"'0.80735'",
",",
"]",
"}",
"with",
"patch",
".",
"object",
"(",
"BCRASMLScraper",
",",
"'read_intermediate_panel_dataframe'",
",",
"return_value",
"=",
"pd",
".",
"DataFrame",
"(",
"data",
"=",
"intermediate_panel_df",
")",
")",
":",
"scraper",
"=",
"BCRASMLScraper",
"(",
"url",
",",
"coins",
",",
"intermediate_panel_path",
"=",
"None",
",",
"use_intermediate_panel",
"=",
"True",
")",
"content",
"=",
"scraper",
".",
"parse_from_intermediate_panel",
"(",
"start_date",
",",
"end_date",
",",
")",
"assert",
"content",
"==",
"{",
"'peso_uruguayo'",
":",
"[",
"{",
"'indice_tiempo'",
":",
"'2019-03-06'",
",",
"'Tipo de cambio de Referencia'",
":",
"'40.48170'",
",",
"'Tipo de cambio URINUSCA'",
":",
"'32.68200'",
",",
"'Tipo de cambio SML Peso Uruguayo'",
":",
"'1.23865'",
",",
"'Tipo de cambio SML Uruguayo Peso'",
":",
"'0.80735'",
"}",
"]",
",",
"'real'",
":",
"[",
"{",
"'indice_tiempo'",
":",
"'2019-03-06'",
",",
"'Tipo de cambio de Referencia'",
":",
"'40.48170'",
",",
"'Tipo de cambio PTAX'",
":",
"'3.83000'",
",",
"'Tipo de cambio SML Peso Real'",
":",
"'10.56965'",
",",
"'Tipo de cambio SML Real Peso'",
":",
"'0.09465'",
"}",
"]",
"}"
] |
[
605,
4
] |
[
690,
13
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
Linea.__init__
|
(self, texto)
|
Establece el texto completo, con indicadores, de la línea.
|
Establece el texto completo, con indicadores, de la línea.
|
def __init__(self, texto):
"""Establece el texto completo, con indicadores, de la línea."""
self._texto_original = texto
|
[
"def",
"__init__",
"(",
"self",
",",
"texto",
")",
":",
"self",
".",
"_texto_original",
"=",
"texto"
] |
[
33,
4
] |
[
35,
36
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
PlaceDbWriter.is_registered
|
(self, data)
|
Ejecuta la query para comprobar si el local comercial ha sido registrado para la fecha pasada por argumento.
|
Ejecuta la query para comprobar si el local comercial ha sido registrado para la fecha pasada por argumento.
|
def is_registered(self, data):
"""Ejecuta la query para comprobar si el local comercial ha sido registrado para la fecha pasada por argumento.
"""
name = data.get("name", "")
date = data.get("date", "")
address = "{prefix_address}%".format(prefix_address=data.get("address", ""))
cursor = self.db.cursor()
is_registered = False
try:
cursor.execute(self._find_place_query, (name, date, address))
db_element = cursor.fetchone()
if db_element and len(db_element):
is_registered = True
else:
is_registered = False
except Exception as e:
self.logger.error("-{place}-: error checking if place is already registered for address"
" -{address} and date -{date}-".format(place=name, date=date, address=address))
self.logger.error(str(e))
finally:
cursor.close()
return is_registered
|
[
"def",
"is_registered",
"(",
"self",
",",
"data",
")",
":",
"name",
"=",
"data",
".",
"get",
"(",
"\"name\"",
",",
"\"\"",
")",
"date",
"=",
"data",
".",
"get",
"(",
"\"date\"",
",",
"\"\"",
")",
"address",
"=",
"\"{prefix_address}%\"",
".",
"format",
"(",
"prefix_address",
"=",
"data",
".",
"get",
"(",
"\"address\"",
",",
"\"\"",
")",
")",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"is_registered",
"=",
"False",
"try",
":",
"cursor",
".",
"execute",
"(",
"self",
".",
"_find_place_query",
",",
"(",
"name",
",",
"date",
",",
"address",
")",
")",
"db_element",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"if",
"db_element",
"and",
"len",
"(",
"db_element",
")",
":",
"is_registered",
"=",
"True",
"else",
":",
"is_registered",
"=",
"False",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"-{place}-: error checking if place is already registered for address\"",
"\" -{address} and date -{date}-\"",
".",
"format",
"(",
"place",
"=",
"name",
",",
"date",
"=",
"date",
",",
"address",
"=",
"address",
")",
")",
"self",
".",
"logger",
".",
"error",
"(",
"str",
"(",
"e",
")",
")",
"finally",
":",
"cursor",
".",
"close",
"(",
")",
"return",
"is_registered"
] |
[
174,
4
] |
[
195,
32
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
gemv
|
(transa, alpha, a, x, beta, y)
|
Computes y = alpha * op(a) @ x + beta * y
op(a) = a if transa is 'N', op(a) = a.T if transa is 'T',
op(a) = a.T.conj() if transa is 'H'.
Note: ''y'' will be updated.
|
Computes y = alpha * op(a) @ x + beta * y
|
def gemv(transa, alpha, a, x, beta, y):
"""Computes y = alpha * op(a) @ x + beta * y
op(a) = a if transa is 'N', op(a) = a.T if transa is 'T',
op(a) = a.T.conj() if transa is 'H'.
Note: ''y'' will be updated.
"""
dtype = a.dtype.char
if dtype == 'f':
func = cublas.sgemv
elif dtype == 'd':
func = cublas.dgemv
elif dtype == 'F':
func = cublas.cgemv
elif dtype == 'D':
func = cublas.zgemv
else:
raise TypeError('invalid dtype')
assert a.ndim == 2
assert x.ndim == y.ndim == 1
assert a.dtype == x.dtype == y.dtype
m, n = a.shape
transa = _trans_to_cublas_op(transa)
if transa == cublas.CUBLAS_OP_N:
xlen, ylen = n, m
else:
xlen, ylen = m, n
assert x.shape[0] == xlen
assert y.shape[0] == ylen
alpha, alpha_ptr = _get_scalar_ptr(alpha, a.dtype)
beta, beta_ptr = _get_scalar_ptr(beta, a.dtype)
handle = device.get_cublas_handle()
orig_mode = cublas.getPointerMode(handle)
if isinstance(alpha, cupy.ndarray) or isinstance(beta, cupy.ndarray):
if not isinstance(alpha, cupy.ndarray):
alpha = cupy.array(alpha)
alpha_ptr = alpha.data.ptr
if not isinstance(beta, cupy.ndarray):
beta = cupy.array(beta)
beta_ptr = beta.data.ptr
cublas.setPointerMode(handle, cublas.CUBLAS_POINTER_MODE_DEVICE)
else:
cublas.setPointerMode(handle, cublas.CUBLAS_POINTER_MODE_HOST)
try:
if a._f_contiguous:
func(handle, transa, m, n, alpha_ptr, a.data.ptr, m, x.data.ptr, 1,
beta_ptr, y.data.ptr, 1)
elif a._c_contiguous and transa != cublas.CUBLAS_OP_C:
if transa == cublas.CUBLAS_OP_N:
transa = cublas.CUBLAS_OP_T
else:
transa = cublas.CUBLAS_OP_N
func(handle, transa, n, m, alpha_ptr, a.data.ptr, n, x.data.ptr, 1,
beta_ptr, y.data.ptr, 1)
else:
a = a.copy(order='F')
func(handle, transa, m, n, alpha_ptr, a.data.ptr, m, x.data.ptr, 1,
beta_ptr, y.data.ptr, 1)
finally:
cublas.setPointerMode(handle, orig_mode)
|
[
"def",
"gemv",
"(",
"transa",
",",
"alpha",
",",
"a",
",",
"x",
",",
"beta",
",",
"y",
")",
":",
"dtype",
"=",
"a",
".",
"dtype",
".",
"char",
"if",
"dtype",
"==",
"'f'",
":",
"func",
"=",
"cublas",
".",
"sgemv",
"elif",
"dtype",
"==",
"'d'",
":",
"func",
"=",
"cublas",
".",
"dgemv",
"elif",
"dtype",
"==",
"'F'",
":",
"func",
"=",
"cublas",
".",
"cgemv",
"elif",
"dtype",
"==",
"'D'",
":",
"func",
"=",
"cublas",
".",
"zgemv",
"else",
":",
"raise",
"TypeError",
"(",
"'invalid dtype'",
")",
"assert",
"a",
".",
"ndim",
"==",
"2",
"assert",
"x",
".",
"ndim",
"==",
"y",
".",
"ndim",
"==",
"1",
"assert",
"a",
".",
"dtype",
"==",
"x",
".",
"dtype",
"==",
"y",
".",
"dtype",
"m",
",",
"n",
"=",
"a",
".",
"shape",
"transa",
"=",
"_trans_to_cublas_op",
"(",
"transa",
")",
"if",
"transa",
"==",
"cublas",
".",
"CUBLAS_OP_N",
":",
"xlen",
",",
"ylen",
"=",
"n",
",",
"m",
"else",
":",
"xlen",
",",
"ylen",
"=",
"m",
",",
"n",
"assert",
"x",
".",
"shape",
"[",
"0",
"]",
"==",
"xlen",
"assert",
"y",
".",
"shape",
"[",
"0",
"]",
"==",
"ylen",
"alpha",
",",
"alpha_ptr",
"=",
"_get_scalar_ptr",
"(",
"alpha",
",",
"a",
".",
"dtype",
")",
"beta",
",",
"beta_ptr",
"=",
"_get_scalar_ptr",
"(",
"beta",
",",
"a",
".",
"dtype",
")",
"handle",
"=",
"device",
".",
"get_cublas_handle",
"(",
")",
"orig_mode",
"=",
"cublas",
".",
"getPointerMode",
"(",
"handle",
")",
"if",
"isinstance",
"(",
"alpha",
",",
"cupy",
".",
"ndarray",
")",
"or",
"isinstance",
"(",
"beta",
",",
"cupy",
".",
"ndarray",
")",
":",
"if",
"not",
"isinstance",
"(",
"alpha",
",",
"cupy",
".",
"ndarray",
")",
":",
"alpha",
"=",
"cupy",
".",
"array",
"(",
"alpha",
")",
"alpha_ptr",
"=",
"alpha",
".",
"data",
".",
"ptr",
"if",
"not",
"isinstance",
"(",
"beta",
",",
"cupy",
".",
"ndarray",
")",
":",
"beta",
"=",
"cupy",
".",
"array",
"(",
"beta",
")",
"beta_ptr",
"=",
"beta",
".",
"data",
".",
"ptr",
"cublas",
".",
"setPointerMode",
"(",
"handle",
",",
"cublas",
".",
"CUBLAS_POINTER_MODE_DEVICE",
")",
"else",
":",
"cublas",
".",
"setPointerMode",
"(",
"handle",
",",
"cublas",
".",
"CUBLAS_POINTER_MODE_HOST",
")",
"try",
":",
"if",
"a",
".",
"_f_contiguous",
":",
"func",
"(",
"handle",
",",
"transa",
",",
"m",
",",
"n",
",",
"alpha_ptr",
",",
"a",
".",
"data",
".",
"ptr",
",",
"m",
",",
"x",
".",
"data",
".",
"ptr",
",",
"1",
",",
"beta_ptr",
",",
"y",
".",
"data",
".",
"ptr",
",",
"1",
")",
"elif",
"a",
".",
"_c_contiguous",
"and",
"transa",
"!=",
"cublas",
".",
"CUBLAS_OP_C",
":",
"if",
"transa",
"==",
"cublas",
".",
"CUBLAS_OP_N",
":",
"transa",
"=",
"cublas",
".",
"CUBLAS_OP_T",
"else",
":",
"transa",
"=",
"cublas",
".",
"CUBLAS_OP_N",
"func",
"(",
"handle",
",",
"transa",
",",
"n",
",",
"m",
",",
"alpha_ptr",
",",
"a",
".",
"data",
".",
"ptr",
",",
"n",
",",
"x",
".",
"data",
".",
"ptr",
",",
"1",
",",
"beta_ptr",
",",
"y",
".",
"data",
".",
"ptr",
",",
"1",
")",
"else",
":",
"a",
"=",
"a",
".",
"copy",
"(",
"order",
"=",
"'F'",
")",
"func",
"(",
"handle",
",",
"transa",
",",
"m",
",",
"n",
",",
"alpha_ptr",
",",
"a",
".",
"data",
".",
"ptr",
",",
"m",
",",
"x",
".",
"data",
".",
"ptr",
",",
"1",
",",
"beta_ptr",
",",
"y",
".",
"data",
".",
"ptr",
",",
"1",
")",
"finally",
":",
"cublas",
".",
"setPointerMode",
"(",
"handle",
",",
"orig_mode",
")"
] |
[
420,
0
] |
[
482,
48
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
planilla.guardar_planilla
|
(self)
|
Guarda en un archivo .txt la planilla (diccionario) de forma directa.
|
Guarda en un archivo .txt la planilla (diccionario) de forma directa.
|
def guardar_planilla(self):
"Guarda en un archivo .txt la planilla (diccionario) de forma directa."
# open file for writing
f = open(input("nombre")+".txt","w") #Abre eel archivo txt y habilita escribir "w"
# write file
f.write(str(self.Planilla_)) #escribe en f = (file.txt) el string del diccionario
# close file
f.close()
|
[
"def",
"guardar_planilla",
"(",
"self",
")",
":",
"# open file for writing",
"f",
"=",
"open",
"(",
"input",
"(",
"\"nombre\"",
")",
"+",
"\".txt\"",
",",
"\"w\"",
")",
"#Abre eel archivo txt y habilita escribir \"w\"",
"# write file",
"f",
".",
"write",
"(",
"str",
"(",
"self",
".",
"Planilla_",
")",
")",
"#escribe en f = (file.txt) el string del diccionario ",
"# close file",
"f",
".",
"close",
"(",
")"
] |
[
41,
4
] |
[
48,
17
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
InitSession.__init__
|
(
self,
pk_dst: bytes,
sk_src: Optional[bytes] = None
)
|
Crea y/o importa tanto las claves del destinatario como del remitente
Args:
pk_dst:
La clave pública del destinatario
sk_src:
La clave privada del remitente.
Si no se especifica, se genera.
|
Crea y/o importa tanto las claves del destinatario como del remitente
Args:
pk_dst:
La clave pública del destinatario
|
def __init__(
self,
pk_dst: bytes,
sk_src: Optional[bytes] = None
):
"""Crea y/o importa tanto las claves del destinatario como del remitente
Args:
pk_dst:
La clave pública del destinatario
sk_src:
La clave privada del remitente.
Si no se especifica, se genera.
"""
if (sk_src is None):
self._sk_src = nacl.public.PrivateKey.generate()
else:
self._sk_src = nacl.public.PrivateKey(sk_src)
self._pk_dst = nacl.public.PublicKey(pk_dst)
self._box = nacl.public.Box(self._sk_src, self._pk_dst)
|
[
"def",
"__init__",
"(",
"self",
",",
"pk_dst",
":",
"bytes",
",",
"sk_src",
":",
"Optional",
"[",
"bytes",
"]",
"=",
"None",
")",
":",
"if",
"(",
"sk_src",
"is",
"None",
")",
":",
"self",
".",
"_sk_src",
"=",
"nacl",
".",
"public",
".",
"PrivateKey",
".",
"generate",
"(",
")",
"else",
":",
"self",
".",
"_sk_src",
"=",
"nacl",
".",
"public",
".",
"PrivateKey",
"(",
"sk_src",
")",
"self",
".",
"_pk_dst",
"=",
"nacl",
".",
"public",
".",
"PublicKey",
"(",
"pk_dst",
")",
"self",
".",
"_box",
"=",
"nacl",
".",
"public",
".",
"Box",
"(",
"self",
".",
"_sk_src",
",",
"self",
".",
"_pk_dst",
")"
] |
[
60,
4
] |
[
85,
63
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
CentroDeSaludListView.get_queryset
|
(self)
|
return qs
|
mostrar todos los centros y permitir
modificar solo sobre los cuales tiene permiso
csp = self.request.user.centros_de_salud_permitidos.all()
permitidos = [c.centro_de_salud.id for c in csp]
qs = CentroDeSalud.objects.filter(pk__in=permitidos)
|
mostrar todos los centros y permitir
modificar solo sobre los cuales tiene permiso
csp = self.request.user.centros_de_salud_permitidos.all()
permitidos = [c.centro_de_salud.id for c in csp]
qs = CentroDeSalud.objects.filter(pk__in=permitidos)
|
def get_queryset(self):
""" mostrar todos los centros y permitir
modificar solo sobre los cuales tiene permiso
csp = self.request.user.centros_de_salud_permitidos.all()
permitidos = [c.centro_de_salud.id for c in csp]
qs = CentroDeSalud.objects.filter(pk__in=permitidos)
"""
qs = CentroDeSalud.objects.all()
if 'search' in self.request.GET:
q = self.request.GET['search']
qs = qs.filter(
Q(nombre__icontains=q) |
Q(codigo_hpgd__icontains=q)
)
return qs
|
[
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"CentroDeSalud",
".",
"objects",
".",
"all",
"(",
")",
"if",
"'search'",
"in",
"self",
".",
"request",
".",
"GET",
":",
"q",
"=",
"self",
".",
"request",
".",
"GET",
"[",
"'search'",
"]",
"qs",
"=",
"qs",
".",
"filter",
"(",
"Q",
"(",
"nombre__icontains",
"=",
"q",
")",
"|",
"Q",
"(",
"codigo_hpgd__icontains",
"=",
"q",
")",
")",
"return",
"qs"
] |
[
24,
4
] |
[
40,
17
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_instrucciones_funcion_div
|
(t)
|
lista_funciones : DIV PARIZQ funcion_math_parametro COMA ENTERO PARDER
|
lista_funciones : DIV PARIZQ funcion_math_parametro COMA ENTERO PARDER
|
def p_instrucciones_funcion_div(t) :
'lista_funciones : DIV PARIZQ funcion_math_parametro COMA ENTERO PARDER'
|
[
"def",
"p_instrucciones_funcion_div",
"(",
"t",
")",
":"
] |
[
897,
0
] |
[
898,
79
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
solucion_c
|
(fuente: str, analizador: dict, n: int = 2)
|
return "".join(
[analizador[fuente[x:x+n]] for x in range(0, len(fuente), n)
if fuente[x:x+n] in analizador]
)
|
Reemplaza 'n' caracteres si son encontrados en el
analizador.
:param fuente: Texto fuente
:fuente type: str
:param analizador: Mapeo de caracteres a reemplazar
:analizador type: dict
:param n: Cantidad de caracteres a analizar
:type n: int
:returns: Texto modificado
:rtype: str
|
Reemplaza 'n' caracteres si son encontrados en el
analizador.
|
def solucion_c(fuente: str, analizador: dict, n: int = 2) -> str:
"""Reemplaza 'n' caracteres si son encontrados en el
analizador.
:param fuente: Texto fuente
:fuente type: str
:param analizador: Mapeo de caracteres a reemplazar
:analizador type: dict
:param n: Cantidad de caracteres a analizar
:type n: int
:returns: Texto modificado
:rtype: str
"""
return "".join(
[analizador[fuente[x:x+n]] for x in range(0, len(fuente), n)
if fuente[x:x+n] in analizador]
)
|
[
"def",
"solucion_c",
"(",
"fuente",
":",
"str",
",",
"analizador",
":",
"dict",
",",
"n",
":",
"int",
"=",
"2",
")",
"->",
"str",
":",
"return",
"\"\"",
".",
"join",
"(",
"[",
"analizador",
"[",
"fuente",
"[",
"x",
":",
"x",
"+",
"n",
"]",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"fuente",
")",
",",
"n",
")",
"if",
"fuente",
"[",
"x",
":",
"x",
"+",
"n",
"]",
"in",
"analizador",
"]",
")"
] |
[
64,
0
] |
[
80,
9
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
EAD.validar_existencia_archivo
|
(self, filename)
|
return True
|
Valida la existencia del archivo en el directorio actual
|
Valida la existencia del archivo en el directorio actual
|
def validar_existencia_archivo(self, filename):
"""Valida la existencia del archivo en el directorio actual"""
return True
|
[
"def",
"validar_existencia_archivo",
"(",
"self",
",",
"filename",
")",
":",
"return",
"True"
] |
[
42,
4
] |
[
45,
19
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_aritmetica1_2
|
(t)
|
aritmetica : lista_funciones
|
aritmetica : lista_funciones
|
def p_aritmetica1_2(t) :
'''aritmetica : lista_funciones
'''
t[0] = t[1]
|
[
"def",
"p_aritmetica1_2",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] |
[
828,
0
] |
[
831,
15
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
guardar_usuarios
|
(datos)
|
abre el json y guarda el usuario
|
abre el json y guarda el usuario
|
def guardar_usuarios(datos):
"""abre el json y guarda el usuario"""
with open(PATH_FILE, 'w') as f:
json.dump(datos, f, indent=4)
|
[
"def",
"guardar_usuarios",
"(",
"datos",
")",
":",
"with",
"open",
"(",
"PATH_FILE",
",",
"'w'",
")",
"as",
"f",
":",
"json",
".",
"dump",
"(",
"datos",
",",
"f",
",",
"indent",
"=",
"4",
")"
] |
[
21,
0
] |
[
24,
37
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
get_config_constant_file
|
()
|
return cfg
|
Contiene la obtencion del objeto config
para setear datos de constantes en archivo
configurador
:rtype: object
|
Contiene la obtencion del objeto config
para setear datos de constantes en archivo
configurador
|
def get_config_constant_file():
"""Contiene la obtencion del objeto config
para setear datos de constantes en archivo
configurador
:rtype: object
"""
# PROD
# _constants_file = "/path/to/api/prod/constants/constants.yml"
# TEST
_constants_file = "/path/to/api/test/constants/constants.yml"
cfg = Const.get_constants_file(_constants_file)
return cfg
|
[
"def",
"get_config_constant_file",
"(",
")",
":",
"# PROD",
"# _constants_file = \"/path/to/api/prod/constants/constants.yml\"",
"# TEST",
"_constants_file",
"=",
"\"/path/to/api/test/constants/constants.yml\"",
"cfg",
"=",
"Const",
".",
"get_constants_file",
"(",
"_constants_file",
")",
"return",
"cfg"
] |
[
473,
0
] |
[
488,
14
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
Hasar2GenComandos.getLastRemitNumber
|
(self)
|
Obtiene el último número de Remtio
|
Obtiene el último número de Remtio
|
def getLastRemitNumber(self):
"""Obtiene el último número de Remtio"""
pass
|
[
"def",
"getLastRemitNumber",
"(",
"self",
")",
":",
"pass"
] |
[
405,
1
] |
[
407,
6
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_x_value
|
(t)
|
x_value : cualquiercadena
| cualquiernumero
|
x_value : cualquiercadena
| cualquiernumero
|
def p_x_value(t):
''' x_value : cualquiercadena
| cualquiernumero'''
t[0] = t[1]
|
[
"def",
"p_x_value",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] |
[
571,
0
] |
[
574,
15
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
run
|
()
|
Función principal que se va a correr cuando ejecutemos el archivo
|
Función principal que se va a correr cuando ejecutemos el archivo
|
def run():
''' Función principal que se va a correr cuando ejecutemos el archivo'''
parse_home()
|
[
"def",
"run",
"(",
")",
":",
"parse_home",
"(",
")"
] |
[
102,
0
] |
[
104,
16
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
euclidean_norm
|
(p: Point2D, q: Point2D)
|
return np.linalg.norm(np.array(p) - np.array(q))
|
Calcula la distancia euclídea entre 2 puntos.
:param p: punto 1.
:param q: punto 2.
:return: distancia euclídea.
|
Calcula la distancia euclídea entre 2 puntos.
|
def euclidean_norm(p: Point2D, q: Point2D) -> float:
"""Calcula la distancia euclídea entre 2 puntos.
:param p: punto 1.
:param q: punto 2.
:return: distancia euclídea.
"""
return np.linalg.norm(np.array(p) - np.array(q))
|
[
"def",
"euclidean_norm",
"(",
"p",
":",
"Point2D",
",",
"q",
":",
"Point2D",
")",
"->",
"float",
":",
"return",
"np",
".",
"linalg",
".",
"norm",
"(",
"np",
".",
"array",
"(",
"p",
")",
"-",
"np",
".",
"array",
"(",
"q",
")",
")"
] |
[
5,
0
] |
[
12,
52
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
ExecutionDbReader.read
|
(self)
|
Función encargada de ejecutar la query y obtener los resultados de la base de datos y devolverlos en forma de
json array
Returns
-------
executions: list
lista de códigos postales de los que se extraerá la información
example:
```json
[{
"postal_code": "48005",
"base_url": "https://www.google.com/maps/place/48005+Bilbao,+Biscay/@43.2598164,-2.9304266,15z",
"types": ["Restaurants", "Bars"],
"country": "Spain""
}]
```
|
Función encargada de ejecutar la query y obtener los resultados de la base de datos y devolverlos en forma de
json array
|
def read(self):
"""Función encargada de ejecutar la query y obtener los resultados de la base de datos y devolverlos en forma de
json array
Returns
-------
executions: list
lista de códigos postales de los que se extraerá la información
example:
```json
[{
"postal_code": "48005",
"base_url": "https://www.google.com/maps/place/48005+Bilbao,+Biscay/@43.2598164,-2.9304266,15z",
"types": ["Restaurants", "Bars"],
"country": "Spain""
}]
```
"""
cursor = self.db.cursor()
executions = []
try:
cursor.execute(self._read_execution_info)
results = cursor.fetchall()
for zip_code, url, country, types in results:
executions.append({"postal_code": str(zip_code),
"base_url": url,
"types": str(types).split(","),
"country": str(country).capitalize()})
except Exception as e:
self.logger.error("something went wrong trying to retrieve execution info")
self.logger.error(str(e))
finally:
cursor.close()
return executions
|
[
"def",
"read",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"executions",
"=",
"[",
"]",
"try",
":",
"cursor",
".",
"execute",
"(",
"self",
".",
"_read_execution_info",
")",
"results",
"=",
"cursor",
".",
"fetchall",
"(",
")",
"for",
"zip_code",
",",
"url",
",",
"country",
",",
"types",
"in",
"results",
":",
"executions",
".",
"append",
"(",
"{",
"\"postal_code\"",
":",
"str",
"(",
"zip_code",
")",
",",
"\"base_url\"",
":",
"url",
",",
"\"types\"",
":",
"str",
"(",
"types",
")",
".",
"split",
"(",
"\",\"",
")",
",",
"\"country\"",
":",
"str",
"(",
"country",
")",
".",
"capitalize",
"(",
")",
"}",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"something went wrong trying to retrieve execution info\"",
")",
"self",
".",
"logger",
".",
"error",
"(",
"str",
"(",
"e",
")",
")",
"finally",
":",
"cursor",
".",
"close",
"(",
")",
"return",
"executions"
] |
[
76,
4
] |
[
109,
29
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
incrementar
|
(num,**datos)
|
Cuando se sale de la ventana se debe detener el audio
|
Cuando se sale de la ventana se debe detener el audio
|
def incrementar(num,**datos):
while (datos['inicio'].devolver()):#Cuando se oprima el botón salir
#devolver regresara un falso, mientras
#se realizará este ciclo
#print(pygame.mixer.music.get_busy())
if(pygame.mixer.music.get_busy()==0):#Pregunta si no se esta reproduciendo algo
a=datos['inicio'].devolveri()#Se obtiene del objeto de la clase ventana i y se guarda en a
'''Se analiza si el valor de i llego al tamaño del arreglo menos 1'''
if(a==len(datos['arreglo'])-1):
a=-1#Se le asigna -1 a "a"
a=a+1#Se incrementa el índice para obtener el siguiente audio
datos['inicio'].poneri(a)#Se poner el valor de i en el objeto de la clase ventana
#para que pueda ser usado por los métodos de los botones
pygame.mixer.music.load(datos['arreglo'][a])#Carga el nuevo archivo de audio
pygame.mixer.music.play()#Reproduce el audio
'''Así cuando termina de reproducirse un audio comienza el otro'''
'''Cuando se sale de la ventana se debe detener el audio'''
pygame.mixer.music.stop()#Detiene el audio
pygame.mixer.quit()
|
[
"def",
"incrementar",
"(",
"num",
",",
"*",
"*",
"datos",
")",
":",
"while",
"(",
"datos",
"[",
"'inicio'",
"]",
".",
"devolver",
"(",
")",
")",
":",
"#Cuando se oprima el botón salir",
"#devolver regresara un falso, mientras",
"#se realizará este ciclo",
"#print(pygame.mixer.music.get_busy())",
"if",
"(",
"pygame",
".",
"mixer",
".",
"music",
".",
"get_busy",
"(",
")",
"==",
"0",
")",
":",
"#Pregunta si no se esta reproduciendo algo",
"a",
"=",
"datos",
"[",
"'inicio'",
"]",
".",
"devolveri",
"(",
")",
"#Se obtiene del objeto de la clase ventana i y se guarda en a",
"'''Se analiza si el valor de i llego al tamaño del arreglo menos 1'''",
"if",
"(",
"a",
"==",
"len",
"(",
"datos",
"[",
"'arreglo'",
"]",
")",
"-",
"1",
")",
":",
"a",
"=",
"-",
"1",
"#Se le asigna -1 a \"a\"",
"a",
"=",
"a",
"+",
"1",
"#Se incrementa el índice para obtener el siguiente audio",
"datos",
"[",
"'inicio'",
"]",
".",
"poneri",
"(",
"a",
")",
"#Se poner el valor de i en el objeto de la clase ventana",
"#para que pueda ser usado por los métodos de los botones",
"pygame",
".",
"mixer",
".",
"music",
".",
"load",
"(",
"datos",
"[",
"'arreglo'",
"]",
"[",
"a",
"]",
")",
"#Carga el nuevo archivo de audio",
"pygame",
".",
"mixer",
".",
"music",
".",
"play",
"(",
")",
"#Reproduce el audio",
"'''Así cuando termina de reproducirse un audio comienza el otro'''",
"pygame",
".",
"mixer",
".",
"music",
".",
"stop",
"(",
")",
"#Detiene el audio",
"pygame",
".",
"mixer",
".",
"quit",
"(",
")"
] |
[
374,
0
] |
[
392,
23
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
InvalidDataType.__init__
|
(self, key)
|
Cuando el tipo de dato es inválido.
|
Cuando el tipo de dato es inválido.
|
def __init__(self, key):
""" Cuando el tipo de dato es inválido. """
self.key = key
|
[
"def",
"__init__",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"key",
"=",
"key"
] |
[
30,
4
] |
[
32,
22
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
Instruction.execute
|
(self)
|
recibe hijos paras el ast grafico
|
recibe hijos paras el ast grafico
|
def execute(self):
''' recibe hijos paras el ast grafico '''
pass
|
[
"def",
"execute",
"(",
"self",
")",
":",
"pass"
] |
[
6,
4
] |
[
8,
12
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_llamadaProcedimiento_o_funcion
|
(t)
|
llamadaProcedimiento_o_funcion : R_EXECUTE ID S_PARIZQ paramsList S_PARDER
| R_EXECUTE ID S_PARIZQ S_PARDER
| R_EXECUTE ID
| R_EXECUTE STRING
|
llamadaProcedimiento_o_funcion : R_EXECUTE ID S_PARIZQ paramsList S_PARDER
| R_EXECUTE ID S_PARIZQ S_PARDER
| R_EXECUTE ID
| R_EXECUTE STRING
|
def p_llamadaProcedimiento_o_funcion(t):# esta aparte porque va directo al MAIN
'''llamadaProcedimiento_o_funcion : R_EXECUTE ID S_PARIZQ paramsList S_PARDER
| R_EXECUTE ID S_PARIZQ S_PARDER
| R_EXECUTE ID
| R_EXECUTE STRING'''
repGrammar.append(t.slice)
if len(t) == 6:
t[0] = Execute(t[2], t[4], t.slice[2].lineno, t.slice[2].lexpos)
else:
t[0] = Execute(t[2], [], t.slice[2].lineno, t.slice[2].lexpos) # NO USAR EL GENERATE3D ACA porque ese se usara para manejar los excute internos en funciones y procedimientos
t[0].generate3d(None, instancia_codigo3d,True)
|
[
"def",
"p_llamadaProcedimiento_o_funcion",
"(",
"t",
")",
":",
"# esta aparte porque va directo al MAIN",
"repGrammar",
".",
"append",
"(",
"t",
".",
"slice",
")",
"if",
"len",
"(",
"t",
")",
"==",
"6",
":",
"t",
"[",
"0",
"]",
"=",
"Execute",
"(",
"t",
"[",
"2",
"]",
",",
"t",
"[",
"4",
"]",
",",
"t",
".",
"slice",
"[",
"2",
"]",
".",
"lineno",
",",
"t",
".",
"slice",
"[",
"2",
"]",
".",
"lexpos",
")",
"else",
":",
"t",
"[",
"0",
"]",
"=",
"Execute",
"(",
"t",
"[",
"2",
"]",
",",
"[",
"]",
",",
"t",
".",
"slice",
"[",
"2",
"]",
".",
"lineno",
",",
"t",
".",
"slice",
"[",
"2",
"]",
".",
"lexpos",
")",
"# NO USAR EL GENERATE3D ACA porque ese se usara para manejar los excute internos en funciones y procedimientos",
"t",
"[",
"0",
"]",
".",
"generate3d",
"(",
"None",
",",
"instancia_codigo3d",
",",
"True",
")"
] |
[
226,
0
] |
[
236,
50
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_opcion_from_1_0_0_0_1_1_0_1
|
(t)
|
opcion_from : ID opcion_sobrenombre HAVING expresion_logica ORDER BY campos_c orden PTCOMA
|
opcion_from : ID opcion_sobrenombre HAVING expresion_logica ORDER BY campos_c orden PTCOMA
|
def p_opcion_from_1_0_0_0_1_1_0_1(t):
'opcion_from : ID opcion_sobrenombre HAVING expresion_logica ORDER BY campos_c orden PTCOMA'
|
[
"def",
"p_opcion_from_1_0_0_0_1_1_0_1",
"(",
"t",
")",
":"
] |
[
1516,
0
] |
[
1517,
96
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_create_opciones
|
(t)
|
create_opciones : OWNER SIGNO_IGUAL ID
| MODE SIGNO_IGUAL NUMERO
|
create_opciones : OWNER SIGNO_IGUAL ID
| MODE SIGNO_IGUAL NUMERO
|
def p_create_opciones(t):
'''create_opciones : OWNER SIGNO_IGUAL ID
| MODE SIGNO_IGUAL NUMERO'''
|
[
"def",
"p_create_opciones",
"(",
"t",
")",
":"
] |
[
230,
0
] |
[
232,
51
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
eliminar
|
(arr: list, tmp: Any = None)
|
Elimina el elemento en la posicion media. Si el tamaño es
par, elimina el elemento previo al punto medio.
:param arr: Secuencia de elementos
:arr type: list
:param tmp: Ultimo elemento de la secuencia
:tmp type: Any
:return: Secuencia sin el elemento de la posicion media
:rtype: list
>>> eliminar([1, 2, 3])
[1, 3]
>>> eliminar([1, 2, 3, 4])
[1, 3, 4]
>>> eliminar(['x', 'y'])
['y']
>>> eliminar(['a'])
[]
|
Elimina el elemento en la posicion media. Si el tamaño es
par, elimina el elemento previo al punto medio.
|
def eliminar(arr: list, tmp: Any = None) -> list:
"""Elimina el elemento en la posicion media. Si el tamaño es
par, elimina el elemento previo al punto medio.
:param arr: Secuencia de elementos
:arr type: list
:param tmp: Ultimo elemento de la secuencia
:tmp type: Any
:return: Secuencia sin el elemento de la posicion media
:rtype: list
>>> eliminar([1, 2, 3])
[1, 3]
>>> eliminar([1, 2, 3, 4])
[1, 3, 4]
>>> eliminar(['x', 'y'])
['y']
>>> eliminar(['a'])
[]
"""
if len(arr) <= 2:
arr.pop(0)
return arr
elif len(arr) % 2 == 1:
arr.pop(len(arr)//2)
if tmp is not None:
arr.append(tmp)
return arr
else:
tmp = arr.pop(-1)
return eliminar(arr, tmp=tmp)
|
[
"def",
"eliminar",
"(",
"arr",
":",
"list",
",",
"tmp",
":",
"Any",
"=",
"None",
")",
"->",
"list",
":",
"if",
"len",
"(",
"arr",
")",
"<=",
"2",
":",
"arr",
".",
"pop",
"(",
"0",
")",
"return",
"arr",
"elif",
"len",
"(",
"arr",
")",
"%",
"2",
"==",
"1",
":",
"arr",
".",
"pop",
"(",
"len",
"(",
"arr",
")",
"//",
"2",
")",
"if",
"tmp",
"is",
"not",
"None",
":",
"arr",
".",
"append",
"(",
"tmp",
")",
"return",
"arr",
"else",
":",
"tmp",
"=",
"arr",
".",
"pop",
"(",
"-",
"1",
")",
"return",
"eliminar",
"(",
"arr",
",",
"tmp",
"=",
"tmp",
")"
] |
[
10,
0
] |
[
40,
37
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
_cargar_cajero
|
()
|
return Cajero(nombre, data)
|
Carga los datos de un cajero.
|
Carga los datos de un cajero.
|
def _cargar_cajero() -> Cajero:
"""Carga los datos de un cajero."""
data = {}
nombre = input("Ingrese el nombre del cajero: ")
for mes in MESES:
data[mes] = int_input(
f"Horas trabajadas en {mes}: ", min=0, max=240,
)
return Cajero(nombre, data)
|
[
"def",
"_cargar_cajero",
"(",
")",
"->",
"Cajero",
":",
"data",
"=",
"{",
"}",
"nombre",
"=",
"input",
"(",
"\"Ingrese el nombre del cajero: \"",
")",
"for",
"mes",
"in",
"MESES",
":",
"data",
"[",
"mes",
"]",
"=",
"int_input",
"(",
"f\"Horas trabajadas en {mes}: \"",
",",
"min",
"=",
"0",
",",
"max",
"=",
"240",
",",
")",
"return",
"Cajero",
"(",
"nombre",
",",
"data",
")"
] |
[
119,
0
] |
[
127,
31
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_select
|
(t)
|
sentencia_select : select opciones_fecha
|
sentencia_select : select opciones_fecha
|
def p_select(t):
'sentencia_select : select opciones_fecha'
node= grammer.nodoDireccion('sentencia_select')
node1 = grammer.nodoDireccion(t[1])
node.agregar(node1)
node.agregar(t[2])
t[0]=node
|
[
"def",
"p_select",
"(",
"t",
")",
":",
"node",
"=",
"grammer",
".",
"nodoDireccion",
"(",
"'sentencia_select'",
")",
"node1",
"=",
"grammer",
".",
"nodoDireccion",
"(",
"t",
"[",
"1",
"]",
")",
"node",
".",
"agregar",
"(",
"node1",
")",
"node",
".",
"agregar",
"(",
"t",
"[",
"2",
"]",
")",
"t",
"[",
"0",
"]",
"=",
"node"
] |
[
793,
0
] |
[
799,
17
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
DataCleaner.reemplazar_string
|
(self, field, replacements, sufix=None,
keep_original=False, inplace=False)
|
return series
|
Reemplaza listas de strings por un nuevo string.
A diferencias de la funcion reemplazar hace reemplazos parciales.
Args:
field (str): Campo a limpiar
replacements (dict): {"new_value": ["old_value1", "old_value2"]}
Returns:
pandas.Series: Serie de strings limpios
|
Reemplaza listas de strings por un nuevo string.
A diferencias de la funcion reemplazar hace reemplazos parciales.
|
def reemplazar_string(self, field, replacements, sufix=None,
keep_original=False, inplace=False):
"""Reemplaza listas de strings por un nuevo string.
A diferencias de la funcion reemplazar hace reemplazos parciales.
Args:
field (str): Campo a limpiar
replacements (dict): {"new_value": ["old_value1", "old_value2"]}
Returns:
pandas.Series: Serie de strings limpios
"""
sufix = sufix or self.DEFAULT_SUFIX
field = self._normalize_field(field)
series = self.df[field]
for new_value, old_values in replacements.items():
# for old_value in sorted(old_values, key=len, reverse=True):
for old_value in old_values:
replace_function = partial(self._safe_replace,
old_value=old_value,
new_value=new_value)
series = map(replace_function, series)
if inplace:
self._update_series(field=field, sufix=sufix,
keep_original=keep_original,
new_series=series)
return series
|
[
"def",
"reemplazar_string",
"(",
"self",
",",
"field",
",",
"replacements",
",",
"sufix",
"=",
"None",
",",
"keep_original",
"=",
"False",
",",
"inplace",
"=",
"False",
")",
":",
"sufix",
"=",
"sufix",
"or",
"self",
".",
"DEFAULT_SUFIX",
"field",
"=",
"self",
".",
"_normalize_field",
"(",
"field",
")",
"series",
"=",
"self",
".",
"df",
"[",
"field",
"]",
"for",
"new_value",
",",
"old_values",
"in",
"replacements",
".",
"items",
"(",
")",
":",
"# for old_value in sorted(old_values, key=len, reverse=True):",
"for",
"old_value",
"in",
"old_values",
":",
"replace_function",
"=",
"partial",
"(",
"self",
".",
"_safe_replace",
",",
"old_value",
"=",
"old_value",
",",
"new_value",
"=",
"new_value",
")",
"series",
"=",
"map",
"(",
"replace_function",
",",
"series",
")",
"if",
"inplace",
":",
"self",
".",
"_update_series",
"(",
"field",
"=",
"field",
",",
"sufix",
"=",
"sufix",
",",
"keep_original",
"=",
"keep_original",
",",
"new_series",
"=",
"series",
")",
"return",
"series"
] |
[
469,
4
] |
[
498,
21
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
table_view
|
(request, table, title)
|
return render(request, 'toshl_get/table_view.html', {
'table': table, 'title': title
})
|
Muestra una tabla y permite exportarla
|
Muestra una tabla y permite exportarla
|
def table_view(request, table, title):
''' Muestra una tabla y permite exportarla'''
# TODO: ver django-filter para filtrar los datos que se muestran en la tabla
RequestConfig(request, paginate={"per_page": 20}).configure(table)
# para exportar en formatos
export_format = request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, table)
return exporter.response("table.{}".format(export_format))
return render(request, 'toshl_get/table_view.html', {
'table': table, 'title': title
})
|
[
"def",
"table_view",
"(",
"request",
",",
"table",
",",
"title",
")",
":",
"# TODO: ver django-filter para filtrar los datos que se muestran en la tabla",
"RequestConfig",
"(",
"request",
",",
"paginate",
"=",
"{",
"\"per_page\"",
":",
"20",
"}",
")",
".",
"configure",
"(",
"table",
")",
"# para exportar en formatos",
"export_format",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"_export\"",
",",
"None",
")",
"if",
"TableExport",
".",
"is_valid_format",
"(",
"export_format",
")",
":",
"exporter",
"=",
"TableExport",
"(",
"export_format",
",",
"table",
")",
"return",
"exporter",
".",
"response",
"(",
"\"table.{}\"",
".",
"format",
"(",
"export_format",
")",
")",
"return",
"render",
"(",
"request",
",",
"'toshl_get/table_view.html'",
",",
"{",
"'table'",
":",
"table",
",",
"'title'",
":",
"title",
"}",
")"
] |
[
45,
0
] |
[
56,
6
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
NormalizarUnidadTerritorialTestCase.test_parsed_entity_level
|
(self)
|
Pluraliza una unidad territorial.
|
Pluraliza una unidad territorial.
|
def test_parsed_entity_level(self):
"""Pluraliza una unidad territorial."""
test_string = [
("provincia", "provincias"),
("departamento", "departamentos"),
("municipio", "municipios"),
("localidad", "localidades")
]
for (inp, outp) in test_string:
self.assertEqual(DataCleaner._plural_entity_level(inp), outp)
|
[
"def",
"test_parsed_entity_level",
"(",
"self",
")",
":",
"test_string",
"=",
"[",
"(",
"\"provincia\"",
",",
"\"provincias\"",
")",
",",
"(",
"\"departamento\"",
",",
"\"departamentos\"",
")",
",",
"(",
"\"municipio\"",
",",
"\"municipios\"",
")",
",",
"(",
"\"localidad\"",
",",
"\"localidades\"",
")",
"]",
"for",
"(",
"inp",
",",
"outp",
")",
"in",
"test_string",
":",
"self",
".",
"assertEqual",
"(",
"DataCleaner",
".",
"_plural_entity_level",
"(",
"inp",
")",
",",
"outp",
")"
] |
[
520,
4
] |
[
529,
73
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
cargar_personal
|
()
|
return Tienda(personal)
|
Carga los datos del personal de la tienda.
|
Carga los datos del personal de la tienda.
|
def cargar_personal() -> Tienda:
"""Carga los datos del personal de la tienda."""
personal = []
while True:
personal.append(_cargar_cajero())
if not ask_to_finish(lang="es"):
break
return Tienda(personal)
|
[
"def",
"cargar_personal",
"(",
")",
"->",
"Tienda",
":",
"personal",
"=",
"[",
"]",
"while",
"True",
":",
"personal",
".",
"append",
"(",
"_cargar_cajero",
"(",
")",
")",
"if",
"not",
"ask_to_finish",
"(",
"lang",
"=",
"\"es\"",
")",
":",
"break",
"return",
"Tienda",
"(",
"personal",
")"
] |
[
130,
0
] |
[
137,
27
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
Estante.__getitem__
|
(self, clave)
|
return self.dic.get(clave, None)
|
Retorna el elemento asignado a la clave (None si no existe).
|
Retorna el elemento asignado a la clave (None si no existe).
|
def __getitem__(self, clave):
"""Retorna el elemento asignado a la clave (None si no existe)."""
return self.dic.get(clave, None)
|
[
"def",
"__getitem__",
"(",
"self",
",",
"clave",
")",
":",
"return",
"self",
".",
"dic",
".",
"get",
"(",
"clave",
",",
"None",
")"
] |
[
29,
4
] |
[
31,
40
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
Contacto.__init__
|
(self, nombre, telefono)
|
Constructor: Inicializa propiedades de instancia.
|
Constructor: Inicializa propiedades de instancia.
|
def __init__(self, nombre, telefono):
"""Constructor: Inicializa propiedades de instancia."""
self.nombre = nombre
self.telefono = telefono
|
[
"def",
"__init__",
"(",
"self",
",",
"nombre",
",",
"telefono",
")",
":",
"self",
".",
"nombre",
"=",
"nombre",
"self",
".",
"telefono",
"=",
"telefono"
] |
[
12,
4
] |
[
15,
32
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
Url.domain_port
|
(self)
|
return netloc.split('@', 1)[-1] or None
|
Dominio con el puerto si lo hay
|
Dominio con el puerto si lo hay
|
def domain_port(self):
"""Dominio con el puerto si lo hay
"""
if not self.urlparsed:
return
netloc = self.urlparsed[1]
return netloc.split('@', 1)[-1] or None
|
[
"def",
"domain_port",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"urlparsed",
":",
"return",
"netloc",
"=",
"self",
".",
"urlparsed",
"[",
"1",
"]",
"return",
"netloc",
".",
"split",
"(",
"'@'",
",",
"1",
")",
"[",
"-",
"1",
"]",
"or",
"None"
] |
[
79,
4
] |
[
85,
47
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_con_drop
|
(t)
|
con_drop : column identificador
| constraint identificador
|
con_drop : column identificador
| constraint identificador
|
def p_con_drop(t):
'''con_drop : column identificador
| constraint identificador '''
node = grammer.nodoDireccion('con_drop')
node1 = grammer.nodoDireccion(t[1])
node2 = grammer.nodoDireccion(t[2])
node.agregar(node1)
node.agregar(node2)
t[0] = node
|
[
"def",
"p_con_drop",
"(",
"t",
")",
":",
"node",
"=",
"grammer",
".",
"nodoDireccion",
"(",
"'con_drop'",
")",
"node1",
"=",
"grammer",
".",
"nodoDireccion",
"(",
"t",
"[",
"1",
"]",
")",
"node2",
"=",
"grammer",
".",
"nodoDireccion",
"(",
"t",
"[",
"2",
"]",
")",
"node",
".",
"agregar",
"(",
"node1",
")",
"node",
".",
"agregar",
"(",
"node2",
")",
"t",
"[",
"0",
"]",
"=",
"node"
] |
[
606,
0
] |
[
614,
19
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_funciones42
|
(p)
|
funciones : FACTORIAL PABRE expresion PCIERRA
|
funciones : FACTORIAL PABRE expresion PCIERRA
|
def p_funciones42(p):
'funciones : FACTORIAL PABRE expresion PCIERRA'
|
[
"def",
"p_funciones42",
"(",
"p",
")",
":"
] |
[
424,
0
] |
[
425,
51
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
get_notifications
|
(user)
|
return mensajes
|
Obtener los mensajes no leidos del usuario
|
Obtener los mensajes no leidos del usuario
|
def get_notifications(user):
""" Obtener los mensajes no leidos del usuario """
if user.is_authenticated:
mensajes = MensajeDestinado.objects.filter(
destinatario=user,
estado=MensajeDestinado.CREATED
)
else:
mensajes = []
return mensajes
|
[
"def",
"get_notifications",
"(",
"user",
")",
":",
"if",
"user",
".",
"is_authenticated",
":",
"mensajes",
"=",
"MensajeDestinado",
".",
"objects",
".",
"filter",
"(",
"destinatario",
"=",
"user",
",",
"estado",
"=",
"MensajeDestinado",
".",
"CREATED",
")",
"else",
":",
"mensajes",
"=",
"[",
"]",
"return",
"mensajes"
] |
[
12,
0
] |
[
21,
19
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
custom_cleaning_after_rules
|
(dc)
|
Script de limpieza custom para aplicar al objeto después de las reglas.
Args:
dc (DataCleaner): Objeto data cleaner con datos cargados.
|
Script de limpieza custom para aplicar al objeto después de las reglas.
|
def custom_cleaning_after_rules(dc):
"""Script de limpieza custom para aplicar al objeto después de las reglas.
Args:
dc (DataCleaner): Objeto data cleaner con datos cargados.
"""
pass
|
[
"def",
"custom_cleaning_after_rules",
"(",
"dc",
")",
":",
"pass"
] |
[
58,
0
] |
[
64,
8
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
BcraLiborScraperTestCase.test_libor_configuration_has_rates
|
(self)
|
Validar la existencia de la clave rates dentro de
la configuración de libor
|
Validar la existencia de la clave rates dentro de
la configuración de libor
|
def test_libor_configuration_has_rates(self):
"""Validar la existencia de la clave rates dentro de
la configuración de libor"""
dict_config = {'libor': {'foo': 'bar'}}
with mock.patch(
'builtins.open',
return_value=io.StringIO(json.dumps(dict_config))
):
with self.assertRaises(InvalidConfigurationError):
config = read_config("config_general.json", "libor")
validate_libor_rates_config(config)
|
[
"def",
"test_libor_configuration_has_rates",
"(",
"self",
")",
":",
"dict_config",
"=",
"{",
"'libor'",
":",
"{",
"'foo'",
":",
"'bar'",
"}",
"}",
"with",
"mock",
".",
"patch",
"(",
"'builtins.open'",
",",
"return_value",
"=",
"io",
".",
"StringIO",
"(",
"json",
".",
"dumps",
"(",
"dict_config",
")",
")",
")",
":",
"with",
"self",
".",
"assertRaises",
"(",
"InvalidConfigurationError",
")",
":",
"config",
"=",
"read_config",
"(",
"\"config_general.json\"",
",",
"\"libor\"",
")",
"validate_libor_rates_config",
"(",
"config",
")"
] |
[
624,
4
] |
[
636,
51
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
parse_json_recursively
|
(json_object)
|
funcion recursiva que permite obtener el clave-valor
mas anida en el subjson
|
funcion recursiva que permite obtener el clave-valor
mas anida en el subjson
|
def parse_json_recursively(json_object):
"""funcion recursiva que permite obtener el clave-valor
mas anida en el subjson
"""
if type(json_object) is dict and json_object:
for key in json_object:
if type(json_object[key]) is str and json_object:
# print("{}: {}".format(key, json_object[key]))
dt[key] = json_object[key]
parse_json_recursively(json_object[key])
elif type(json_object) is list and json_object:
for item in json_object:
parse_json_recursively(item)
|
[
"def",
"parse_json_recursively",
"(",
"json_object",
")",
":",
"if",
"type",
"(",
"json_object",
")",
"is",
"dict",
"and",
"json_object",
":",
"for",
"key",
"in",
"json_object",
":",
"if",
"type",
"(",
"json_object",
"[",
"key",
"]",
")",
"is",
"str",
"and",
"json_object",
":",
"# print(\"{}: {}\".format(key, json_object[key]))",
"dt",
"[",
"key",
"]",
"=",
"json_object",
"[",
"key",
"]",
"parse_json_recursively",
"(",
"json_object",
"[",
"key",
"]",
")",
"elif",
"type",
"(",
"json_object",
")",
"is",
"list",
"and",
"json_object",
":",
"for",
"item",
"in",
"json_object",
":",
"parse_json_recursively",
"(",
"item",
")"
] |
[
3,
0
] |
[
16,
40
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
F2s_Estado
|
(tarea)
|
return salida
|
Mira el esado de la tarea genereada
|
Mira el esado de la tarea genereada
|
def F2s_Estado(tarea):
'''Mira el esado de la tarea genereada'''
detener=False
if tarea == None:
salida = '<div class="progress">'
detener=True
else:
buscar=db(db.tbl_control_maestro.id==tarea).select(db.tbl_control_maestro.estado).first()
if buscar.estado == "I":
salida='<div class="progress">'
salida += '<div class="progress-bar text-dark progress-bar-striped bg-warning" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"><b>CARGANDO</b></div>'
salida += '</div>'
elif buscar.estado == "A":
salida='<div class="progress">'
salida += '<div class="progress-bar progress-bar-striped bg-success" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>'
salida += '<div class="progress-bar text-dark progress-bar-striped bg-warning" role="progressbar" style="width: 25%" aria-valuenow="5" aria-valuemin="0" aria-valuemax="100"><b>PROCESANDO</b></div>'
salida += '</div>'
elif buscar.estado == "P":
salida = '<div class="progress">'
salida += '<div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>'
salida += '<div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" style="width: 25%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>'
salida += '<div class="progress-bar text-dark progress-bar-striped progress-bar-animated bg-warning" role="progressbar bg-warning" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"><b>GRABANDO</b></div>'
salida += '</div>'
if buscar.estado == "F":
detener=True
salida ='<div class="progress">'
salida +='<div class="progress-bar progress-bar-animated progress-bar-striped bg-success" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>'
salida +='<div class="progress-bar progress-bar-animated progress-bar-striped bg-success" role="progressbar" style="width: 25%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>'
salida +='<div class="progress-bar progress-bar-animated progress-bar-striped bg-success" role="progressbar" style="width: 25%" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"></div>'
salida +='<div class="progress-bar text-dark progress-bar-animated progress-bar-striped bg-success" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"><B>FINALIZADO</B></div>'
salida +='</div>'
salida +='<br>'
if buscar.estado == "E":
detener=True
salida ='<div class="progress">'
salida +='<div class="progress-bar text-dark progress-bar-animated progress-bar-striped bg-danger" role="progressbar" style="width: 100%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"><B>Error!!</B></div>'
salida +='</div>'
salida +='<br>'
salida="$('#progreso').html('{}');".format(XML(salida))
if detener: salida +="Detener();"
return salida
|
[
"def",
"F2s_Estado",
"(",
"tarea",
")",
":",
"detener",
"=",
"False",
"if",
"tarea",
"==",
"None",
":",
"salida",
"=",
"'<div class=\"progress\">'",
"detener",
"=",
"True",
"else",
":",
"buscar",
"=",
"db",
"(",
"db",
".",
"tbl_control_maestro",
".",
"id",
"==",
"tarea",
")",
".",
"select",
"(",
"db",
".",
"tbl_control_maestro",
".",
"estado",
")",
".",
"first",
"(",
")",
"if",
"buscar",
".",
"estado",
"==",
"\"I\"",
":",
"salida",
"=",
"'<div class=\"progress\">'",
"salida",
"+=",
"'<div class=\"progress-bar text-dark progress-bar-striped bg-warning\" role=\"progressbar\" style=\"width: 25%\" aria-valuenow=\"25\" aria-valuemin=\"0\" aria-valuemax=\"100\"><b>CARGANDO</b></div>'",
"salida",
"+=",
"'</div>'",
"elif",
"buscar",
".",
"estado",
"==",
"\"A\"",
":",
"salida",
"=",
"'<div class=\"progress\">'",
"salida",
"+=",
"'<div class=\"progress-bar progress-bar-striped bg-success\" role=\"progressbar\" style=\"width: 25%\" aria-valuenow=\"25\" aria-valuemin=\"0\" aria-valuemax=\"100\"></div>'",
"salida",
"+=",
"'<div class=\"progress-bar text-dark progress-bar-striped bg-warning\" role=\"progressbar\" style=\"width: 25%\" aria-valuenow=\"5\" aria-valuemin=\"0\" aria-valuemax=\"100\"><b>PROCESANDO</b></div>'",
"salida",
"+=",
"'</div>'",
"elif",
"buscar",
".",
"estado",
"==",
"\"P\"",
":",
"salida",
"=",
"'<div class=\"progress\">'",
"salida",
"+=",
"'<div class=\"progress-bar progress-bar-striped progress-bar-animated bg-success\" role=\"progressbar\" style=\"width: 25%\" aria-valuenow=\"25\" aria-valuemin=\"0\" aria-valuemax=\"100\"></div>'",
"salida",
"+=",
"'<div class=\"progress-bar progress-bar-striped progress-bar-animated bg-success\" role=\"progressbar\" style=\"width: 25%\" aria-valuenow=\"50\" aria-valuemin=\"0\" aria-valuemax=\"100\"></div>'",
"salida",
"+=",
"'<div class=\"progress-bar text-dark progress-bar-striped progress-bar-animated bg-warning\" role=\"progressbar bg-warning\" style=\"width: 25%\" aria-valuenow=\"25\" aria-valuemin=\"0\" aria-valuemax=\"100\"><b>GRABANDO</b></div>'",
"salida",
"+=",
"'</div>'",
"if",
"buscar",
".",
"estado",
"==",
"\"F\"",
":",
"detener",
"=",
"True",
"salida",
"=",
"'<div class=\"progress\">'",
"salida",
"+=",
"'<div class=\"progress-bar progress-bar-animated progress-bar-striped bg-success\" role=\"progressbar\" style=\"width: 25%\" aria-valuenow=\"25\" aria-valuemin=\"0\" aria-valuemax=\"100\"></div>'",
"salida",
"+=",
"'<div class=\"progress-bar progress-bar-animated progress-bar-striped bg-success\" role=\"progressbar\" style=\"width: 25%\" aria-valuenow=\"50\" aria-valuemin=\"0\" aria-valuemax=\"100\"></div>'",
"salida",
"+=",
"'<div class=\"progress-bar progress-bar-animated progress-bar-striped bg-success\" role=\"progressbar\" style=\"width: 25%\" aria-valuenow=\"75\" aria-valuemin=\"0\" aria-valuemax=\"100\"></div>'",
"salida",
"+=",
"'<div class=\"progress-bar text-dark progress-bar-animated progress-bar-striped bg-success\" role=\"progressbar\" style=\"width: 25%\" aria-valuenow=\"25\" aria-valuemin=\"0\" aria-valuemax=\"100\"><B>FINALIZADO</B></div>'",
"salida",
"+=",
"'</div>'",
"salida",
"+=",
"'<br>'",
"if",
"buscar",
".",
"estado",
"==",
"\"E\"",
":",
"detener",
"=",
"True",
"salida",
"=",
"'<div class=\"progress\">'",
"salida",
"+=",
"'<div class=\"progress-bar text-dark progress-bar-animated progress-bar-striped bg-danger\" role=\"progressbar\" style=\"width: 100%\" aria-valuenow=\"25\" aria-valuemin=\"0\" aria-valuemax=\"100\"><B>Error!!</B></div>'",
"salida",
"+=",
"'</div>'",
"salida",
"+=",
"'<br>'",
"salida",
"=",
"\"$('#progreso').html('{}');\"",
".",
"format",
"(",
"XML",
"(",
"salida",
")",
")",
"if",
"detener",
":",
"salida",
"+=",
"\"Detener();\"",
"return",
"salida"
] |
[
326,
0
] |
[
367,
17
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
validar_correo
|
(usuario: str, dominio: str = '@calufa.com')
|
return False
|
Función que valida si un correo electrónico pertenece al dominio
calufa.com
:param usuario: correo electrónico a validar
:type usuario: str
:param dominio: dominio a validar
:type dominio: str
:return: True si pertenece al dominio calufa.com, False si no
:rtype: bool
|
Función que valida si un correo electrónico pertenece al dominio
calufa.com
|
def validar_correo(usuario: str, dominio: str = '@calufa.com') -> bool:
"""Función que valida si un correo electrónico pertenece al dominio
calufa.com
:param usuario: correo electrónico a validar
:type usuario: str
:param dominio: dominio a validar
:type dominio: str
:return: True si pertenece al dominio calufa.com, False si no
:rtype: bool
"""
if usuario.endswith(dominio):
return True
return False
|
[
"def",
"validar_correo",
"(",
"usuario",
":",
"str",
",",
"dominio",
":",
"str",
"=",
"'@calufa.com'",
")",
"->",
"bool",
":",
"if",
"usuario",
".",
"endswith",
"(",
"dominio",
")",
":",
"return",
"True",
"return",
"False"
] |
[
12,
0
] |
[
25,
16
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
TrackingVideo.properties
|
(self)
|
return self._properties
|
Devuelve la lista de propiedades.
:return: diccionario con las propiedades.
|
Devuelve la lista de propiedades.
|
def properties(self) -> Dict[TrackingVideoProperty, Any]:
"""Devuelve la lista de propiedades.
:return: diccionario con las propiedades.
"""
return self._properties
|
[
"def",
"properties",
"(",
"self",
")",
"->",
"Dict",
"[",
"TrackingVideoProperty",
",",
"Any",
"]",
":",
"return",
"self",
".",
"_properties"
] |
[
367,
4
] |
[
372,
31
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_propcol2
|
(p)
|
propcol : propiedadescol
|
propcol : propiedadescol
|
def p_propcol2(p):
"propcol : propiedadescol"
p[0] = p[1]
|
[
"def",
"p_propcol2",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] |
[
364,
0
] |
[
366,
15
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
oto_glosser
|
(word_list, tags, pos_tags=[], corpus_row=0)
|
return glossed_phrase
|
Funcion que glosa dadas las etiquetas
Esta funcion se encarga de etiquetar una lista de palabras en
otomi dadas las etiquetas en formato BIO-Label. El etiquetado
se realiza con la siguiente estructura para cada palabra:
[[<chunk-word>, <tag>], [<chunk-word>, <tag>], ..., <POS tag>]
|
Funcion que glosa dadas las etiquetas
Esta funcion se encarga de etiquetar una lista de palabras en
otomi dadas las etiquetas en formato BIO-Label. El etiquetado
se realiza con la siguiente estructura para cada palabra:
[[<chunk-word>, <tag>], [<chunk-word>, <tag>], ..., <POS tag>]
|
def oto_glosser(word_list, tags, pos_tags=[], corpus_row=0):
"""Funcion que glosa dadas las etiquetas
Esta funcion se encarga de etiquetar una lista de palabras en
otomi dadas las etiquetas en formato BIO-Label. El etiquetado
se realiza con la siguiente estructura para cada palabra:
[[<chunk-word>, <tag>], [<chunk-word>, <tag>], ..., <POS tag>]
"""
phrase_len, word_len, i = 0, 0, 0
chunk = ''
glossed_words, glossed_phrase = [], []
letters = ''.join(word_list)
for tag, letter in zip(tags, letters):
if tag.startswith("B"):
if chunk:
try:
glossed_words.append([chunk, current_tag[2:]])
except UnboundLocalError:
# TODO: Tratar caso cuando glosa predicha es incorrecta
# EJ. Inicia con I-tag y no con B-tag
print(f"Wrong BIO-label secuence:")
print("BIO-labels:", tags)
print("Sentence:", word_list)
return [f"ERROR AT {corpus_row}"]
if len(word_list[i]) == word_len:
# Adding POS tag
#TODO: Adecuarla para que reciba una lista de etiquetas POS
glossed_words.append(pos_tags[i][-1])
# Forming phrase structure
glossed_phrase.append(glossed_words)
# Next word
i += 1
# New word
word_len = 0
# New glossed word structure
glossed_words = []
chunk = letter
phrase_len += 1
word_len += 1
current_tag = tag
elif tag.startswith("I"):
chunk += letter
phrase_len += 1
word_len += 1
if len(letters) == phrase_len:
glossed_words.append([chunk, current_tag[2:]])
glossed_words.append(pos_tags[i][-1])
glossed_phrase.append(glossed_words)
return glossed_phrase
|
[
"def",
"oto_glosser",
"(",
"word_list",
",",
"tags",
",",
"pos_tags",
"=",
"[",
"]",
",",
"corpus_row",
"=",
"0",
")",
":",
"phrase_len",
",",
"word_len",
",",
"i",
"=",
"0",
",",
"0",
",",
"0",
"chunk",
"=",
"''",
"glossed_words",
",",
"glossed_phrase",
"=",
"[",
"]",
",",
"[",
"]",
"letters",
"=",
"''",
".",
"join",
"(",
"word_list",
")",
"for",
"tag",
",",
"letter",
"in",
"zip",
"(",
"tags",
",",
"letters",
")",
":",
"if",
"tag",
".",
"startswith",
"(",
"\"B\"",
")",
":",
"if",
"chunk",
":",
"try",
":",
"glossed_words",
".",
"append",
"(",
"[",
"chunk",
",",
"current_tag",
"[",
"2",
":",
"]",
"]",
")",
"except",
"UnboundLocalError",
":",
"# TODO: Tratar caso cuando glosa predicha es incorrecta",
"# EJ. Inicia con I-tag y no con B-tag",
"print",
"(",
"f\"Wrong BIO-label secuence:\"",
")",
"print",
"(",
"\"BIO-labels:\"",
",",
"tags",
")",
"print",
"(",
"\"Sentence:\"",
",",
"word_list",
")",
"return",
"[",
"f\"ERROR AT {corpus_row}\"",
"]",
"if",
"len",
"(",
"word_list",
"[",
"i",
"]",
")",
"==",
"word_len",
":",
"# Adding POS tag",
"#TODO: Adecuarla para que reciba una lista de etiquetas POS",
"glossed_words",
".",
"append",
"(",
"pos_tags",
"[",
"i",
"]",
"[",
"-",
"1",
"]",
")",
"# Forming phrase structure",
"glossed_phrase",
".",
"append",
"(",
"glossed_words",
")",
"# Next word",
"i",
"+=",
"1",
"# New word",
"word_len",
"=",
"0",
"# New glossed word structure",
"glossed_words",
"=",
"[",
"]",
"chunk",
"=",
"letter",
"phrase_len",
"+=",
"1",
"word_len",
"+=",
"1",
"current_tag",
"=",
"tag",
"elif",
"tag",
".",
"startswith",
"(",
"\"I\"",
")",
":",
"chunk",
"+=",
"letter",
"phrase_len",
"+=",
"1",
"word_len",
"+=",
"1",
"if",
"len",
"(",
"letters",
")",
"==",
"phrase_len",
":",
"glossed_words",
".",
"append",
"(",
"[",
"chunk",
",",
"current_tag",
"[",
"2",
":",
"]",
"]",
")",
"glossed_words",
".",
"append",
"(",
"pos_tags",
"[",
"i",
"]",
"[",
"-",
"1",
"]",
")",
"glossed_phrase",
".",
"append",
"(",
"glossed_words",
")",
"return",
"glossed_phrase"
] |
[
100,
0
] |
[
149,
25
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
calcular_precio
|
(tipo: str, cantidad: int)
|
return precio, iva, precio + iva
|
Calcula el precio de la compra de boletos.
:param tipo: tipo de boleto
:tipo type: str
:param cantidad: número de boletos
:tipo type: int
:return: precio, iva, total
:rtype: tuple
|
Calcula el precio de la compra de boletos.
:param tipo: tipo de boleto
:tipo type: str
:param cantidad: número de boletos
:tipo type: int
:return: precio, iva, total
:rtype: tuple
|
def calcular_precio(tipo: str, cantidad: int):
"""Calcula el precio de la compra de boletos.
:param tipo: tipo de boleto
:tipo type: str
:param cantidad: número de boletos
:tipo type: int
:return: precio, iva, total
:rtype: tuple
"""
precio = cantidad * TIPO[tipo]
iva = precio * IVA
return precio, iva, precio + iva
|
[
"def",
"calcular_precio",
"(",
"tipo",
":",
"str",
",",
"cantidad",
":",
"int",
")",
":",
"precio",
"=",
"cantidad",
"*",
"TIPO",
"[",
"tipo",
"]",
"iva",
"=",
"precio",
"*",
"IVA",
"return",
"precio",
",",
"iva",
",",
"precio",
"+",
"iva"
] |
[
50,
0
] |
[
62,
36
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_funciones10
|
(t)
|
instruccion : CREATE FUNCTION IDENTIFICADOR PAR1 listid PAR2 AS DOLLAR DOLLAR BEGIN contenidosbegin END PYC DOLLAR DOLLAR LANGUAGE IDENTIFICADOR PYC
|
instruccion : CREATE FUNCTION IDENTIFICADOR PAR1 listid PAR2 AS DOLLAR DOLLAR BEGIN contenidosbegin END PYC DOLLAR DOLLAR LANGUAGE IDENTIFICADOR PYC
|
def p_funciones10(t):
'''instruccion : CREATE FUNCTION IDENTIFICADOR PAR1 listid PAR2 AS DOLLAR DOLLAR BEGIN contenidosbegin END PYC DOLLAR DOLLAR LANGUAGE IDENTIFICADOR PYC'''
instru = grammer.nodoGramatical('instruccion')
instru.agregarDetalle('::= CREATE FUNCTION IDENTIFICADOR PAR1 listid PAR2 AS DOLLAR DOLLAR BEGIN contenidosbegin END PYC DOLLAR DOLLAR LANGUAGE IDENTIFICADOR PYC')
listGrammer.insert(0,instru)
|
[
"def",
"p_funciones10",
"(",
"t",
")",
":",
"instru",
"=",
"grammer",
".",
"nodoGramatical",
"(",
"'instruccion'",
")",
"instru",
".",
"agregarDetalle",
"(",
"'::= CREATE FUNCTION IDENTIFICADOR PAR1 listid PAR2 AS DOLLAR DOLLAR BEGIN contenidosbegin END PYC DOLLAR DOLLAR LANGUAGE IDENTIFICADOR PYC'",
")",
"listGrammer",
".",
"insert",
"(",
"0",
",",
"instru",
")"
] |
[
129,
0
] |
[
133,
32
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_instrucciones
|
(t)
|
instrucciones : instruccion produc_a
|
instrucciones : instruccion produc_a
|
def p_instrucciones(t):
'instrucciones : instruccion produc_a'
|
[
"def",
"p_instrucciones",
"(",
"t",
")",
":"
] |
[
214,
0
] |
[
215,
46
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
sueldo_
|
(cargo)
|
return sueldos.get(cargo, None)
|
Devuelve el sueldo acorde al cargo del trabajador.
:param cargo: Cargo del trabajador.
:cargo type: str
:return: Sueldo del trabajador
:rtype: int
>>> sueldo_("ejecutivo")
90
|
Devuelve el sueldo acorde al cargo del trabajador.
|
def sueldo_(cargo):
"""Devuelve el sueldo acorde al cargo del trabajador.
:param cargo: Cargo del trabajador.
:cargo type: str
:return: Sueldo del trabajador
:rtype: int
>>> sueldo_("ejecutivo")
90
"""
cargo = cargo.capitalize()
sueldos = {
"Externo": 50,
"Ejecutivo": 90,
"Jefe": 100
}
return sueldos.get(cargo, None)
|
[
"def",
"sueldo_",
"(",
"cargo",
")",
":",
"cargo",
"=",
"cargo",
".",
"capitalize",
"(",
")",
"sueldos",
"=",
"{",
"\"Externo\"",
":",
"50",
",",
"\"Ejecutivo\"",
":",
"90",
",",
"\"Jefe\"",
":",
"100",
"}",
"return",
"sueldos",
".",
"get",
"(",
"cargo",
",",
"None",
")"
] |
[
50,
0
] |
[
67,
35
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
Grid.wrap_y
|
(self, y)
|
return self._wrap_functions[1](y)
|
Wraps a y coordinate.
y -- Y Coordinate.
|
Wraps a y coordinate.
|
def wrap_y(self, y):
"""Wraps a y coordinate.
y -- Y Coordinate.
"""
return self._wrap_functions[1](y)
|
[
"def",
"wrap_y",
"(",
"self",
",",
"y",
")",
":",
"return",
"self",
".",
"_wrap_functions",
"[",
"1",
"]",
"(",
"y",
")"
] |
[
99,
4
] |
[
106,
41
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
generar_contrasena
|
()
|
return contrasena
|
generar_contraseña es una funcion que contiene listas
Las cuales se unifican en otra lista llamada caracteres
en la cual en el ciclo for se genera una contraseña aleatoria de 10 caracteres
donde el modulo random elije los caracteres y los inserta en una nueva lista la cual
Returns:
str contrasena: devuelve contraseña o contraseñas dependiendo del valor que tenga range
|
generar_contraseña es una funcion que contiene listas
Las cuales se unifican en otra lista llamada caracteres
en la cual en el ciclo for se genera una contraseña aleatoria de 10 caracteres
donde el modulo random elije los caracteres y los inserta en una nueva lista la cual
Returns:
str contrasena: devuelve contraseña o contraseñas dependiendo del valor que tenga range
|
def generar_contrasena():
"""generar_contraseña es una funcion que contiene listas
Las cuales se unifican en otra lista llamada caracteres
en la cual en el ciclo for se genera una contraseña aleatoria de 10 caracteres
donde el modulo random elije los caracteres y los inserta en una nueva lista la cual
Returns:
str contrasena: devuelve contraseña o contraseñas dependiendo del valor que tenga range
"""
mayusculas = ['A', 'B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
minusculas = ['a', 'b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
simbolos = ['!','"','#','$','%','&','/','(',')','=','?','*','[',']','{','}','_','-',':',';',',','.','|','^','~']
numeros = ['1','2','3','4','5','6','7','8','9','0']
caracteres = mayusculas + minusculas + numeros + simbolos
contrasena = []
for i in range(numero_caracteres):#Dato dado por el usuario
caracter_random = random.choice(caracteres)
contrasena.append(caracter_random)
contrasena = "".join(contrasena)
return contrasena
|
[
"def",
"generar_contrasena",
"(",
")",
":",
"mayusculas",
"=",
"[",
"'A'",
",",
"'B'",
",",
"'C'",
",",
"'D'",
",",
"'E'",
",",
"'F'",
",",
"'G'",
",",
"'H'",
",",
"'I'",
",",
"'J'",
",",
"'K'",
",",
"'L'",
",",
"'M'",
",",
"'N'",
",",
"'O'",
",",
"'P'",
",",
"'Q'",
",",
"'R'",
",",
"'S'",
",",
"'T'",
",",
"'U'",
",",
"'V'",
",",
"'W'",
",",
"'X'",
",",
"'Y'",
",",
"'Z'",
"]",
"minusculas",
"=",
"[",
"'a'",
",",
"'b'",
",",
"'c'",
",",
"'d'",
",",
"'e'",
",",
"'f'",
",",
"'g'",
",",
"'h'",
",",
"'i'",
",",
"'j'",
",",
"'k'",
",",
"'l'",
",",
"'m'",
",",
"'n'",
",",
"'o'",
",",
"'p'",
",",
"'q'",
",",
"'r'",
",",
"'s'",
",",
"'t'",
",",
"'u'",
",",
"'v'",
",",
"'w'",
",",
"'x'",
",",
"'y'",
",",
"'z'",
"]",
"simbolos",
"=",
"[",
"'!'",
",",
"'\"'",
",",
"'#'",
",",
"'$'",
",",
"'%'",
",",
"'&'",
",",
"'/'",
",",
"'('",
",",
"')'",
",",
"'='",
",",
"'?'",
",",
"'*'",
",",
"'['",
",",
"']'",
",",
"'{'",
",",
"'}'",
",",
"'_'",
",",
"'-'",
",",
"':'",
",",
"';'",
",",
"','",
",",
"'.'",
",",
"'|'",
",",
"'^'",
",",
"'~'",
"]",
"numeros",
"=",
"[",
"'1'",
",",
"'2'",
",",
"'3'",
",",
"'4'",
",",
"'5'",
",",
"'6'",
",",
"'7'",
",",
"'8'",
",",
"'9'",
",",
"'0'",
"]",
"caracteres",
"=",
"mayusculas",
"+",
"minusculas",
"+",
"numeros",
"+",
"simbolos",
"contrasena",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"numero_caracteres",
")",
":",
"#Dato dado por el usuario",
"caracter_random",
"=",
"random",
".",
"choice",
"(",
"caracteres",
")",
"contrasena",
".",
"append",
"(",
"caracter_random",
")",
"contrasena",
"=",
"\"\"",
".",
"join",
"(",
"contrasena",
")",
"return",
"contrasena"
] |
[
12,
0
] |
[
33,
21
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
md
|
(pieza)
|
crea los id de las tuplas con un hash
|
crea los id de las tuplas con un hash
|
def md(pieza):
"""crea los id de las tuplas con un hash"""
try:
r = hashlib.md5(pieza)
return str(r.hexdigest())
except:
return None
|
[
"def",
"md",
"(",
"pieza",
")",
":",
"try",
":",
"r",
"=",
"hashlib",
".",
"md5",
"(",
"pieza",
")",
"return",
"str",
"(",
"r",
".",
"hexdigest",
"(",
")",
")",
"except",
":",
"return",
"None"
] |
[
75,
0
] |
[
81,
19
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
mostrar
|
(resultado: List[str])
|
Muestra los vehículos en pantalla.
:param resultado: lista de vehículos filtrados
:resultado type: List[str]
:rtype: None
|
Muestra los vehículos en pantalla.
|
def mostrar(resultado: List[str]) -> None:
"""Muestra los vehículos en pantalla.
:param resultado: lista de vehículos filtrados
:resultado type: List[str]
:rtype: None
"""
print(*resultado, sep="\n")
|
[
"def",
"mostrar",
"(",
"resultado",
":",
"List",
"[",
"str",
"]",
")",
"->",
"None",
":",
"print",
"(",
"*",
"resultado",
",",
"sep",
"=",
"\"\\n\"",
")"
] |
[
37,
0
] |
[
44,
31
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
TrackedObjects._next_uid
|
(self)
|
return self._next_uid
|
Devuelve el uid siguiente para asignar.
:return: identificador único siguiente.
|
Devuelve el uid siguiente para asignar.
|
def _next_uid(self) -> int:
"""Devuelve el uid siguiente para asignar.
:return: identificador único siguiente.
"""
return self._next_uid
|
[
"def",
"_next_uid",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_next_uid"
] |
[
352,
4
] |
[
357,
29
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
Estante.keys
|
(self)
|
return list(self.dic.keys())
|
Retorna una lista con las claves del diccionario.
|
Retorna una lista con las claves del diccionario.
|
def keys(self):
"""Retorna una lista con las claves del diccionario."""
return list(self.dic.keys())
|
[
"def",
"keys",
"(",
"self",
")",
":",
"return",
"list",
"(",
"self",
".",
"dic",
".",
"keys",
"(",
")",
")"
] |
[
59,
4
] |
[
61,
36
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_metodos2
|
(t)
|
METODOS : id para EXP parc
|
METODOS : id para EXP parc
|
def p_metodos2(t):
'''METODOS : id para EXP parc
'''
print("METODOS")
|
[
"def",
"p_metodos2",
"(",
"t",
")",
":",
"print",
"(",
"\"METODOS\"",
")"
] |
[
279,
0
] |
[
282,
20
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
cantidad
|
(participantes: List[Tuple[str, str, int]])
|
return {
categoria: len([p for p in participantes if p[3] == categoria])
for categoria in CATEGORIAS
}
|
Calcula la cantidad de participantes por categoría.
:param participantes: lista de participantes.
:participantes type: List[Tuple[str, str, int]]
:return: cantidad de participantes por categoría (diccionario).
:rtype: Dict[str, int]
|
Calcula la cantidad de participantes por categoría.
|
def cantidad(participantes: List[Tuple[str, str, int]]) -> Dict[str, int]:
"""Calcula la cantidad de participantes por categoría.
:param participantes: lista de participantes.
:participantes type: List[Tuple[str, str, int]]
:return: cantidad de participantes por categoría (diccionario).
:rtype: Dict[str, int]
"""
return {
categoria: len([p for p in participantes if p[3] == categoria])
for categoria in CATEGORIAS
}
|
[
"def",
"cantidad",
"(",
"participantes",
":",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
",",
"int",
"]",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"int",
"]",
":",
"return",
"{",
"categoria",
":",
"len",
"(",
"[",
"p",
"for",
"p",
"in",
"participantes",
"if",
"p",
"[",
"3",
"]",
"==",
"categoria",
"]",
")",
"for",
"categoria",
"in",
"CATEGORIAS",
"}"
] |
[
49,
0
] |
[
60,
5
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_inst_generales_ins2
|
(t)
|
instrucciones_generales : instruccion2
|
instrucciones_generales : instruccion2
|
def p_inst_generales_ins2(t):
'''instrucciones_generales : instruccion2'''
arr = []
arr.append(t[1])
#print('Valor del arr -> ' + str(arr))
t[0] = arr
|
[
"def",
"p_inst_generales_ins2",
"(",
"t",
")",
":",
"arr",
"=",
"[",
"]",
"arr",
".",
"append",
"(",
"t",
"[",
"1",
"]",
")",
"#print('Valor del arr -> ' + str(arr))",
"t",
"[",
"0",
"]",
"=",
"arr"
] |
[
2268,
0
] |
[
2273,
14
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
fibonacci_for
|
(n: int)
|
return secuencia
|
Genera la secuencia de Fibonacci de 'n' elementos.
:param n: cantidad de elementos de la secuencia
:n type: int
:return: secuencia de Fibonacci
:rtype: List[int]
|
Genera la secuencia de Fibonacci de 'n' elementos.
|
def fibonacci_for(n: int) -> List[int]:
"""Genera la secuencia de Fibonacci de 'n' elementos.
:param n: cantidad de elementos de la secuencia
:n type: int
:return: secuencia de Fibonacci
:rtype: List[int]
"""
secuencia = [0, 1]
for i in range(2, n):
secuencia.append(secuencia[i - 1] + secuencia[i - 2])
return secuencia
|
[
"def",
"fibonacci_for",
"(",
"n",
":",
"int",
")",
"->",
"List",
"[",
"int",
"]",
":",
"secuencia",
"=",
"[",
"0",
",",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"n",
")",
":",
"secuencia",
".",
"append",
"(",
"secuencia",
"[",
"i",
"-",
"1",
"]",
"+",
"secuencia",
"[",
"i",
"-",
"2",
"]",
")",
"return",
"secuencia"
] |
[
32,
0
] |
[
43,
20
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
get_random_point
|
()
|
return x, y
|
Returns random x, y coordinates.
|
Returns random x, y coordinates.
|
def get_random_point():
"""Returns random x, y coordinates."""
x = random.randint(-100, 100)
y = random.randint(-100, 100)
return x, y
|
[
"def",
"get_random_point",
"(",
")",
":",
"x",
"=",
"random",
".",
"randint",
"(",
"-",
"100",
",",
"100",
")",
"y",
"=",
"random",
".",
"randint",
"(",
"-",
"100",
",",
"100",
")",
"return",
"x",
",",
"y"
] |
[
4,
0
] |
[
8,
15
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
ModelBase.has_history
|
(self)
|
return bool(self.history.count())
|
Comprueba si este objeto posee historial de cambios.
|
Comprueba si este objeto posee historial de cambios.
|
def has_history(self):
"""Comprueba si este objeto posee historial de cambios."""
if not hasattr(self, "history"):
return False
return bool(self.history.count())
|
[
"def",
"has_history",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"history\"",
")",
":",
"return",
"False",
"return",
"bool",
"(",
"self",
".",
"history",
".",
"count",
"(",
")",
")"
] |
[
471,
4
] |
[
475,
41
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
TablaValores.SiguienteTemp
|
(self)
|
return var
|
Retorna el siguiente temporal simbolicamente pues no aumenta el contador
|
Retorna el siguiente temporal simbolicamente pues no aumenta el contador
|
def SiguienteTemp(self):
'''Retorna el siguiente temporal simbolicamente pues no aumenta el contador'''
num = self.temp
var = 't' + str(num)
return var
|
[
"def",
"SiguienteTemp",
"(",
"self",
")",
":",
"num",
"=",
"self",
".",
"temp",
"var",
"=",
"'t'",
"+",
"str",
"(",
"num",
")",
"return",
"var"
] |
[
23,
4
] |
[
27,
18
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
p_propiedades7
|
(t)
|
propiedades : identity
|
propiedades : identity
|
def p_propiedades7(t):
'''propiedades : identity'''
node = grammer.nodoDireccion('propiedades')
node1 = grammer.nodoDireccion(t[1])
node.agregar(node1)
t[0] = node
|
[
"def",
"p_propiedades7",
"(",
"t",
")",
":",
"node",
"=",
"grammer",
".",
"nodoDireccion",
"(",
"'propiedades'",
")",
"node1",
"=",
"grammer",
".",
"nodoDireccion",
"(",
"t",
"[",
"1",
"]",
")",
"node",
".",
"agregar",
"(",
"node1",
")",
"t",
"[",
"0",
"]",
"=",
"node"
] |
[
326,
0
] |
[
331,
19
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_alter_db1
|
(t)
|
accion_alter_db : OWNER TO nuevo_prop
|
accion_alter_db : OWNER TO nuevo_prop
|
def p_alter_db1(t):
'''accion_alter_db : OWNER TO nuevo_prop'''
reportebnf.append(bnf["p_alter_db1"])
nuevo = Alter('C_ALTER')
nuevo.hijos.append(Alter('OWNER',t.lineno(1),t.lexpos(1)+1))
nuevo.hijos.append(Alter('TO',t.lineno(1),t.lexpos(1)+1))
nuevo.hijos.append(t[3])
t[0] = nuevo
|
[
"def",
"p_alter_db1",
"(",
"t",
")",
":",
"reportebnf",
".",
"append",
"(",
"bnf",
"[",
"\"p_alter_db1\"",
"]",
")",
"nuevo",
"=",
"Alter",
"(",
"'C_ALTER'",
")",
"nuevo",
".",
"hijos",
".",
"append",
"(",
"Alter",
"(",
"'OWNER'",
",",
"t",
".",
"lineno",
"(",
"1",
")",
",",
"t",
".",
"lexpos",
"(",
"1",
")",
"+",
"1",
")",
")",
"nuevo",
".",
"hijos",
".",
"append",
"(",
"Alter",
"(",
"'TO'",
",",
"t",
".",
"lineno",
"(",
"1",
")",
",",
"t",
".",
"lexpos",
"(",
"1",
")",
"+",
"1",
")",
")",
"nuevo",
".",
"hijos",
".",
"append",
"(",
"t",
"[",
"3",
"]",
")",
"t",
"[",
"0",
"]",
"=",
"nuevo"
] |
[
2172,
0
] |
[
2179,
16
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
start_roles_and_permissions
|
()
|
crear los grupos/roles iniciales del sistema
|
crear los grupos/roles iniciales del sistema
|
def start_roles_and_permissions():
""" crear los grupos/roles iniciales del sistema """
group_city, created = Group.objects.get_or_create(name=settings.GRUPO_CIUDADANO)
group_admin, created = Group.objects.get_or_create(name=settings.GRUPO_ADMIN)
group_prof, created = Group.objects.get_or_create(name=settings.GRUPO_PROFESIONAL)
group_data, created = Group.objects.get_or_create(name=settings.GRUPO_DATOS)
group_super, created = Group.objects.get_or_create(name=settings.GRUPO_SUPER_ADMIN)
group_recupero, created = Group.objects.get_or_create(name=settings.GRUPO_RECUPERO)
""" asignar los permisos iniciales a los roles en el sistema """
perm_schedule_turno = Permission.objects.get(codename='can_schedule_turno', content_type__app_label='calendario')
perm_viewmy_turno = Permission.objects.get(codename='can_view_misturnos', content_type__app_label='calendario')
perm_cancel_turno = Permission.objects.get(codename='can_cancel_turno', content_type__app_label='calendario')
perm_add_turno = Permission.objects.get(codename='add_turno', content_type__app_label='calendario')
perm_view_turno = Permission.objects.get(codename='view_turno', content_type__app_label='calendario')
perm_change_turno = Permission.objects.get(codename='change_turno', content_type__app_label='calendario')
group_admin.permissions.add(perm_add_turno, perm_change_turno, perm_schedule_turno, perm_view_turno,
perm_cancel_turno)
group_city.permissions.add(perm_viewmy_turno)
perm_add_consulta = Permission.objects.get(codename='add_consulta', content_type__app_label='pacientes')
perm_view_consulta = Permission.objects.get(codename='view_consulta', content_type__app_label='pacientes')
perm_add_paciente = Permission.objects.get(codename='add_paciente', content_type__app_label='pacientes')
perm_change_paciente = Permission.objects.get(codename='change_paciente', content_type__app_label='pacientes')
group_prof.permissions.add(perm_view_consulta, perm_add_consulta)
group_recupero.permissions.add(perm_add_paciente, perm_change_paciente)
group_admin.permissions.add(perm_add_paciente, perm_change_paciente)
perm_add_prof = Permission.objects.get(codename='add_profesional', content_type__app_label='profesionales')
perm_view_prof = Permission.objects.get(codename='view_profesional', content_type__app_label='profesionales')
perm_chg_prof = Permission.objects.get(codename='change_profesional', content_type__app_label='profesionales')
perm_tablero_prof = Permission.objects.get(codename='can_view_tablero', content_type__app_label='profesionales')
# ISSUE limitarlo de alguna forma
# https://github.com/cluster311/ggg/issues/182
group_admin.permissions.add(
perm_view_prof) # lo necesita para filtrar la lista de profesionales al crear los turnos.
group_data.permissions.add(perm_tablero_prof)
group_super.permissions.add(perm_view_prof, perm_chg_prof, perm_add_prof)
perm_tablero_oss = Permission.objects.get(codename='can_view_tablero', content_type__app_label='obras_sociales')
perm_view_oss = Permission.objects.get(codename='view_obrasocial', content_type__app_label='obras_sociales')
perm_add_oss = Permission.objects.get(codename='add_obrasocial', content_type__app_label='obras_sociales')
perm_chg_oss = Permission.objects.get(codename='change_obrasocial', content_type__app_label='obras_sociales')
perm_view_ossp = Permission.objects.get(codename='view_obrasocialpaciente', content_type__app_label='obras_sociales')
perm_add_ossp = Permission.objects.get(codename='add_obrasocialpaciente', content_type__app_label='obras_sociales')
perm_chg_ossp = Permission.objects.get(codename='change_obrasocialpaciente', content_type__app_label='obras_sociales')
group_data.permissions.add(perm_tablero_oss)
group_super.permissions.add(perm_view_oss, perm_add_oss, perm_chg_oss,perm_view_ossp, perm_add_ossp, perm_chg_ossp)
perm_tablero_cds = Permission.objects.get(codename='can_view_tablero', content_type__app_label='centros_de_salud')
perm_add_serv = Permission.objects.get(codename='add_servicio', content_type__app_label='centros_de_salud')
perm_view_serv = Permission.objects.get(codename='view_servicio', content_type__app_label='centros_de_salud')
perm_chg_serv = Permission.objects.get(codename='change_servicio', content_type__app_label='centros_de_salud')
perm_add_esp = Permission.objects.get(codename='add_especialidad', content_type__app_label='centros_de_salud')
perm_view_esp = Permission.objects.get(codename='view_especialidad', content_type__app_label='centros_de_salud')
perm_chg_esp = Permission.objects.get(codename='change_especialidad', content_type__app_label='centros_de_salud')
perm_add_cds = Permission.objects.get(codename='add_centrodesalud', content_type__app_label='centros_de_salud')
perm_view_cds = Permission.objects.get(codename='view_centrodesalud', content_type__app_label='centros_de_salud')
perm_chg_cds = Permission.objects.get(codename='change_centrodesalud', content_type__app_label='centros_de_salud')
perm_add_pes = Permission.objects.get(codename='add_profesionalesenservicio',
content_type__app_label='centros_de_salud')
perm_view_pes = Permission.objects.get(codename='view_profesionalesenservicio',
content_type__app_label='centros_de_salud')
perm_chg_pes = Permission.objects.get(codename='change_profesionalesenservicio',
content_type__app_label='centros_de_salud')
group_data.permissions.add(perm_tablero_cds)
group_super.permissions.add(perm_view_serv, perm_chg_serv, perm_view_esp, perm_chg_esp,
perm_view_cds, perm_chg_cds, perm_view_pes, perm_chg_pes,
perm_add_serv, perm_add_esp, perm_add_cds, perm_add_pes)
perm_add_ma = Permission.objects.get(codename='add_medidaanexa', content_type__app_label='especialidades')
perm_view_ma = Permission.objects.get(codename='view_medidaanexa', content_type__app_label='especialidades')
perm_chg_ma = Permission.objects.get(codename='change_medidaanexa', content_type__app_label='especialidades')
perm_add_maesp = Permission.objects.get(codename='add_medidasanexasespecialidad',
content_type__app_label='especialidades')
perm_view_maesp = Permission.objects.get(codename='view_medidasanexasespecialidad',
content_type__app_label='especialidades')
perm_chg_maesp = Permission.objects.get(codename='change_medidasanexasespecialidad',
content_type__app_label='especialidades')
group_super.permissions.add(perm_view_ma, perm_chg_ma, perm_view_maesp, perm_chg_maesp,
perm_add_ma, perm_add_maesp)
perm_add_fact = Permission.objects.get(codename='add_factura', content_type__app_label='recupero')
perm_view_fact = Permission.objects.get(codename='view_factura', content_type__app_label='recupero')
perm_chg_fact = Permission.objects.get(codename='change_factura', content_type__app_label='recupero')
perm_add_tda = Permission.objects.get(codename='add_tipodocumentoanexo', content_type__app_label='recupero')
perm_view_tda = Permission.objects.get(codename='view_tipodocumentoanexo', content_type__app_label='recupero')
perm_chg_tda = Permission.objects.get(codename='change_tipodocumentoanexo', content_type__app_label='recupero')
perm_add_tp = Permission.objects.get(codename='add_tipoprestacion', content_type__app_label='recupero')
perm_view_tp = Permission.objects.get(codename='view_tipoprestacion', content_type__app_label='recupero')
perm_chg_tp = Permission.objects.get(codename='change_tipoprestacion', content_type__app_label='recupero')
group_recupero.permissions.add(perm_view_fact, perm_chg_fact, perm_view_tda,
perm_chg_tda, perm_view_tp, perm_chg_tp,
perm_add_tda, perm_add_tp, perm_add_fact, perm_view_oss,)
perm_view_uecds = Permission.objects.get(codename='view_usuarioencentrodesalud', content_type__app_label='usuarios')
perm_add_uecds = Permission.objects.get(codename='add_usuarioencentrodesalud', content_type__app_label='usuarios')
perm_chg_uecds = Permission.objects.get(codename='change_usuarioencentrodesalud',
content_type__app_label='usuarios')
group_super.permissions.add(perm_view_uecds, perm_add_uecds, perm_chg_uecds)
|
[
"def",
"start_roles_and_permissions",
"(",
")",
":",
"group_city",
",",
"created",
"=",
"Group",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"settings",
".",
"GRUPO_CIUDADANO",
")",
"group_admin",
",",
"created",
"=",
"Group",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"settings",
".",
"GRUPO_ADMIN",
")",
"group_prof",
",",
"created",
"=",
"Group",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"settings",
".",
"GRUPO_PROFESIONAL",
")",
"group_data",
",",
"created",
"=",
"Group",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"settings",
".",
"GRUPO_DATOS",
")",
"group_super",
",",
"created",
"=",
"Group",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"settings",
".",
"GRUPO_SUPER_ADMIN",
")",
"group_recupero",
",",
"created",
"=",
"Group",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"settings",
".",
"GRUPO_RECUPERO",
")",
"\"\"\" asignar los permisos iniciales a los roles en el sistema \"\"\"",
"perm_schedule_turno",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'can_schedule_turno'",
",",
"content_type__app_label",
"=",
"'calendario'",
")",
"perm_viewmy_turno",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'can_view_misturnos'",
",",
"content_type__app_label",
"=",
"'calendario'",
")",
"perm_cancel_turno",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'can_cancel_turno'",
",",
"content_type__app_label",
"=",
"'calendario'",
")",
"perm_add_turno",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_turno'",
",",
"content_type__app_label",
"=",
"'calendario'",
")",
"perm_view_turno",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_turno'",
",",
"content_type__app_label",
"=",
"'calendario'",
")",
"perm_change_turno",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_turno'",
",",
"content_type__app_label",
"=",
"'calendario'",
")",
"group_admin",
".",
"permissions",
".",
"add",
"(",
"perm_add_turno",
",",
"perm_change_turno",
",",
"perm_schedule_turno",
",",
"perm_view_turno",
",",
"perm_cancel_turno",
")",
"group_city",
".",
"permissions",
".",
"add",
"(",
"perm_viewmy_turno",
")",
"perm_add_consulta",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_consulta'",
",",
"content_type__app_label",
"=",
"'pacientes'",
")",
"perm_view_consulta",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_consulta'",
",",
"content_type__app_label",
"=",
"'pacientes'",
")",
"perm_add_paciente",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_paciente'",
",",
"content_type__app_label",
"=",
"'pacientes'",
")",
"perm_change_paciente",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_paciente'",
",",
"content_type__app_label",
"=",
"'pacientes'",
")",
"group_prof",
".",
"permissions",
".",
"add",
"(",
"perm_view_consulta",
",",
"perm_add_consulta",
")",
"group_recupero",
".",
"permissions",
".",
"add",
"(",
"perm_add_paciente",
",",
"perm_change_paciente",
")",
"group_admin",
".",
"permissions",
".",
"add",
"(",
"perm_add_paciente",
",",
"perm_change_paciente",
")",
"perm_add_prof",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_profesional'",
",",
"content_type__app_label",
"=",
"'profesionales'",
")",
"perm_view_prof",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_profesional'",
",",
"content_type__app_label",
"=",
"'profesionales'",
")",
"perm_chg_prof",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_profesional'",
",",
"content_type__app_label",
"=",
"'profesionales'",
")",
"perm_tablero_prof",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'can_view_tablero'",
",",
"content_type__app_label",
"=",
"'profesionales'",
")",
"# ISSUE limitarlo de alguna forma",
"# https://github.com/cluster311/ggg/issues/182",
"group_admin",
".",
"permissions",
".",
"add",
"(",
"perm_view_prof",
")",
"# lo necesita para filtrar la lista de profesionales al crear los turnos.",
"group_data",
".",
"permissions",
".",
"add",
"(",
"perm_tablero_prof",
")",
"group_super",
".",
"permissions",
".",
"add",
"(",
"perm_view_prof",
",",
"perm_chg_prof",
",",
"perm_add_prof",
")",
"perm_tablero_oss",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'can_view_tablero'",
",",
"content_type__app_label",
"=",
"'obras_sociales'",
")",
"perm_view_oss",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_obrasocial'",
",",
"content_type__app_label",
"=",
"'obras_sociales'",
")",
"perm_add_oss",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_obrasocial'",
",",
"content_type__app_label",
"=",
"'obras_sociales'",
")",
"perm_chg_oss",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_obrasocial'",
",",
"content_type__app_label",
"=",
"'obras_sociales'",
")",
"perm_view_ossp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_obrasocialpaciente'",
",",
"content_type__app_label",
"=",
"'obras_sociales'",
")",
"perm_add_ossp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_obrasocialpaciente'",
",",
"content_type__app_label",
"=",
"'obras_sociales'",
")",
"perm_chg_ossp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_obrasocialpaciente'",
",",
"content_type__app_label",
"=",
"'obras_sociales'",
")",
"group_data",
".",
"permissions",
".",
"add",
"(",
"perm_tablero_oss",
")",
"group_super",
".",
"permissions",
".",
"add",
"(",
"perm_view_oss",
",",
"perm_add_oss",
",",
"perm_chg_oss",
",",
"perm_view_ossp",
",",
"perm_add_ossp",
",",
"perm_chg_ossp",
")",
"perm_tablero_cds",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'can_view_tablero'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_add_serv",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_servicio'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_view_serv",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_servicio'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_chg_serv",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_servicio'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_add_esp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_especialidad'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_view_esp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_especialidad'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_chg_esp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_especialidad'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_add_cds",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_centrodesalud'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_view_cds",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_centrodesalud'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_chg_cds",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_centrodesalud'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_add_pes",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_profesionalesenservicio'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_view_pes",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_profesionalesenservicio'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"perm_chg_pes",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_profesionalesenservicio'",
",",
"content_type__app_label",
"=",
"'centros_de_salud'",
")",
"group_data",
".",
"permissions",
".",
"add",
"(",
"perm_tablero_cds",
")",
"group_super",
".",
"permissions",
".",
"add",
"(",
"perm_view_serv",
",",
"perm_chg_serv",
",",
"perm_view_esp",
",",
"perm_chg_esp",
",",
"perm_view_cds",
",",
"perm_chg_cds",
",",
"perm_view_pes",
",",
"perm_chg_pes",
",",
"perm_add_serv",
",",
"perm_add_esp",
",",
"perm_add_cds",
",",
"perm_add_pes",
")",
"perm_add_ma",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_medidaanexa'",
",",
"content_type__app_label",
"=",
"'especialidades'",
")",
"perm_view_ma",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_medidaanexa'",
",",
"content_type__app_label",
"=",
"'especialidades'",
")",
"perm_chg_ma",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_medidaanexa'",
",",
"content_type__app_label",
"=",
"'especialidades'",
")",
"perm_add_maesp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_medidasanexasespecialidad'",
",",
"content_type__app_label",
"=",
"'especialidades'",
")",
"perm_view_maesp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_medidasanexasespecialidad'",
",",
"content_type__app_label",
"=",
"'especialidades'",
")",
"perm_chg_maesp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_medidasanexasespecialidad'",
",",
"content_type__app_label",
"=",
"'especialidades'",
")",
"group_super",
".",
"permissions",
".",
"add",
"(",
"perm_view_ma",
",",
"perm_chg_ma",
",",
"perm_view_maesp",
",",
"perm_chg_maesp",
",",
"perm_add_ma",
",",
"perm_add_maesp",
")",
"perm_add_fact",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_factura'",
",",
"content_type__app_label",
"=",
"'recupero'",
")",
"perm_view_fact",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_factura'",
",",
"content_type__app_label",
"=",
"'recupero'",
")",
"perm_chg_fact",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_factura'",
",",
"content_type__app_label",
"=",
"'recupero'",
")",
"perm_add_tda",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_tipodocumentoanexo'",
",",
"content_type__app_label",
"=",
"'recupero'",
")",
"perm_view_tda",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_tipodocumentoanexo'",
",",
"content_type__app_label",
"=",
"'recupero'",
")",
"perm_chg_tda",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_tipodocumentoanexo'",
",",
"content_type__app_label",
"=",
"'recupero'",
")",
"perm_add_tp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_tipoprestacion'",
",",
"content_type__app_label",
"=",
"'recupero'",
")",
"perm_view_tp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_tipoprestacion'",
",",
"content_type__app_label",
"=",
"'recupero'",
")",
"perm_chg_tp",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_tipoprestacion'",
",",
"content_type__app_label",
"=",
"'recupero'",
")",
"group_recupero",
".",
"permissions",
".",
"add",
"(",
"perm_view_fact",
",",
"perm_chg_fact",
",",
"perm_view_tda",
",",
"perm_chg_tda",
",",
"perm_view_tp",
",",
"perm_chg_tp",
",",
"perm_add_tda",
",",
"perm_add_tp",
",",
"perm_add_fact",
",",
"perm_view_oss",
",",
")",
"perm_view_uecds",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'view_usuarioencentrodesalud'",
",",
"content_type__app_label",
"=",
"'usuarios'",
")",
"perm_add_uecds",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'add_usuarioencentrodesalud'",
",",
"content_type__app_label",
"=",
"'usuarios'",
")",
"perm_chg_uecds",
"=",
"Permission",
".",
"objects",
".",
"get",
"(",
"codename",
"=",
"'change_usuarioencentrodesalud'",
",",
"content_type__app_label",
"=",
"'usuarios'",
")",
"group_super",
".",
"permissions",
".",
"add",
"(",
"perm_view_uecds",
",",
"perm_add_uecds",
",",
"perm_chg_uecds",
")"
] |
[
9,
0
] |
[
116,
80
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
UserCallback.insert_user
|
(
user: str,
password: str,
token_limit: int = 1,
guest_user: bool = False,
*, cursor
)
|
Añade un nuevo usuario
Args:
user:
El nombre de usuario
password:
La contraseña
token_limit:
El límite de token's permitidos
guest_user:
**True** si es un usuario invitado; **False** si no.
|
Añade un nuevo usuario
Args:
user:
El nombre de usuario
|
async def insert_user(
user: str,
password: str,
token_limit: int = 1,
guest_user: bool = False,
*, cursor
) -> None:
"""Añade un nuevo usuario
Args:
user:
El nombre de usuario
password:
La contraseña
token_limit:
El límite de token's permitidos
guest_user:
**True** si es un usuario invitado; **False** si no.
"""
logging.debug(_("Creando nuevo usuario: %s"), user)
user_hash = hashlib.sha3_224(
user.encode()
).hexdigest()
await cursor.execute(
"INSERT INTO users(user, password, token_limit, user_hash, guest_user) VALUES (%s, %s, %s, %s, %s)",
(user, password, token_limit, user_hash, guest_user)
)
logging.debug(_("Usuario %s (%s) creado satisfactoriamente"), user, user_hash)
|
[
"async",
"def",
"insert_user",
"(",
"user",
":",
"str",
",",
"password",
":",
"str",
",",
"token_limit",
":",
"int",
"=",
"1",
",",
"guest_user",
":",
"bool",
"=",
"False",
",",
"*",
",",
"cursor",
")",
"->",
"None",
":",
"logging",
".",
"debug",
"(",
"_",
"(",
"\"Creando nuevo usuario: %s\"",
")",
",",
"user",
")",
"user_hash",
"=",
"hashlib",
".",
"sha3_224",
"(",
"user",
".",
"encode",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"await",
"cursor",
".",
"execute",
"(",
"\"INSERT INTO users(user, password, token_limit, user_hash, guest_user) VALUES (%s, %s, %s, %s, %s)\"",
",",
"(",
"user",
",",
"password",
",",
"token_limit",
",",
"user_hash",
",",
"guest_user",
")",
")",
"logging",
".",
"debug",
"(",
"_",
"(",
"\"Usuario %s (%s) creado satisfactoriamente\"",
")",
",",
"user",
",",
"user_hash",
")"
] |
[
68,
4
] |
[
105,
86
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
TrackingVideo.remove_property
|
(self, property_: TrackingVideoProperty)
|
Elimina una propiedad a la creación del vídeo de seguimiento.
:param property_: propiedad para eliminar.
:return: None.
|
Elimina una propiedad a la creación del vídeo de seguimiento.
|
def remove_property(self, property_: TrackingVideoProperty):
"""Elimina una propiedad a la creación del vídeo de seguimiento.
:param property_: propiedad para eliminar.
:return: None.
"""
self._properties.pop(property_)
|
[
"def",
"remove_property",
"(",
"self",
",",
"property_",
":",
"TrackingVideoProperty",
")",
":",
"self",
".",
"_properties",
".",
"pop",
"(",
"property_",
")"
] |
[
359,
4
] |
[
365,
39
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_block
|
(t)
|
block : declare BEGIN instrucciones END
|
block : declare BEGIN instrucciones END
|
def p_block(t):
' block : declare BEGIN instrucciones END'
t[0] = block(t[1],t[3])
|
[
"def",
"p_block",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"block",
"(",
"t",
"[",
"1",
"]",
",",
"t",
"[",
"3",
"]",
")"
] |
[
2524,
0
] |
[
2526,
27
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
tipo_elementos
|
()
|
return layout
|
Seccion jugar con imagenes y/o texto
|
Seccion jugar con imagenes y/o texto
|
def tipo_elementos():
""" Seccion jugar con imagenes y/o texto"""
layout = [
sg.Text('Tipos de elementos de las casillas: ', font=[theme.FONT, 12],
background_color=theme.PRIMARY_COLOR_VARIANT, pad=(5, 6)),
sg.Radio('Palabras', '-ELEMENTS-', True, key='-WORDS-', font=[theme.FONT, 12],
background_color=theme.PRIMARY_COLOR_VARIANT, pad=(5, 6)),
sg.Radio('Imágenes y palabras', '-ELEMENTS-', key='-IMAGES-', font=[theme.FONT, 12],
background_color=theme.PRIMARY_COLOR_VARIANT, pad=(5, 6))
]
return layout
|
[
"def",
"tipo_elementos",
"(",
")",
":",
"layout",
"=",
"[",
"sg",
".",
"Text",
"(",
"'Tipos de elementos de las casillas: '",
",",
"font",
"=",
"[",
"theme",
".",
"FONT",
",",
"12",
"]",
",",
"background_color",
"=",
"theme",
".",
"PRIMARY_COLOR_VARIANT",
",",
"pad",
"=",
"(",
"5",
",",
"6",
")",
")",
",",
"sg",
".",
"Radio",
"(",
"'Palabras'",
",",
"'-ELEMENTS-'",
",",
"True",
",",
"key",
"=",
"'-WORDS-'",
",",
"font",
"=",
"[",
"theme",
".",
"FONT",
",",
"12",
"]",
",",
"background_color",
"=",
"theme",
".",
"PRIMARY_COLOR_VARIANT",
",",
"pad",
"=",
"(",
"5",
",",
"6",
")",
")",
",",
"sg",
".",
"Radio",
"(",
"'Imágenes y palabras',",
" ",
"-ELEMENTS-',",
" ",
"ey=",
"'",
"-IMAGES-',",
" ",
"ont=",
"[",
"t",
"heme.",
"F",
"ONT,",
" ",
"2]",
",",
"",
"background_color",
"=",
"theme",
".",
"PRIMARY_COLOR_VARIANT",
",",
"pad",
"=",
"(",
"5",
",",
"6",
")",
")",
"]",
"return",
"layout"
] |
[
46,
0
] |
[
57,
17
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
cuad_simpson_compuesta
|
(x, f=None, y=None)
|
return aprox
|
Implementación de la regla de simpson
Parameters
----------
x: list or array
Lista de valores de x
f: function (1 parameter)
La función a integrar
y: list or array
La lista de valores de y
Returns
-------
aprox: Aproximación de la integral por la regla de Simpson
Notes
-----
Este código es parte del curso "Computación", Famaf
Uso:
cuad_simpson(x, y=y)
cuad_simpson(x, f=f)
|
Implementación de la regla de simpson
Parameters
----------
x: list or array
Lista de valores de x
f: function (1 parameter)
La función a integrar
y: list or array
La lista de valores de y
Returns
-------
aprox: Aproximación de la integral por la regla de Simpson
Notes
-----
Este código es parte del curso "Computación", Famaf
Uso:
cuad_simpson(x, y=y)
cuad_simpson(x, f=f)
|
def cuad_simpson_compuesta(x, f=None, y=None):
"""Implementación de la regla de simpson
Parameters
----------
x: list or array
Lista de valores de x
f: function (1 parameter)
La función a integrar
y: list or array
La lista de valores de y
Returns
-------
aprox: Aproximación de la integral por la regla de Simpson
Notes
-----
Este código es parte del curso "Computación", Famaf
Uso:
cuad_simpson(x, y=y)
cuad_simpson(x, f=f)
"""
import numpy as np
# Primero verificar si la particion es regular
x = np.array(x)
x.sort()
H = (max(x) - min(x))/len(x-1)
equiesp = np.std(np.diff(x)) < H*1.e-6
# Calcular los valores de y (si se pasó una función)
if (y is None) and (f is not None):
y = f(x)
n = len(x)
if equiesp:
impares = y[1:-1:2].sum()
pares = y[2:-1:2].sum()
H = y[0] + 2*pares + 4*impares + y[-1]
H = H / (3*n)
aprox = (x[-1]-x[0])*H
else:
aprox = 0
for i in range(0, len(x)-2, 2):
aprox += cuad_simpson(x[i], x[i+2], y[i], y[i+1], y[i+2])
return aprox
|
[
"def",
"cuad_simpson_compuesta",
"(",
"x",
",",
"f",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"import",
"numpy",
"as",
"np",
"# Primero verificar si la particion es regular ",
"x",
"=",
"np",
".",
"array",
"(",
"x",
")",
"x",
".",
"sort",
"(",
")",
"H",
"=",
"(",
"max",
"(",
"x",
")",
"-",
"min",
"(",
"x",
")",
")",
"/",
"len",
"(",
"x",
"-",
"1",
")",
"equiesp",
"=",
"np",
".",
"std",
"(",
"np",
".",
"diff",
"(",
"x",
")",
")",
"<",
"H",
"*",
"1.e-6",
"# Calcular los valores de y (si se pasó una función)",
"if",
"(",
"y",
"is",
"None",
")",
"and",
"(",
"f",
"is",
"not",
"None",
")",
":",
"y",
"=",
"f",
"(",
"x",
")",
"n",
"=",
"len",
"(",
"x",
")",
"if",
"equiesp",
":",
"impares",
"=",
"y",
"[",
"1",
":",
"-",
"1",
":",
"2",
"]",
".",
"sum",
"(",
")",
"pares",
"=",
"y",
"[",
"2",
":",
"-",
"1",
":",
"2",
"]",
".",
"sum",
"(",
")",
"H",
"=",
"y",
"[",
"0",
"]",
"+",
"2",
"*",
"pares",
"+",
"4",
"*",
"impares",
"+",
"y",
"[",
"-",
"1",
"]",
"H",
"=",
"H",
"/",
"(",
"3",
"*",
"n",
")",
"aprox",
"=",
"(",
"x",
"[",
"-",
"1",
"]",
"-",
"x",
"[",
"0",
"]",
")",
"*",
"H",
"else",
":",
"aprox",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"x",
")",
"-",
"2",
",",
"2",
")",
":",
"aprox",
"+=",
"cuad_simpson",
"(",
"x",
"[",
"i",
"]",
",",
"x",
"[",
"i",
"+",
"2",
"]",
",",
"y",
"[",
"i",
"]",
",",
"y",
"[",
"i",
"+",
"1",
"]",
",",
"y",
"[",
"i",
"+",
"2",
"]",
")",
"return",
"aprox"
] |
[
399,
0
] |
[
447,
16
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
ingresar_pedido
|
()
|
Pide al usuario los datos para calcular el precio de la compra.
:return: Cantidad de cada helado
:rtype: Dict[str, int]
|
Pide al usuario los datos para calcular el precio de la compra.
|
def ingresar_pedido() -> Dict[str, int]:
"""Pide al usuario los datos para calcular el precio de la compra.
:return: Cantidad de cada helado
:rtype: Dict[str, int]
"""
data = {"lucuma": 0, "fresa": 0, "mango": 0, "leche": 0}
while True:
tipo = menu_input(tuple(TIPO.keys()), numbers=True, lang="es")
cantidad = int_input("Cantidad: ", min=1)
data[tipo] += cantidad
if not ask_to_finish(lang="es"):
return data
|
[
"def",
"ingresar_pedido",
"(",
")",
"->",
"Dict",
"[",
"str",
",",
"int",
"]",
":",
"data",
"=",
"{",
"\"lucuma\"",
":",
"0",
",",
"\"fresa\"",
":",
"0",
",",
"\"mango\"",
":",
"0",
",",
"\"leche\"",
":",
"0",
"}",
"while",
"True",
":",
"tipo",
"=",
"menu_input",
"(",
"tuple",
"(",
"TIPO",
".",
"keys",
"(",
")",
")",
",",
"numbers",
"=",
"True",
",",
"lang",
"=",
"\"es\"",
")",
"cantidad",
"=",
"int_input",
"(",
"\"Cantidad: \"",
",",
"min",
"=",
"1",
")",
"data",
"[",
"tipo",
"]",
"+=",
"cantidad",
"if",
"not",
"ask_to_finish",
"(",
"lang",
"=",
"\"es\"",
")",
":",
"return",
"data"
] |
[
10,
0
] |
[
22,
23
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
unRegister
|
(apiclient: ApiClient, customerId: str)
|
Este servicio permite eliminar el registro de la tarjeta de crédito
de un cliente. Al eliminar el registro no se podrá hacer cargos
automáticos y Flow enviará un cobro por email.
|
Este servicio permite eliminar el registro de la tarjeta de crédito
de un cliente. Al eliminar el registro no se podrá hacer cargos
automáticos y Flow enviará un cobro por email.
|
def unRegister(apiclient: ApiClient, customerId: str) -> Union[Customer, Error]:
"""Este servicio permite eliminar el registro de la tarjeta de crédito
de un cliente. Al eliminar el registro no se podrá hacer cargos
automáticos y Flow enviará un cobro por email.
"""
url = f"{apiclient.api_url}/customer/unRegister"
params: Dict[str, Any] = {
"apiKey": apiclient.api_key,
"customerId": customerId,
}
signature = apiclient.make_signature(params)
params["s"] = signature
logging.debug("Before Request:" + str(params))
response = apiclient.post(url, params)
if response.status_code == 200:
return Customer.from_dict(cast(Dict[str, Any], response.json()))
if response.status_code == 400:
return Error.from_dict(cast(Dict[str, Any], response.json()))
if response.status_code == 401:
return Error.from_dict(cast(Dict[str, Any], response.json()))
else:
raise Exception(response=response)
|
[
"def",
"unRegister",
"(",
"apiclient",
":",
"ApiClient",
",",
"customerId",
":",
"str",
")",
"->",
"Union",
"[",
"Customer",
",",
"Error",
"]",
":",
"url",
"=",
"f\"{apiclient.api_url}/customer/unRegister\"",
"params",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"\"apiKey\"",
":",
"apiclient",
".",
"api_key",
",",
"\"customerId\"",
":",
"customerId",
",",
"}",
"signature",
"=",
"apiclient",
".",
"make_signature",
"(",
"params",
")",
"params",
"[",
"\"s\"",
"]",
"=",
"signature",
"logging",
".",
"debug",
"(",
"\"Before Request:\"",
"+",
"str",
"(",
"params",
")",
")",
"response",
"=",
"apiclient",
".",
"post",
"(",
"url",
",",
"params",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"Customer",
".",
"from_dict",
"(",
"cast",
"(",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"response",
".",
"json",
"(",
")",
")",
")",
"if",
"response",
".",
"status_code",
"==",
"400",
":",
"return",
"Error",
".",
"from_dict",
"(",
"cast",
"(",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"response",
".",
"json",
"(",
")",
")",
")",
"if",
"response",
".",
"status_code",
"==",
"401",
":",
"return",
"Error",
".",
"from_dict",
"(",
"cast",
"(",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"response",
".",
"json",
"(",
")",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"response",
"=",
"response",
")"
] |
[
222,
0
] |
[
247,
42
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
BcraSmlScraperTestCase.test_html_is_valid
|
(self)
|
Probar que el html sea valido
|
Probar que el html sea valido
|
def test_html_is_valid(self):
"""Probar que el html sea valido"""
url = ""
single_date = date(2019, 3, 4)
coins = {}
with patch.object(
BCRASMLScraper,
'fetch_content',
return_value='''
<table class="table table-BCRA table-bordered table-hover
table-responsive">
<thead>
</thead>
<tbody>
</tbody>
</table>
'''
):
scraper = BCRASMLScraper(url, coins, intermediate_panel_path=None, use_intermediate_panel=False)
content = scraper.fetch_content(single_date)
soup = BeautifulSoup(content, "html.parser")
table = soup.find('table')
head = table.find('thead') if table else None
body = table.find('tbody') if table else None
assert table is not None
assert head is not None
assert body is not None
|
[
"def",
"test_html_is_valid",
"(",
"self",
")",
":",
"url",
"=",
"\"\"",
"single_date",
"=",
"date",
"(",
"2019",
",",
"3",
",",
"4",
")",
"coins",
"=",
"{",
"}",
"with",
"patch",
".",
"object",
"(",
"BCRASMLScraper",
",",
"'fetch_content'",
",",
"return_value",
"=",
"'''\n <table class=\"table table-BCRA table-bordered table-hover\n table-responsive\">\n <thead>\n </thead>\n <tbody>\n </tbody>\n </table>\n '''",
")",
":",
"scraper",
"=",
"BCRASMLScraper",
"(",
"url",
",",
"coins",
",",
"intermediate_panel_path",
"=",
"None",
",",
"use_intermediate_panel",
"=",
"False",
")",
"content",
"=",
"scraper",
".",
"fetch_content",
"(",
"single_date",
")",
"soup",
"=",
"BeautifulSoup",
"(",
"content",
",",
"\"html.parser\"",
")",
"table",
"=",
"soup",
".",
"find",
"(",
"'table'",
")",
"head",
"=",
"table",
".",
"find",
"(",
"'thead'",
")",
"if",
"table",
"else",
"None",
"body",
"=",
"table",
".",
"find",
"(",
"'tbody'",
")",
"if",
"table",
"else",
"None",
"assert",
"table",
"is",
"not",
"None",
"assert",
"head",
"is",
"not",
"None",
"assert",
"body",
"is",
"not",
"None"
] |
[
24,
4
] |
[
54,
35
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_asignaciones2
|
(t)
|
asignaciones : asignacion
|
asignaciones : asignacion
|
def p_asignaciones2(t):
'asignaciones : asignacion'
t[0] = [t[1]]
varGramatical.append('asignaciones ::= asignacion')
varSemantico.append('if ')
|
[
"def",
"p_asignaciones2",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"[",
"t",
"[",
"1",
"]",
"]",
"varGramatical",
".",
"append",
"(",
"'asignaciones ::= asignacion'",
")",
"varSemantico",
".",
"append",
"(",
"'if '",
")"
] |
[
701,
0
] |
[
705,
30
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
p_inicio
|
(t)
|
inicio : instrucciones
|
inicio : instrucciones
|
def p_inicio(t):
'''inicio : instrucciones'''
node = grammer.nodoDireccion('inicio')
node.agregar(t[1])
t[0] = node
|
[
"def",
"p_inicio",
"(",
"t",
")",
":",
"node",
"=",
"grammer",
".",
"nodoDireccion",
"(",
"'inicio'",
")",
"node",
".",
"agregar",
"(",
"t",
"[",
"1",
"]",
")",
"t",
"[",
"0",
"]",
"=",
"node"
] |
[
19,
0
] |
[
23,
27
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
apply_homography_tracked_objects
|
(tracked_objects: TrackedObjects,
h: np.ndarray)
|
return tracked_objects
|
Aplicar la homografía al seguimiento de los objetos.
:param tracked_objects: secuencia de objetos (seguimiento).
:param h: matriz de homografía.
:return: secuencia de objetos con la homografía aplicada.
|
Aplicar la homografía al seguimiento de los objetos.
|
def apply_homography_tracked_objects(tracked_objects: TrackedObjects,
h: np.ndarray) -> TrackedObjects:
"""Aplicar la homografía al seguimiento de los objetos.
:param tracked_objects: secuencia de objetos (seguimiento).
:param h: matriz de homografía.
:return: secuencia de objetos con la homografía aplicada.
"""
tracked_objects = copy.deepcopy(tracked_objects)
# Iterar sobre todos los objetos seguidos.
for tracked_object in tracked_objects:
# Aplicar a cada una de sus detecciones en el seguimiento.
for tracked_object_detection in tracked_object:
# Obtener objeto con la homografía.
object_detection_h = apply_homography_object(tracked_object_detection.object, h)
# Aplicar los puntos homografiados al objeto de la tupla.
tracked_object_detection.object.center = object_detection_h.center
tracked_object_detection.object.bounding_box = object_detection_h.bounding_box
return tracked_objects
|
[
"def",
"apply_homography_tracked_objects",
"(",
"tracked_objects",
":",
"TrackedObjects",
",",
"h",
":",
"np",
".",
"ndarray",
")",
"->",
"TrackedObjects",
":",
"tracked_objects",
"=",
"copy",
".",
"deepcopy",
"(",
"tracked_objects",
")",
"# Iterar sobre todos los objetos seguidos.",
"for",
"tracked_object",
"in",
"tracked_objects",
":",
"# Aplicar a cada una de sus detecciones en el seguimiento.",
"for",
"tracked_object_detection",
"in",
"tracked_object",
":",
"# Obtener objeto con la homografía.",
"object_detection_h",
"=",
"apply_homography_object",
"(",
"tracked_object_detection",
".",
"object",
",",
"h",
")",
"# Aplicar los puntos homografiados al objeto de la tupla.",
"tracked_object_detection",
".",
"object",
".",
"center",
"=",
"object_detection_h",
".",
"center",
"tracked_object_detection",
".",
"object",
".",
"bounding_box",
"=",
"object_detection_h",
".",
"bounding_box",
"return",
"tracked_objects"
] |
[
75,
0
] |
[
93,
26
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
DataCleaner.clean
|
(self, rules)
|
Aplica las reglas de limpieza al objeto en memoria.
Args:
rules (list): Lista de reglas de limpieza.
|
Aplica las reglas de limpieza al objeto en memoria.
|
def clean(self, rules):
"""Aplica las reglas de limpieza al objeto en memoria.
Args:
rules (list): Lista de reglas de limpieza.
"""
for rule_item in rules:
for rule in rule_item:
rule_method = getattr(self, rule)
for kwargs in rule_item[rule]:
kwargs["inplace"] = True
rule_method(**kwargs)
|
[
"def",
"clean",
"(",
"self",
",",
"rules",
")",
":",
"for",
"rule_item",
"in",
"rules",
":",
"for",
"rule",
"in",
"rule_item",
":",
"rule_method",
"=",
"getattr",
"(",
"self",
",",
"rule",
")",
"for",
"kwargs",
"in",
"rule_item",
"[",
"rule",
"]",
":",
"kwargs",
"[",
"\"inplace\"",
"]",
"=",
"True",
"rule_method",
"(",
"*",
"*",
"kwargs",
")"
] |
[
220,
4
] |
[
231,
41
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
pdf_view
|
(request, file_name)
|
**Muestra archivos PDF con base en el nombre**
:param request: Objeto ``HttpRequets`` para pasar el estado de la app a
través del sistema
:type: ``HttpRequest``
:param file_name: Nombre del ``PDF`` a mostrar
:type: str
:return: Archivo ``PDF`` para ser visto en el navegador
|
**Muestra archivos PDF con base en el nombre**
|
def pdf_view(request, file_name):
"""**Muestra archivos PDF con base en el nombre**
:param request: Objeto ``HttpRequets`` para pasar el estado de la app a
través del sistema
:type: ``HttpRequest``
:param file_name: Nombre del ``PDF`` a mostrar
:type: str
:return: Archivo ``PDF`` para ser visto en el navegador
"""
try:
path = settings.BASE_DIR + settings.MEDIA_ROOT + file_name
return FileResponse(open(path, 'rb'), content_type='application/pdf')
except FileNotFoundError:
path = settings.BASE_DIR + settings.MEDIA_ROOT + file_name
LOGGER.error("No se encontro el PDF en " + path)
raise Http404()
|
[
"def",
"pdf_view",
"(",
"request",
",",
"file_name",
")",
":",
"try",
":",
"path",
"=",
"settings",
".",
"BASE_DIR",
"+",
"settings",
".",
"MEDIA_ROOT",
"+",
"file_name",
"return",
"FileResponse",
"(",
"open",
"(",
"path",
",",
"'rb'",
")",
",",
"content_type",
"=",
"'application/pdf'",
")",
"except",
"FileNotFoundError",
":",
"path",
"=",
"settings",
".",
"BASE_DIR",
"+",
"settings",
".",
"MEDIA_ROOT",
"+",
"file_name",
"LOGGER",
".",
"error",
"(",
"\"No se encontro el PDF en \"",
"+",
"path",
")",
"raise",
"Http404",
"(",
")"
] |
[
123,
0
] |
[
139,
23
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
|
async_execute_function
|
(function: Callable[..., Any], arguments: Dict[str, Any] = {})
|
return await execute_possible_coroutine.execute(
function, *args, **kwargs
)
|
Imita al usuario cuando llama a una función
Esta función trata de imitar el comportamiento entre una
función (o un objeto invocable) y un usuario que ingresa
parámetros y argumentos.
Args:
function:
La función a llamar
arguments:
Los parámetros y argumentos de la función a llamar
Returns:
Lo mismo que la función a llamar
Raises:
RequiredArgument: Falta un parámetro que es requerido
|
Imita al usuario cuando llama a una función
|
async def async_execute_function(function: Callable[..., Any], arguments: Dict[str, Any] = {}) -> Any:
"""Imita al usuario cuando llama a una función
Esta función trata de imitar el comportamiento entre una
función (o un objeto invocable) y un usuario que ingresa
parámetros y argumentos.
Args:
function:
La función a llamar
arguments:
Los parámetros y argumentos de la función a llamar
Returns:
Lo mismo que la función a llamar
Raises:
RequiredArgument: Falta un parámetro que es requerido
"""
parse_args = parse(function)
if (len(parse_args[VAR_POSITIONAL]) >= 1):
args = list(arguments.values())
kwargs = {}
elif (len(parse_args[VAR_KEYWORD]) >= 1):
args = []
kwargs = arguments
else:
args = []
kwargs = {}
for key, value in parse_args[POSITIONAL_ONLY].items():
if (value in args):
continue
default_value = value.get("default")
annotation = value.get("annotation")
try:
real_value = arguments[key]
except KeyError:
if (default_value == empty):
raise RequiredArgument(key, _("'{}' es necesario para poder continuar").format(key))
else:
real_value = default_value
if (real_value is None):
real_value = default_value
args.append(
convert(key, real_value, annotation)
)
for dictionary in (parse_args[POSITIONAL_OR_KEYWORD], parse_args[KEYWORD_ONLY]):
for key, value in dictionary.items():
if (key in kwargs):
continue
default_value = value.get("default")
annotation = value.get("annotation")
try:
real_value = arguments[key]
except KeyError:
real_value = default_value
if (real_value == empty):
raise RequiredArgument(key, _("'{}' es necesario para poder continuar").format(key))
if (real_value is None):
real_value = default_value
kwargs[key] = convert(key, real_value, annotation)
return await execute_possible_coroutine.execute(
function, *args, **kwargs
)
|
[
"async",
"def",
"async_execute_function",
"(",
"function",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
",",
"arguments",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"}",
")",
"->",
"Any",
":",
"parse_args",
"=",
"parse",
"(",
"function",
")",
"if",
"(",
"len",
"(",
"parse_args",
"[",
"VAR_POSITIONAL",
"]",
")",
">=",
"1",
")",
":",
"args",
"=",
"list",
"(",
"arguments",
".",
"values",
"(",
")",
")",
"kwargs",
"=",
"{",
"}",
"elif",
"(",
"len",
"(",
"parse_args",
"[",
"VAR_KEYWORD",
"]",
")",
">=",
"1",
")",
":",
"args",
"=",
"[",
"]",
"kwargs",
"=",
"arguments",
"else",
":",
"args",
"=",
"[",
"]",
"kwargs",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"parse_args",
"[",
"POSITIONAL_ONLY",
"]",
".",
"items",
"(",
")",
":",
"if",
"(",
"value",
"in",
"args",
")",
":",
"continue",
"default_value",
"=",
"value",
".",
"get",
"(",
"\"default\"",
")",
"annotation",
"=",
"value",
".",
"get",
"(",
"\"annotation\"",
")",
"try",
":",
"real_value",
"=",
"arguments",
"[",
"key",
"]",
"except",
"KeyError",
":",
"if",
"(",
"default_value",
"==",
"empty",
")",
":",
"raise",
"RequiredArgument",
"(",
"key",
",",
"_",
"(",
"\"'{}' es necesario para poder continuar\"",
")",
".",
"format",
"(",
"key",
")",
")",
"else",
":",
"real_value",
"=",
"default_value",
"if",
"(",
"real_value",
"is",
"None",
")",
":",
"real_value",
"=",
"default_value",
"args",
".",
"append",
"(",
"convert",
"(",
"key",
",",
"real_value",
",",
"annotation",
")",
")",
"for",
"dictionary",
"in",
"(",
"parse_args",
"[",
"POSITIONAL_OR_KEYWORD",
"]",
",",
"parse_args",
"[",
"KEYWORD_ONLY",
"]",
")",
":",
"for",
"key",
",",
"value",
"in",
"dictionary",
".",
"items",
"(",
")",
":",
"if",
"(",
"key",
"in",
"kwargs",
")",
":",
"continue",
"default_value",
"=",
"value",
".",
"get",
"(",
"\"default\"",
")",
"annotation",
"=",
"value",
".",
"get",
"(",
"\"annotation\"",
")",
"try",
":",
"real_value",
"=",
"arguments",
"[",
"key",
"]",
"except",
"KeyError",
":",
"real_value",
"=",
"default_value",
"if",
"(",
"real_value",
"==",
"empty",
")",
":",
"raise",
"RequiredArgument",
"(",
"key",
",",
"_",
"(",
"\"'{}' es necesario para poder continuar\"",
")",
".",
"format",
"(",
"key",
")",
")",
"if",
"(",
"real_value",
"is",
"None",
")",
":",
"real_value",
"=",
"default_value",
"kwargs",
"[",
"key",
"]",
"=",
"convert",
"(",
"key",
",",
"real_value",
",",
"annotation",
")",
"return",
"await",
"execute_possible_coroutine",
".",
"execute",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
[
83,
0
] |
[
168,
5
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
filtrar
|
(c: str, v: int, r: List[str] = vehiculos)
|
return [r[i] for i in range(len(c)) if c[i] >= v]
|
Devuelve los vehículos que cumplan con el criterio dado.
:param c: criterio
:c type: str
:param v: valor a comparar
:v type: int
:param r: lista de vehículos
:r type: List[str]
:return: lista de vehículos que cumplan con el criterio dado
:rtype: List[str]
|
Devuelve los vehículos que cumplan con el criterio dado.
|
def filtrar(c: str, v: int, r: List[str] = vehiculos) -> List[str]:
"""Devuelve los vehículos que cumplan con el criterio dado.
:param c: criterio
:c type: str
:param v: valor a comparar
:v type: int
:param r: lista de vehículos
:r type: List[str]
:return: lista de vehículos que cumplan con el criterio dado
:rtype: List[str]
"""
return [r[i] for i in range(len(c)) if c[i] >= v]
|
[
"def",
"filtrar",
"(",
"c",
":",
"str",
",",
"v",
":",
"int",
",",
"r",
":",
"List",
"[",
"str",
"]",
"=",
"vehiculos",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"[",
"r",
"[",
"i",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"c",
")",
")",
"if",
"c",
"[",
"i",
"]",
">=",
"v",
"]"
] |
[
22,
0
] |
[
34,
53
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
map_dataset_to_observations
|
(dataset: dict,
tracked_objects: TrackedObjects,
tracked_objects_h: TrackedObjects,
line: Tuple[Point2D, Point2D],
max_time_diff: float = 0.4,
only_match_with_valid_cars: bool = False,
verbose: bool = False)
|
return cars_matched, tracked_objects_mapped, tracked_objects_h_mapped
|
Función para establecer una correspondencia entre los vehículos detectados en el seguimiento
y los vehículos anotados en el dataset.
:param dataset: información de la sesión del dataset BrnoCompSpeed.
:param tracked_objects: estructura de datos de los objetos seguidos.
:param tracked_objects_h: estructura de datos de los objetos seguidos con la homografía aplicada.
:param line: línea que se usará para comparar el instante en que pasaron los vehículos (anotados
y seguidos).
:param max_time_diff: tiempo máximo de diferencia que puede haber entre un vehículo anotado y un
vehículo detectado al pasar la línea indicada.
:param only_match_with_valid_cars: indica si se realizará el matching únicamente con vehículos
válidos.
:param verbose: indica si se quiere mostrar la barra de progreso o no.
:return: lista de los vehículos anotados y estructura de los objetos seguidos indexadas en el
mismo orden de correspondencia.
|
Función para establecer una correspondencia entre los vehículos detectados en el seguimiento
y los vehículos anotados en el dataset.
|
def map_dataset_to_observations(dataset: dict,
tracked_objects: TrackedObjects,
tracked_objects_h: TrackedObjects,
line: Tuple[Point2D, Point2D],
max_time_diff: float = 0.4,
only_match_with_valid_cars: bool = False,
verbose: bool = False) -> Tuple[List[Dict], TrackedObjects,
TrackedObjects]:
"""Función para establecer una correspondencia entre los vehículos detectados en el seguimiento
y los vehículos anotados en el dataset.
:param dataset: información de la sesión del dataset BrnoCompSpeed.
:param tracked_objects: estructura de datos de los objetos seguidos.
:param tracked_objects_h: estructura de datos de los objetos seguidos con la homografía aplicada.
:param line: línea que se usará para comparar el instante en que pasaron los vehículos (anotados
y seguidos).
:param max_time_diff: tiempo máximo de diferencia que puede haber entre un vehículo anotado y un
vehículo detectado al pasar la línea indicada.
:param only_match_with_valid_cars: indica si se realizará el matching únicamente con vehículos
válidos.
:param verbose: indica si se quiere mostrar la barra de progreso o no.
:return: lista de los vehículos anotados y estructura de los objetos seguidos indexadas en el
mismo orden de correspondencia.
"""
fps: float = dataset['fps']
cars: List[Dict] = dataset['cars'].copy()
tracked_objects_h_list: List[TrackedObject] = list(tracked_objects_h)
# 1. Reordenar tracked_objects_h por su orden de llegada a la línea final.
tracked_objects_h_list.sort(key=lambda tobj: tobj.find_closest_detection_to_line(line).frame)
# 2. Crear el diccionario de coches anotados y la lista de objetos seguidos con el
# emparejamiento correcto.
dataset_cars_ids_matched: List[int] = []
tracked_objects_matched: List[TrackedObject] = []
tracked_objects_h_matched: List[TrackedObject] = []
cars_matched: List[Dict] = []
id_ = 0
t = tqdm(total=len(tracked_objects_h_list), desc='Mapping dataset to tracked objects.',
disable=not verbose)
for tracked_object_h in tracked_objects_h_list:
time_passed_line = tracked_object_h.find_closest_detection_to_line(line).frame / fps
# Vehículos del dataset candidatos.
candidates = [car for car in cars
if car['carId'] not in dataset_cars_ids_matched and
abs(car['timeIntersectionLastShifted'] - time_passed_line) < max_time_diff]
# Si se eligió hacer matching únicamente con vehículos válidos, filtrar los candidatos solo
# válidos.
if only_match_with_valid_cars:
candidates = [car for car in candidates if car['valid']]
# Ordenarlos por el que pasó en el instante más cercano y realizar el emparejamiento con él.
if len(candidates) > 0:
candidates.sort(
key=lambda car: abs(car['timeIntersectionLastShifted'] - time_passed_line))
candidate = candidates[0]
# Marcar el candidato como emparejado.
dataset_cars_ids_matched.append(candidate['carId'])
# Copiar los datos para editar sus ids y mantener los originales.
candidate = candidate.copy()
tracked_object = copy(tracked_objects[tracked_object_h.id])
tracked_object_h = copy(tracked_object_h)
# Asignar el nuevo id y actualizarlo.
candidate['carId'] = id_
tracked_object.id = id_
tracked_object_h.id = id_
id_ += 1
# Realizar el emparejamiento.
tracked_objects_matched.append(tracked_object)
tracked_objects_h_matched.append(tracked_object_h)
cars_matched.append(candidate)
t.update()
tracked_objects_mapped = TrackedObjects()
tracked_objects_mapped.tracked_objects = tracked_objects_matched
tracked_objects_h_mapped = TrackedObjects()
tracked_objects_h_mapped.tracked_objects = tracked_objects_h_matched
return cars_matched, tracked_objects_mapped, tracked_objects_h_mapped
|
[
"def",
"map_dataset_to_observations",
"(",
"dataset",
":",
"dict",
",",
"tracked_objects",
":",
"TrackedObjects",
",",
"tracked_objects_h",
":",
"TrackedObjects",
",",
"line",
":",
"Tuple",
"[",
"Point2D",
",",
"Point2D",
"]",
",",
"max_time_diff",
":",
"float",
"=",
"0.4",
",",
"only_match_with_valid_cars",
":",
"bool",
"=",
"False",
",",
"verbose",
":",
"bool",
"=",
"False",
")",
"->",
"Tuple",
"[",
"List",
"[",
"Dict",
"]",
",",
"TrackedObjects",
",",
"TrackedObjects",
"]",
":",
"fps",
":",
"float",
"=",
"dataset",
"[",
"'fps'",
"]",
"cars",
":",
"List",
"[",
"Dict",
"]",
"=",
"dataset",
"[",
"'cars'",
"]",
".",
"copy",
"(",
")",
"tracked_objects_h_list",
":",
"List",
"[",
"TrackedObject",
"]",
"=",
"list",
"(",
"tracked_objects_h",
")",
"# 1. Reordenar tracked_objects_h por su orden de llegada a la línea final.",
"tracked_objects_h_list",
".",
"sort",
"(",
"key",
"=",
"lambda",
"tobj",
":",
"tobj",
".",
"find_closest_detection_to_line",
"(",
"line",
")",
".",
"frame",
")",
"# 2. Crear el diccionario de coches anotados y la lista de objetos seguidos con el",
"# emparejamiento correcto.",
"dataset_cars_ids_matched",
":",
"List",
"[",
"int",
"]",
"=",
"[",
"]",
"tracked_objects_matched",
":",
"List",
"[",
"TrackedObject",
"]",
"=",
"[",
"]",
"tracked_objects_h_matched",
":",
"List",
"[",
"TrackedObject",
"]",
"=",
"[",
"]",
"cars_matched",
":",
"List",
"[",
"Dict",
"]",
"=",
"[",
"]",
"id_",
"=",
"0",
"t",
"=",
"tqdm",
"(",
"total",
"=",
"len",
"(",
"tracked_objects_h_list",
")",
",",
"desc",
"=",
"'Mapping dataset to tracked objects.'",
",",
"disable",
"=",
"not",
"verbose",
")",
"for",
"tracked_object_h",
"in",
"tracked_objects_h_list",
":",
"time_passed_line",
"=",
"tracked_object_h",
".",
"find_closest_detection_to_line",
"(",
"line",
")",
".",
"frame",
"/",
"fps",
"# Vehículos del dataset candidatos.",
"candidates",
"=",
"[",
"car",
"for",
"car",
"in",
"cars",
"if",
"car",
"[",
"'carId'",
"]",
"not",
"in",
"dataset_cars_ids_matched",
"and",
"abs",
"(",
"car",
"[",
"'timeIntersectionLastShifted'",
"]",
"-",
"time_passed_line",
")",
"<",
"max_time_diff",
"]",
"# Si se eligió hacer matching únicamente con vehículos válidos, filtrar los candidatos solo",
"# válidos.",
"if",
"only_match_with_valid_cars",
":",
"candidates",
"=",
"[",
"car",
"for",
"car",
"in",
"candidates",
"if",
"car",
"[",
"'valid'",
"]",
"]",
"# Ordenarlos por el que pasó en el instante más cercano y realizar el emparejamiento con él.",
"if",
"len",
"(",
"candidates",
")",
">",
"0",
":",
"candidates",
".",
"sort",
"(",
"key",
"=",
"lambda",
"car",
":",
"abs",
"(",
"car",
"[",
"'timeIntersectionLastShifted'",
"]",
"-",
"time_passed_line",
")",
")",
"candidate",
"=",
"candidates",
"[",
"0",
"]",
"# Marcar el candidato como emparejado.",
"dataset_cars_ids_matched",
".",
"append",
"(",
"candidate",
"[",
"'carId'",
"]",
")",
"# Copiar los datos para editar sus ids y mantener los originales.",
"candidate",
"=",
"candidate",
".",
"copy",
"(",
")",
"tracked_object",
"=",
"copy",
"(",
"tracked_objects",
"[",
"tracked_object_h",
".",
"id",
"]",
")",
"tracked_object_h",
"=",
"copy",
"(",
"tracked_object_h",
")",
"# Asignar el nuevo id y actualizarlo.",
"candidate",
"[",
"'carId'",
"]",
"=",
"id_",
"tracked_object",
".",
"id",
"=",
"id_",
"tracked_object_h",
".",
"id",
"=",
"id_",
"id_",
"+=",
"1",
"# Realizar el emparejamiento.",
"tracked_objects_matched",
".",
"append",
"(",
"tracked_object",
")",
"tracked_objects_h_matched",
".",
"append",
"(",
"tracked_object_h",
")",
"cars_matched",
".",
"append",
"(",
"candidate",
")",
"t",
".",
"update",
"(",
")",
"tracked_objects_mapped",
"=",
"TrackedObjects",
"(",
")",
"tracked_objects_mapped",
".",
"tracked_objects",
"=",
"tracked_objects_matched",
"tracked_objects_h_mapped",
"=",
"TrackedObjects",
"(",
")",
"tracked_objects_h_mapped",
".",
"tracked_objects",
"=",
"tracked_objects_h_matched",
"return",
"cars_matched",
",",
"tracked_objects_mapped",
",",
"tracked_objects_h_mapped"
] |
[
9,
0
] |
[
82,
73
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
Hasar2GenComandos.cancelAnyDocument
|
(self)
|
return self.cancelDocument()
|
Este comando no esta disponible en la 2da generación de impresoras, es necesaria su declaración por el uso del TraductorFiscal
|
Este comando no esta disponible en la 2da generación de impresoras, es necesaria su declaración por el uso del TraductorFiscal
|
def cancelAnyDocument(self):
"""Este comando no esta disponible en la 2da generación de impresoras, es necesaria su declaración por el uso del TraductorFiscal """
return self.cancelDocument()
|
[
"def",
"cancelAnyDocument",
"(",
"self",
")",
":",
"return",
"self",
".",
"cancelDocument",
"(",
")"
] |
[
409,
1
] |
[
411,
30
] | null |
python
|
es
|
['es', 'es', 'es']
|
True
| true | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.