identifier
stringlengths 0
89
| parameters
stringlengths 0
399
| return_statement
stringlengths 0
982
⌀ | docstring
stringlengths 10
3.04k
| docstring_summary
stringlengths 0
3.04k
| function
stringlengths 13
25.8k
| function_tokens
sequence | start_point
sequence | end_point
sequence | argument_list
null | language
stringclasses 3
values | docstring_language
stringclasses 4
values | docstring_language_predictions
stringclasses 4
values | is_langid_reliable
stringclasses 2
values | is_langid_extra_reliable
bool 1
class | type
stringclasses 9
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
computeR | (x_train) | return R | Función que calcula el valor de R (diámetro) del
conjunto de datos de entrenamiento, x_train | Función que calcula el valor de R (diámetro) del
conjunto de datos de entrenamiento, x_train | def computeR(x_train):
""" Función que calcula el valor de R (diámetro) del
conjunto de datos de entrenamiento, x_train """
dist = []
x_train_roll = x_train.copy()
for i in range(x_train.shape[0]):
x_train_roll = np.roll(x_train_roll,1,axis=0)
dist.append(np.amax(np.linalg.norm(x_train-x_train_roll,axis=1)))
R = np.amax(dist)
return R | [
"def",
"computeR",
"(",
"x_train",
")",
":",
"dist",
"=",
"[",
"]",
"x_train_roll",
"=",
"x_train",
".",
"copy",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"x_train",
".",
"shape",
"[",
"0",
"]",
")",
":",
"x_train_roll",
"=",
"np",
".",
"roll",
"(",
"x_train_roll",
",",
"1",
",",
"axis",
"=",
"0",
")",
"dist",
".",
"append",
"(",
"np",
".",
"amax",
"(",
"np",
".",
"linalg",
".",
"norm",
"(",
"x_train",
"-",
"x_train_roll",
",",
"axis",
"=",
"1",
")",
")",
")",
"R",
"=",
"np",
".",
"amax",
"(",
"dist",
")",
"return",
"R"
] | [
10,
0
] | [
21,
12
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
handleMessage | (msg) | Broadcast permite enviarselas a todos los clientes | Broadcast permite enviarselas a todos los clientes | def handleMessage(msg):
print("Message: " + msg)
"""Broadcast permite enviarselas a todos los clientes"""
send(msg, broadcast=True) | [
"def",
"handleMessage",
"(",
"msg",
")",
":",
"print",
"(",
"\"Message: \"",
"+",
"msg",
")",
"send",
"(",
"msg",
",",
"broadcast",
"=",
"True",
")"
] | [
13,
0
] | [
16,
29
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
DriverInterface.close | (self) | Cierra recurso de conexion con impresora | Cierra recurso de conexion con impresora | def close(self):
"""Cierra recurso de conexion con impresora"""
raise NotImplementedError | [
"def",
"close",
"(",
"self",
")",
":",
"raise",
"NotImplementedError"
] | [
8,
4
] | [
10,
33
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_cuerpofuncion1 | (t) | cuerpofuncion : CADDOLAR declaraciones cuerpo CADDOLAR PTCOMA | cuerpofuncion : CADDOLAR declaraciones cuerpo CADDOLAR PTCOMA | def p_cuerpofuncion1(t):
'cuerpofuncion : CADDOLAR declaraciones cuerpo CADDOLAR PTCOMA'
t[0] = getCuerpoFuncion(t) | [
"def",
"p_cuerpofuncion1",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"getCuerpoFuncion",
"(",
"t",
")"
] | [
579,
0
] | [
581,
30
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ProductModelSerializer.validate | (self, data) | return data | Varifica que el stock limited sea mayor que el stock inicial. | Varifica que el stock limited sea mayor que el stock inicial. | def validate(self, data):
"""Varifica que el stock limited sea mayor que el stock inicial."""
if data.get('stock',0) > data.get('stock_limited',0):
raise serializers.ValidationError('El stock limited debe ser mayor que el stock inicial')
return data | [
"def",
"validate",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
".",
"get",
"(",
"'stock'",
",",
"0",
")",
">",
"data",
".",
"get",
"(",
"'stock_limited'",
",",
"0",
")",
":",
"raise",
"serializers",
".",
"ValidationError",
"(",
"'El stock limited debe ser mayor que el stock inicial'",
")",
"return",
"data"
] | [
51,
4
] | [
55,
19
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_salida_instrucciones | (t) | instrucciones : instruccion | instrucciones : instruccion | def p_salida_instrucciones(t) :
'instrucciones : instruccion' | [
"def",
"p_salida_instrucciones",
"(",
"t",
")",
":"
] | [
159,
0
] | [
160,
36
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Matrix.__mul__ | (self, other) | Metodo para la multiplicacion de matrices. | Metodo para la multiplicacion de matrices. | def __mul__(self, other):
""" Metodo para la multiplicacion de matrices. """
if type(other) == int or type(other) == float:
new = [map(lambda r: other * r, i) for i in self]
return Matrix(new)
else:
if self.check("mul", other):
tra = self.transpose()
fa = len(tra)
cb = len(other)
new = [[0] * fa for t in xrange(cb)]
for f in xrange(fa):
for c in xrange(cb):
new[c][f] = sum(map(lambda r, s: r * s, tra[f], other[c]))
return Matrix(new)
else:
raise IndexError("Matrix: Dimensions are not a match to multiply.") | [
"def",
"__mul__",
"(",
"self",
",",
"other",
")",
":",
"if",
"type",
"(",
"other",
")",
"==",
"int",
"or",
"type",
"(",
"other",
")",
"==",
"float",
":",
"new",
"=",
"[",
"map",
"(",
"lambda",
"r",
":",
"other",
"*",
"r",
",",
"i",
")",
"for",
"i",
"in",
"self",
"]",
"return",
"Matrix",
"(",
"new",
")",
"else",
":",
"if",
"self",
".",
"check",
"(",
"\"mul\"",
",",
"other",
")",
":",
"tra",
"=",
"self",
".",
"transpose",
"(",
")",
"fa",
"=",
"len",
"(",
"tra",
")",
"cb",
"=",
"len",
"(",
"other",
")",
"new",
"=",
"[",
"[",
"0",
"]",
"*",
"fa",
"for",
"t",
"in",
"xrange",
"(",
"cb",
")",
"]",
"for",
"f",
"in",
"xrange",
"(",
"fa",
")",
":",
"for",
"c",
"in",
"xrange",
"(",
"cb",
")",
":",
"new",
"[",
"c",
"]",
"[",
"f",
"]",
"=",
"sum",
"(",
"map",
"(",
"lambda",
"r",
",",
"s",
":",
"r",
"*",
"s",
",",
"tra",
"[",
"f",
"]",
",",
"other",
"[",
"c",
"]",
")",
")",
"return",
"Matrix",
"(",
"new",
")",
"else",
":",
"raise",
"IndexError",
"(",
"\"Matrix: Dimensions are not a match to multiply.\"",
")"
] | [
37,
4
] | [
53,
83
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
_get_y_label | (method) | return y_label | generates y-label string
Args:
method : String
Method for model evaluation used
Returns:
y_label : String
| generates y-label string
Args:
method : String
Method for model evaluation used
Returns:
y_label : String
| def _get_y_label(method):
""" generates y-label string
Args:
method : String
Method for model evaluation used
Returns:
y_label : String
"""
if method.lower() == 'cosine':
y_label = '[across-subject mean of cosine similarity]'
if method.lower() in ['cosine_cov', 'whitened cosine']:
y_label = '[across-subject mean of whitened-RDM cosine]'
elif method.lower() == 'spearman':
y_label = '[across-subject mean of Spearman r rank correlation]'
elif method.lower() in ['corr', 'pearson']:
y_label = '[across-subject mean of Pearson r correlation]'
elif method.lower() in ['whitened pearson', 'corr_cov']:
y_label = '[across-subject mean of whitened-RDM Pearson r correlation]'
elif method.lower() in ['kendall', 'tau-b']:
y_label = '[across-subject mean of Kendall tau-b rank correlation]'
elif method.lower() == 'tau-a':
y_label = '[across-subject mean of ' \
+ 'Kendall tau-a rank correlation]'
elif method.lower() == 'neg_riem_dist':
y_label = '[across-subject mean of ' \
+ 'negative riemannian distance]'
return y_label | [
"def",
"_get_y_label",
"(",
"method",
")",
":",
"if",
"method",
".",
"lower",
"(",
")",
"==",
"'cosine'",
":",
"y_label",
"=",
"'[across-subject mean of cosine similarity]'",
"if",
"method",
".",
"lower",
"(",
")",
"in",
"[",
"'cosine_cov'",
",",
"'whitened cosine'",
"]",
":",
"y_label",
"=",
"'[across-subject mean of whitened-RDM cosine]'",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'spearman'",
":",
"y_label",
"=",
"'[across-subject mean of Spearman r rank correlation]'",
"elif",
"method",
".",
"lower",
"(",
")",
"in",
"[",
"'corr'",
",",
"'pearson'",
"]",
":",
"y_label",
"=",
"'[across-subject mean of Pearson r correlation]'",
"elif",
"method",
".",
"lower",
"(",
")",
"in",
"[",
"'whitened pearson'",
",",
"'corr_cov'",
"]",
":",
"y_label",
"=",
"'[across-subject mean of whitened-RDM Pearson r correlation]'",
"elif",
"method",
".",
"lower",
"(",
")",
"in",
"[",
"'kendall'",
",",
"'tau-b'",
"]",
":",
"y_label",
"=",
"'[across-subject mean of Kendall tau-b rank correlation]'",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'tau-a'",
":",
"y_label",
"=",
"'[across-subject mean of '",
"+",
"'Kendall tau-a rank correlation]'",
"elif",
"method",
".",
"lower",
"(",
")",
"==",
"'neg_riem_dist'",
":",
"y_label",
"=",
"'[across-subject mean of '",
"+",
"'negative riemannian distance]'",
"return",
"y_label"
] | [
983,
0
] | [
1012,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
OnlyEven | (*numbers) | return EVENS | Solo retorna los pares | Solo retorna los pares | def OnlyEven(*numbers):
"""Solo retorna los pares"""
EVENS=[n for n in numbers if n%2==0]
return EVENS | [
"def",
"OnlyEven",
"(",
"*",
"numbers",
")",
":",
"EVENS",
"=",
"[",
"n",
"for",
"n",
"in",
"numbers",
"if",
"n",
"%",
"2",
"==",
"0",
"]",
"return",
"EVENS"
] | [
3,
0
] | [
6,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_nuevo_prop_db | (t) | nuevo_prop : CADENA
| CURRENT_USER
| SESSION_USER | nuevo_prop : CADENA
| CURRENT_USER
| SESSION_USER | def p_nuevo_prop_db(t):
''' nuevo_prop : CADENA
| CURRENT_USER
| SESSION_USER'''
reportebnf.append(bnf["p_nuevo_prop_db"])
t[0] = IdentificadorDML("OWNER",t.lineno(1),t.lexpos(1)+1,t[1]) | [
"def",
"p_nuevo_prop_db",
"(",
"t",
")",
":",
"reportebnf",
".",
"append",
"(",
"bnf",
"[",
"\"p_nuevo_prop_db\"",
"]",
")",
"t",
"[",
"0",
"]",
"=",
"IdentificadorDML",
"(",
"\"OWNER\"",
",",
"t",
".",
"lineno",
"(",
"1",
")",
",",
"t",
".",
"lexpos",
"(",
"1",
")",
"+",
"1",
",",
"t",
"[",
"1",
"]",
")"
] | [
2181,
0
] | [
2186,
67
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones34 | (p) | funciones : ASINH PABRE expresion PCIERRA | funciones : ASINH PABRE expresion PCIERRA | def p_funciones34(p):
'funciones : ASINH PABRE expresion PCIERRA' | [
"def",
"p_funciones34",
"(",
"p",
")",
":"
] | [
400,
0
] | [
401,
47
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ArregloDinamico._reducir | (self) | Reduce la capacidad del arreglo si es necesario | Reduce la capacidad del arreglo si es necesario | def _reducir(self) -> None:
"""Reduce la capacidad del arreglo si es necesario"""
if self._n < self._capacidad // self._factor ** 2:
self._redimensionar(self._capacidad // self._factor) | [
"def",
"_reducir",
"(",
"self",
")",
"->",
"None",
":",
"if",
"self",
".",
"_n",
"<",
"self",
".",
"_capacidad",
"//",
"self",
".",
"_factor",
"**",
"2",
":",
"self",
".",
"_redimensionar",
"(",
"self",
".",
"_capacidad",
"//",
"self",
".",
"_factor",
")"
] | [
127,
4
] | [
130,
64
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ServiceCallback.net2services | (networkid: int, *, cursor) | Obtiene los nombres de los servicios que les pertenezcan a un nodo | Obtiene los nombres de los servicios que les pertenezcan a un nodo | async def net2services(networkid: int, *, cursor) -> AsyncIterator[str]:
"""Obtiene los nombres de los servicios que les pertenezcan a un nodo"""
await cursor.execute(
"SELECT service FROM services WHERE id_network = %s",
(networkid,)
)
while (service := await cursor.fetchone()):
yield service | [
"async",
"def",
"net2services",
"(",
"networkid",
":",
"int",
",",
"*",
",",
"cursor",
")",
"->",
"AsyncIterator",
"[",
"str",
"]",
":",
"await",
"cursor",
".",
"execute",
"(",
"\"SELECT service FROM services WHERE id_network = %s\"",
",",
"(",
"networkid",
",",
")",
")",
"while",
"(",
"service",
":=",
"await",
"cursor",
".",
"fetchone",
"(",
")",
")",
":",
"yield",
"service"
] | [
805,
4
] | [
815,
25
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
inicio_sesion | () | return render_template("auth/login.html", form=form, titulo="Inicio de Sesion - NOW LMS") | Inicio de sesión del usuario. | Inicio de sesión del usuario. | def inicio_sesion():
"""Inicio de sesión del usuario."""
form = LoginForm()
if form.validate_on_submit():
if validar_acceso(form.usuario.data, form.acceso.data):
identidad = Usuario.query.filter_by(usuario=form.usuario.data).first()
if identidad.activo:
login_user(identidad)
return redirect(url_for("panel"))
else:
flash("Su cuenta esta inactiva.")
return INICIO_SESION
else:
flash("Inicio de Sesion Incorrecto.")
return INICIO_SESION
return render_template("auth/login.html", form=form, titulo="Inicio de Sesion - NOW LMS") | [
"def",
"inicio_sesion",
"(",
")",
":",
"form",
"=",
"LoginForm",
"(",
")",
"if",
"form",
".",
"validate_on_submit",
"(",
")",
":",
"if",
"validar_acceso",
"(",
"form",
".",
"usuario",
".",
"data",
",",
"form",
".",
"acceso",
".",
"data",
")",
":",
"identidad",
"=",
"Usuario",
".",
"query",
".",
"filter_by",
"(",
"usuario",
"=",
"form",
".",
"usuario",
".",
"data",
")",
".",
"first",
"(",
")",
"if",
"identidad",
".",
"activo",
":",
"login_user",
"(",
"identidad",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"\"panel\"",
")",
")",
"else",
":",
"flash",
"(",
"\"Su cuenta esta inactiva.\"",
")",
"return",
"INICIO_SESION",
"else",
":",
"flash",
"(",
"\"Inicio de Sesion Incorrecto.\"",
")",
"return",
"INICIO_SESION",
"return",
"render_template",
"(",
"\"auth/login.html\"",
",",
"form",
"=",
"form",
",",
"titulo",
"=",
"\"Inicio de Sesion - NOW LMS\"",
")"
] | [
561,
0
] | [
576,
93
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_ldeclaracionesg4x | (t) | ldeclaracionesg : ID PUNTO ID IGUAL expre
| ldeclaracionesg : ID PUNTO ID IGUAL expre
| def p_ldeclaracionesg4x(t):
'''ldeclaracionesg : ID PUNTO ID IGUAL expre
'''
t[0] = AsignacionC3D(t[1],t[3],t[5],None,t.lexer.lineno, t.lexer.lexpos) | [
"def",
"p_ldeclaracionesg4x",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"AsignacionC3D",
"(",
"t",
"[",
"1",
"]",
",",
"t",
"[",
"3",
"]",
",",
"t",
"[",
"5",
"]",
",",
"None",
",",
"t",
".",
"lexer",
".",
"lineno",
",",
"t",
".",
"lexer",
".",
"lexpos",
")"
] | [
183,
0
] | [
186,
76
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
DataCleaner.clean_file | (self, rules, output_path) | Aplica las reglas de limpieza y guarda los datos en un csv.
Args:
rules (list): Lista de reglas de limpieza.
| Aplica las reglas de limpieza y guarda los datos en un csv. | def clean_file(self, rules, output_path):
"""Aplica las reglas de limpieza y guarda los datos en un csv.
Args:
rules (list): Lista de reglas de limpieza.
"""
self.clean(rules)
self.save(output_path) | [
"def",
"clean_file",
"(",
"self",
",",
"rules",
",",
"output_path",
")",
":",
"self",
".",
"clean",
"(",
"rules",
")",
"self",
".",
"save",
"(",
"output_path",
")"
] | [
233,
4
] | [
240,
30
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Hasar2GenComandos.closeDocument | (self, copias = 0, email = None) | return self.conector.sendCommand( jdata ) | Cierra el documento que esté abierto | Cierra el documento que esté abierto | def closeDocument(self, copias = 0, email = None):
"""Cierra el documento que esté abierto"""
jdata = {"CerrarDocumento": {
"Copias" : str(copias),
}}
jdata["CerrarDocumento"]["DireccionEMail"] = email
return self.conector.sendCommand( jdata ) | [
"def",
"closeDocument",
"(",
"self",
",",
"copias",
"=",
"0",
",",
"email",
"=",
"None",
")",
":",
"jdata",
"=",
"{",
"\"CerrarDocumento\"",
":",
"{",
"\"Copias\"",
":",
"str",
"(",
"copias",
")",
",",
"}",
"}",
"jdata",
"[",
"\"CerrarDocumento\"",
"]",
"[",
"\"DireccionEMail\"",
"]",
"=",
"email",
"return",
"self",
".",
"conector",
".",
"sendCommand",
"(",
"jdata",
")"
] | [
132,
1
] | [
140,
43
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
TrackingVideo._draw_object | (self,
fid: int,
frame: Image,
tracked_object: TrackedObject,
tracked_object_detection: 'TrackedObjectDetection') | return frame | Realiza el dibujado de un objeto en el frame actual.
:param fid: número del frame.
:param frame: frame.
:param tracked_object: objeto con el seguimiento.
:param tracked_object_detection: detección del objeto seguido en el frame actual.
:return: frame con el objeto dibujados.
| Realiza el dibujado de un objeto en el frame actual. | def _draw_object(self,
fid: int,
frame: Image,
tracked_object: TrackedObject,
tracked_object_detection: 'TrackedObjectDetection') -> Image:
"""Realiza el dibujado de un objeto en el frame actual.
:param fid: número del frame.
:param frame: frame.
:param tracked_object: objeto con el seguimiento.
:param tracked_object_detection: detección del objeto seguido en el frame actual.
:return: frame con el objeto dibujados.
"""
# Inicializar la información del objeto
object_information_texts = []
# DRAW_OBJECTS_IDS
if self.get_property(TrackingVideoProperty.DRAW_OBJECTS_IDS):
object_information_texts.append(f'ID: {tracked_object_detection.id}')
# DRAW_OBJECTS_LABELS
if self.get_property(TrackingVideoProperty.DRAW_OBJECTS_LABELS):
object_information_texts.append(f'Label: {tracked_object_detection.object.label}')
# DRAW_OBJECTS_SCORES
if self.get_property(TrackingVideoProperty.DRAW_OBJECTS_SCORES):
object_information_texts.append(f'Score: '
f'{round(tracked_object_detection.object.score, 3)}')
# DRAW_OBJECTS_ESTIMATED_SPEED
if self.get_property(TrackingVideoProperty.DRAW_OBJECTS_ESTIMATED_SPEED):
speed = self._get_object_estimated_speed(tracked_object, tracked_object_detection)
object_information_texts.append(f'Estimated speed: {speed} Km/h')
# DRAW_OBJECTS_BOUNDING_BOXES
if self.get_property(TrackingVideoProperty.DRAW_OBJECTS_BOUNDING_BOXES):
frame = self._draw_object_bounding_box(frame, tracked_object_detection)
# DRAW_OBJECTS_TRACES
if self.get_property(TrackingVideoProperty.DRAW_OBJECTS_TRACES):
frame = self._draw_object_trace(fid, frame, tracked_object)
# DRAW_OBJECTS_BOUNDING_BOXES_TRACES
if self.get_property(TrackingVideoProperty.DRAW_OBJECTS_BOUNDING_BOXES_TRACES):
frame = self._draw_object_bounding_box_trace(fid, frame, tracked_object)
# Dibujar la información del vehículo
frame = self._draw_object_informations(fid, frame, tracked_object, tracked_object_detection,
object_information_texts)
return frame | [
"def",
"_draw_object",
"(",
"self",
",",
"fid",
":",
"int",
",",
"frame",
":",
"Image",
",",
"tracked_object",
":",
"TrackedObject",
",",
"tracked_object_detection",
":",
"'TrackedObjectDetection'",
")",
"->",
"Image",
":",
"# Inicializar la información del objeto",
"object_information_texts",
"=",
"[",
"]",
"# DRAW_OBJECTS_IDS",
"if",
"self",
".",
"get_property",
"(",
"TrackingVideoProperty",
".",
"DRAW_OBJECTS_IDS",
")",
":",
"object_information_texts",
".",
"append",
"(",
"f'ID: {tracked_object_detection.id}'",
")",
"# DRAW_OBJECTS_LABELS",
"if",
"self",
".",
"get_property",
"(",
"TrackingVideoProperty",
".",
"DRAW_OBJECTS_LABELS",
")",
":",
"object_information_texts",
".",
"append",
"(",
"f'Label: {tracked_object_detection.object.label}'",
")",
"# DRAW_OBJECTS_SCORES",
"if",
"self",
".",
"get_property",
"(",
"TrackingVideoProperty",
".",
"DRAW_OBJECTS_SCORES",
")",
":",
"object_information_texts",
".",
"append",
"(",
"f'Score: '",
"f'{round(tracked_object_detection.object.score, 3)}'",
")",
"# DRAW_OBJECTS_ESTIMATED_SPEED",
"if",
"self",
".",
"get_property",
"(",
"TrackingVideoProperty",
".",
"DRAW_OBJECTS_ESTIMATED_SPEED",
")",
":",
"speed",
"=",
"self",
".",
"_get_object_estimated_speed",
"(",
"tracked_object",
",",
"tracked_object_detection",
")",
"object_information_texts",
".",
"append",
"(",
"f'Estimated speed: {speed} Km/h'",
")",
"# DRAW_OBJECTS_BOUNDING_BOXES",
"if",
"self",
".",
"get_property",
"(",
"TrackingVideoProperty",
".",
"DRAW_OBJECTS_BOUNDING_BOXES",
")",
":",
"frame",
"=",
"self",
".",
"_draw_object_bounding_box",
"(",
"frame",
",",
"tracked_object_detection",
")",
"# DRAW_OBJECTS_TRACES",
"if",
"self",
".",
"get_property",
"(",
"TrackingVideoProperty",
".",
"DRAW_OBJECTS_TRACES",
")",
":",
"frame",
"=",
"self",
".",
"_draw_object_trace",
"(",
"fid",
",",
"frame",
",",
"tracked_object",
")",
"# DRAW_OBJECTS_BOUNDING_BOXES_TRACES",
"if",
"self",
".",
"get_property",
"(",
"TrackingVideoProperty",
".",
"DRAW_OBJECTS_BOUNDING_BOXES_TRACES",
")",
":",
"frame",
"=",
"self",
".",
"_draw_object_bounding_box_trace",
"(",
"fid",
",",
"frame",
",",
"tracked_object",
")",
"# Dibujar la información del vehículo",
"frame",
"=",
"self",
".",
"_draw_object_informations",
"(",
"fid",
",",
"frame",
",",
"tracked_object",
",",
"tracked_object_detection",
",",
"object_information_texts",
")",
"return",
"frame"
] | [
121,
4
] | [
162,
20
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
ModelGraphs.plot_compare_accs | (history1, history2, name1="Red 1",
name2="Red 2", title="Graph title") | Compara accuracies de dos entrenamientos con nombres name1 y name2 | Compara accuracies de dos entrenamientos con nombres name1 y name2 | def plot_compare_accs(history1, history2, name1="Red 1",
name2="Red 2", title="Graph title"):
"""Compara accuracies de dos entrenamientos con nombres name1 y name2"""
plt.plot(history1.history['acc'], color="green")
plt.plot(history1.history['val_acc'], 'r--', color="green")
plt.plot(history2.history['acc'], color="blue")
plt.plot(history2.history['val_acc'], 'r--', color="blue")
plt.title(title)
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train ' + name1, 'Val ' + name1,
'Train ' + name2, 'Val ' + name2],
loc='lower right')
plt.show() | [
"def",
"plot_compare_accs",
"(",
"history1",
",",
"history2",
",",
"name1",
"=",
"\"Red 1\"",
",",
"name2",
"=",
"\"Red 2\"",
",",
"title",
"=",
"\"Graph title\"",
")",
":",
"plt",
".",
"plot",
"(",
"history1",
".",
"history",
"[",
"'acc'",
"]",
",",
"color",
"=",
"\"green\"",
")",
"plt",
".",
"plot",
"(",
"history1",
".",
"history",
"[",
"'val_acc'",
"]",
",",
"'r--'",
",",
"color",
"=",
"\"green\"",
")",
"plt",
".",
"plot",
"(",
"history2",
".",
"history",
"[",
"'acc'",
"]",
",",
"color",
"=",
"\"blue\"",
")",
"plt",
".",
"plot",
"(",
"history2",
".",
"history",
"[",
"'val_acc'",
"]",
",",
"'r--'",
",",
"color",
"=",
"\"blue\"",
")",
"plt",
".",
"title",
"(",
"title",
")",
"plt",
".",
"ylabel",
"(",
"'Accuracy'",
")",
"plt",
".",
"xlabel",
"(",
"'Epoch'",
")",
"plt",
".",
"legend",
"(",
"[",
"'Train '",
"+",
"name1",
",",
"'Val '",
"+",
"name1",
",",
"'Train '",
"+",
"name2",
",",
"'Val '",
"+",
"name2",
"]",
",",
"loc",
"=",
"'lower right'",
")",
"plt",
".",
"show",
"(",
")"
] | [
44,
4
] | [
57,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Profesional.importar_matriculado | (self, row) | Importar desde una base de datos específica matriculados.
Ejemplo de row de Excel
AFILIADO: 42000
NOMBRE: JUAN PEREZ
PROFESION: LIC. EN PSICOLOGIA
DOCUMENTO: 5556460
TELEFONO: 03555-555555
DOMICILIO: CHACO 31
BARRIO
LOCALIDAD: RIO CEBALLOS
DEPARTAMENTO: COLON
VOTA: S
| Importar desde una base de datos específica matriculados.
Ejemplo de row de Excel
AFILIADO: 42000
NOMBRE: JUAN PEREZ
PROFESION: LIC. EN PSICOLOGIA
DOCUMENTO: 5556460
TELEFONO: 03555-555555
DOMICILIO: CHACO 31
BARRIO
LOCALIDAD: RIO CEBALLOS
DEPARTAMENTO: COLON
VOTA: S
| def importar_matriculado(self, row):
"""Importar desde una base de datos específica matriculados.
Ejemplo de row de Excel
AFILIADO: 42000
NOMBRE: JUAN PEREZ
PROFESION: LIC. EN PSICOLOGIA
DOCUMENTO: 5556460
TELEFONO: 03555-555555
DOMICILIO: CHACO 31
BARRIO
LOCALIDAD: RIO CEBALLOS
DEPARTAMENTO: COLON
VOTA: S
"""
self.nombres = row["NOMBRE"].strip()
self.matricula_profesional = str(row["AFILIADO"])
self.profesion = row["PROFESION"].strip()
self.numero_documento = str(row["DOCUMENTO"])
tel = row.get("TELEFONO", "")
tel = str(tel) if type(tel) == int else tel.strip()
# self.localidad = row.get('LOCALIDAD', '').strip()
# self.departamento = row.get('DEPARTAMENTO', '').strip()
# domicilio = '{}, {}, {}, {}, Córdoba'.format(
# row.get('DOMICILIO', '').strip(),
# row.get('BARRIO', ''),
# self.localidad,
# self.departamento
# )
# self.domicilio = domicilio
self.agregar_dato_de_contacto('teléfono', tel) | [
"def",
"importar_matriculado",
"(",
"self",
",",
"row",
")",
":",
"self",
".",
"nombres",
"=",
"row",
"[",
"\"NOMBRE\"",
"]",
".",
"strip",
"(",
")",
"self",
".",
"matricula_profesional",
"=",
"str",
"(",
"row",
"[",
"\"AFILIADO\"",
"]",
")",
"self",
".",
"profesion",
"=",
"row",
"[",
"\"PROFESION\"",
"]",
".",
"strip",
"(",
")",
"self",
".",
"numero_documento",
"=",
"str",
"(",
"row",
"[",
"\"DOCUMENTO\"",
"]",
")",
"tel",
"=",
"row",
".",
"get",
"(",
"\"TELEFONO\"",
",",
"\"\"",
")",
"tel",
"=",
"str",
"(",
"tel",
")",
"if",
"type",
"(",
"tel",
")",
"==",
"int",
"else",
"tel",
".",
"strip",
"(",
")",
"# self.localidad = row.get('LOCALIDAD', '').strip()",
"# self.departamento = row.get('DEPARTAMENTO', '').strip()",
"# domicilio = '{}, {}, {}, {}, Córdoba'.format(",
"# row.get('DOMICILIO', '').strip(),",
"# row.get('BARRIO', ''),",
"# self.localidad,",
"# self.departamento",
"# )",
"# self.domicilio = domicilio",
"self",
".",
"agregar_dato_de_contacto",
"(",
"'teléfono',",
" ",
"el)",
""
] | [
45,
4
] | [
74,
55
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_cuerpofuncion | (t) | cuerpofuncion : CADDOLAR declaraciones cuerpo CADDOLAR LANGUAGE PLPGSQL PTCOMA | cuerpofuncion : CADDOLAR declaraciones cuerpo CADDOLAR LANGUAGE PLPGSQL PTCOMA | def p_cuerpofuncion(t):
'cuerpofuncion : CADDOLAR declaraciones cuerpo CADDOLAR LANGUAGE PLPGSQL PTCOMA'
t[0] = getCuerpoFuncion(t) | [
"def",
"p_cuerpofuncion",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"getCuerpoFuncion",
"(",
"t",
")"
] | [
575,
0
] | [
577,
30
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones33 | (p) | funciones : ACOSH PABRE expresion PCIERRA | funciones : ACOSH PABRE expresion PCIERRA | def p_funciones33(p):
'funciones : ACOSH PABRE expresion PCIERRA' | [
"def",
"p_funciones33",
"(",
"p",
")",
":"
] | [
397,
0
] | [
398,
47
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
UserCallback.get_password | (userid: int, *, cursor) | return password | Obtiene la contraseña de un usuario determinado | Obtiene la contraseña de un usuario determinado | async def get_password(userid: int, *, cursor) -> Tuple[str]:
"""Obtiene la contraseña de un usuario determinado"""
await cursor.execute(
"SELECT password FROM users WHERE id = %s LIMIT 1", (userid,)
)
password = await cursor.fetchone()
return password | [
"async",
"def",
"get_password",
"(",
"userid",
":",
"int",
",",
"*",
",",
"cursor",
")",
"->",
"Tuple",
"[",
"str",
"]",
":",
"await",
"cursor",
".",
"execute",
"(",
"\"SELECT password FROM users WHERE id = %s LIMIT 1\"",
",",
"(",
"userid",
",",
")",
")",
"password",
"=",
"await",
"cursor",
".",
"fetchone",
"(",
")",
"return",
"password"
] | [
121,
4
] | [
131,
23
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
calcular | (cantidad: int, precio: float) | return monto_antes, descuento, monto_despues | Calcula el descuento y el monto final.
:param cantidad: Cantidad comprada.
:cantidad type: int
:param precio: Precio unitario.
:precio type: float
:return: Tupla con (monto antes del descuento, descuento, monto
después del descuento).
:rtype: tuple
| Calcula el descuento y el monto final. | def calcular(cantidad: int, precio: float) -> tuple:
"""Calcula el descuento y el monto final.
:param cantidad: Cantidad comprada.
:cantidad type: int
:param precio: Precio unitario.
:precio type: float
:return: Tupla con (monto antes del descuento, descuento, monto
después del descuento).
:rtype: tuple
"""
monto_antes = cantidad * precio
descuento = ((cantidad // 5) * 2) * precio
monto_despues = monto_antes - descuento
return monto_antes, descuento, monto_despues | [
"def",
"calcular",
"(",
"cantidad",
":",
"int",
",",
"precio",
":",
"float",
")",
"->",
"tuple",
":",
"monto_antes",
"=",
"cantidad",
"*",
"precio",
"descuento",
"=",
"(",
"(",
"cantidad",
"//",
"5",
")",
"*",
"2",
")",
"*",
"precio",
"monto_despues",
"=",
"monto_antes",
"-",
"descuento",
"return",
"monto_antes",
",",
"descuento",
",",
"monto_despues"
] | [
20,
0
] | [
34,
48
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
DataCleaner._build_data | (self, field, entity_level, filters) | return False | Construye un diccionario con una lista de unidades territoriales
para realizar consultas a la API de normalización Georef utilizando
el método bulk.
Args:
field (str): Nombre del campo a normalizar.
entity_level (str): Nivel de la unidad territorial.
filters (dict): Diccionario con entidades por las cuales filtrar.
Returns:
dict: (dict): Diccionario a utilizar para realizar una consulta.
En caso de error devuelve False.
| Construye un diccionario con una lista de unidades territoriales
para realizar consultas a la API de normalización Georef utilizando
el método bulk. | def _build_data(self, field, entity_level, filters):
"""Construye un diccionario con una lista de unidades territoriales
para realizar consultas a la API de normalización Georef utilizando
el método bulk.
Args:
field (str): Nombre del campo a normalizar.
entity_level (str): Nivel de la unidad territorial.
filters (dict): Diccionario con entidades por las cuales filtrar.
Returns:
dict: (dict): Diccionario a utilizar para realizar una consulta.
En caso de error devuelve False.
"""
body = []
entity_level = self._plural_entity_level(entity_level)
try:
for item, row in self.df.iterrows():
row = row.fillna('0') # reemplaza valores 'nan' por '0'
data = {'nombre': row[field], 'max': 1, 'aplanar': True}
if filters:
filters_builded = self._build_filters(row, filters)
data.update(filters_builded)
body.append(data)
return {entity_level: body}
except KeyError as e:
print('Error: No existe el campo "{}".'.format(e))
except Exception as e:
print(e)
return False | [
"def",
"_build_data",
"(",
"self",
",",
"field",
",",
"entity_level",
",",
"filters",
")",
":",
"body",
"=",
"[",
"]",
"entity_level",
"=",
"self",
".",
"_plural_entity_level",
"(",
"entity_level",
")",
"try",
":",
"for",
"item",
",",
"row",
"in",
"self",
".",
"df",
".",
"iterrows",
"(",
")",
":",
"row",
"=",
"row",
".",
"fillna",
"(",
"'0'",
")",
"# reemplaza valores 'nan' por '0'",
"data",
"=",
"{",
"'nombre'",
":",
"row",
"[",
"field",
"]",
",",
"'max'",
":",
"1",
",",
"'aplanar'",
":",
"True",
"}",
"if",
"filters",
":",
"filters_builded",
"=",
"self",
".",
"_build_filters",
"(",
"row",
",",
"filters",
")",
"data",
".",
"update",
"(",
"filters_builded",
")",
"body",
".",
"append",
"(",
"data",
")",
"return",
"{",
"entity_level",
":",
"body",
"}",
"except",
"KeyError",
"as",
"e",
":",
"print",
"(",
"'Error: No existe el campo \"{}\".'",
".",
"format",
"(",
"e",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"e",
")",
"return",
"False"
] | [
874,
4
] | [
906,
20
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_instrucciones_prima | (t) | instrucciones_prima : P_COMA instrucciones_prima2
| | instrucciones_prima : P_COMA instrucciones_prima2
| | def p_instrucciones_prima(t):
'''instrucciones_prima : P_COMA instrucciones_prima2
| ''' | [
"def",
"p_instrucciones_prima",
"(",
"t",
")",
":"
] | [
241,
0
] | [
243,
33
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
TrackedObject.find_closest_detection_to_line | (self,
line: Tuple[Point2D, Point2D]) | return TrackedObjectDetection(self.id, self.frames[index], self.detections[index]) | Busca la detección más cercana a una línea dada.
Para ello utiliza el centro como punto del vehículo.
:param line: línea.
:return: detección del objeto seguido.
| Busca la detección más cercana a una línea dada. | def find_closest_detection_to_line(self,
line: Tuple[Point2D, Point2D]) -> TrackedObjectDetection:
"""Busca la detección más cercana a una línea dada.
Para ello utiliza el centro como punto del vehículo.
:param line: línea.
:return: detección del objeto seguido.
"""
positions = [object_.center for object_ in self.detections]
index = find_closest_position_to_line(positions, line)
return TrackedObjectDetection(self.id, self.frames[index], self.detections[index]) | [
"def",
"find_closest_detection_to_line",
"(",
"self",
",",
"line",
":",
"Tuple",
"[",
"Point2D",
",",
"Point2D",
"]",
")",
"->",
"TrackedObjectDetection",
":",
"positions",
"=",
"[",
"object_",
".",
"center",
"for",
"object_",
"in",
"self",
".",
"detections",
"]",
"index",
"=",
"find_closest_position_to_line",
"(",
"positions",
",",
"line",
")",
"return",
"TrackedObjectDetection",
"(",
"self",
".",
"id",
",",
"self",
".",
"frames",
"[",
"index",
"]",
",",
"self",
".",
"detections",
"[",
"index",
"]",
")"
] | [
85,
4
] | [
96,
90
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_funciones_string2 | (t) | funciones_string2 : length
| sha256 | funciones_string2 : length
| sha256 | def p_funciones_string2(t):
'''funciones_string2 : length
| sha256'''
t[0]= t[1] | [
"def",
"p_funciones_string2",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] | [
2098,
0
] | [
2101,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones_tri | (t) | funciones_tri : acos
| acosd
| asin
| asind
| atan
| atand
| atan2
| cos
| cosd
| cot
| cotd
| sin
| sind
| tan
| tand
| sinh
| cosh
| tanh
| asinh
| acosh
| atanh | funciones_tri : acos
| acosd
| asin
| asind
| atan
| atand
| atan2
| cos
| cosd
| cot
| cotd
| sin
| sind
| tan
| tand
| sinh
| cosh
| tanh
| asinh
| acosh
| atanh | def p_funciones_tri(t):
'''funciones_tri : acos
| acosd
| asin
| asind
| atan
| atand
| atan2
| cos
| cosd
| cot
| cotd
| sin
| sind
| tan
| tand
| sinh
| cosh
| tanh
| asinh
| acosh
| atanh''' | [
"def",
"p_funciones_tri",
"(",
"t",
")",
":"
] | [
440,
0
] | [
461,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
RoomSerializer.create | (self, validated_data) | return room | Crea la sala y el banquero de la sala | Crea la sala y el banquero de la sala | def create(self, validated_data):
"""Crea la sala y el banquero de la sala"""
users_data = validated_data.pop('userBanker')
su = shortuuid.ShortUUID().random(length=6) #cambiar a 6
ut = UserType.objects.get(idUserType="1")
user = User.objects.create(userType = ut,
amount=500000,
is_staff=True,
**users_data)
room = Room.objects.create(idRoom=su,
userBanker = user,
**validated_data)
room.limit = 1
user.room=room
user.save()
room.save()
return room | [
"def",
"create",
"(",
"self",
",",
"validated_data",
")",
":",
"users_data",
"=",
"validated_data",
".",
"pop",
"(",
"'userBanker'",
")",
"su",
"=",
"shortuuid",
".",
"ShortUUID",
"(",
")",
".",
"random",
"(",
"length",
"=",
"6",
")",
"#cambiar a 6",
"ut",
"=",
"UserType",
".",
"objects",
".",
"get",
"(",
"idUserType",
"=",
"\"1\"",
")",
"user",
"=",
"User",
".",
"objects",
".",
"create",
"(",
"userType",
"=",
"ut",
",",
"amount",
"=",
"500000",
",",
"is_staff",
"=",
"True",
",",
"*",
"*",
"users_data",
")",
"room",
"=",
"Room",
".",
"objects",
".",
"create",
"(",
"idRoom",
"=",
"su",
",",
"userBanker",
"=",
"user",
",",
"*",
"*",
"validated_data",
")",
"room",
".",
"limit",
"=",
"1",
"user",
".",
"room",
"=",
"room",
"user",
".",
"save",
"(",
")",
"room",
".",
"save",
"(",
")",
"return",
"room"
] | [
17,
4
] | [
33,
19
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
sort_por_clase | () | return sorted(champions_in_csv(), reverse=False, key=lambda x: x[2]) | Campeones por clase | Campeones por clase | def sort_por_clase():
"""Campeones por clase"""
return sorted(champions_in_csv(), reverse=False, key=lambda x: x[2]) | [
"def",
"sort_por_clase",
"(",
")",
":",
"return",
"sorted",
"(",
"champions_in_csv",
"(",
")",
",",
"reverse",
"=",
"False",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"2",
"]",
")"
] | [
35,
0
] | [
37,
72
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
pdf_uploader | (file, name) | return True | **Función encargada de cargar y guardar el archivo pdf de un nuevo
documento**
:param file: ``pdf`` enviado por medio del objeto ``request``
:type: ``FileField``
:param name: Nombre del archivo PDF
:type: str
:return: Verdadero si se pudo cargar el archivo, falso en caso
contrario
:rtype: bool
| **Función encargada de cargar y guardar el archivo pdf de un nuevo
documento** | def pdf_uploader(file, name):
"""**Función encargada de cargar y guardar el archivo pdf de un nuevo
documento**
:param file: ``pdf`` enviado por medio del objeto ``request``
:type: ``FileField``
:param name: Nombre del archivo PDF
:type: str
:return: Verdadero si se pudo cargar el archivo, falso en caso
contrario
:rtype: bool
"""
LOGGER.info("Subiendo archivo PDF::{}".format(name))
path_to_save = settings.BASE_DIR + settings.MEDIA_ROOT + name
LOGGER.debug("Path de PDF::{}".format(path_to_save))
with open(path_to_save, 'wb+') as destination:
for i, chunk in enumerate(file.chunks()):
destination.write(chunk)
return True | [
"def",
"pdf_uploader",
"(",
"file",
",",
"name",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Subiendo archivo PDF::{}\"",
".",
"format",
"(",
"name",
")",
")",
"path_to_save",
"=",
"settings",
".",
"BASE_DIR",
"+",
"settings",
".",
"MEDIA_ROOT",
"+",
"name",
"LOGGER",
".",
"debug",
"(",
"\"Path de PDF::{}\"",
".",
"format",
"(",
"path_to_save",
")",
")",
"with",
"open",
"(",
"path_to_save",
",",
"'wb+'",
")",
"as",
"destination",
":",
"for",
"i",
",",
"chunk",
"in",
"enumerate",
"(",
"file",
".",
"chunks",
"(",
")",
")",
":",
"destination",
".",
"write",
"(",
"chunk",
")",
"return",
"True"
] | [
68,
0
] | [
86,
15
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
ComputeLabelY | (Array) | return Y | Compute label y coordinate | Compute label y coordinate | def ComputeLabelY(Array):
"""Compute label y coordinate"""
Y = min(Array)+ (max(Array)-min(Array))/2
return Y | [
"def",
"ComputeLabelY",
"(",
"Array",
")",
":",
"Y",
"=",
"min",
"(",
"Array",
")",
"+",
"(",
"max",
"(",
"Array",
")",
"-",
"min",
"(",
"Array",
")",
")",
"/",
"2",
"return",
"Y"
] | [
190,
0
] | [
193,
12
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
media_varianza_desviacion | (numeros: List[float]) | return {"media": media, "varianza": varianza, "desviacion": desviacion} | Calcula la media, varianza y desviación estándar de una muestra
de números.
:param numeros: Lista de números.
:numeros type: List[float]
:return: Tupla con la media, varianza y desviación estándar.
:rtype: Dict[str, float]
| Calcula la media, varianza y desviación estándar de una muestra
de números. | def media_varianza_desviacion(numeros: List[float]) -> Dict[str, float]:
"""Calcula la media, varianza y desviación estándar de una muestra
de números.
:param numeros: Lista de números.
:numeros type: List[float]
:return: Tupla con la media, varianza y desviación estándar.
:rtype: Dict[str, float]
"""
media = sum(numeros) / len(numeros)
varianza = sum((x - media) ** 2 for x in numeros) / len(numeros)
desviacion = varianza ** 0.5
return {"media": media, "varianza": varianza, "desviacion": desviacion} | [
"def",
"media_varianza_desviacion",
"(",
"numeros",
":",
"List",
"[",
"float",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"float",
"]",
":",
"media",
"=",
"sum",
"(",
"numeros",
")",
"/",
"len",
"(",
"numeros",
")",
"varianza",
"=",
"sum",
"(",
"(",
"x",
"-",
"media",
")",
"**",
"2",
"for",
"x",
"in",
"numeros",
")",
"/",
"len",
"(",
"numeros",
")",
"desviacion",
"=",
"varianza",
"**",
"0.5",
"return",
"{",
"\"media\"",
":",
"media",
",",
"\"varianza\"",
":",
"varianza",
",",
"\"desviacion\"",
":",
"desviacion",
"}"
] | [
10,
0
] | [
22,
75
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_llamasProcedimientos | (t) | llamadaprocedimiento : EXECUTE ID PARIZQ PARDER PTCOMA | llamadaprocedimiento : EXECUTE ID PARIZQ PARDER PTCOMA | def p_llamasProcedimientos(t):
'llamadaprocedimiento : EXECUTE ID PARIZQ PARDER PTCOMA'
g = '<llamadaprocedimiento> : EXECUTE ID PARIZQ PARDER PTCOMA'
t[0] = Nodo('EXECUTE', t[2], [], t.lexer.lineno, 0, g) | [
"def",
"p_llamasProcedimientos",
"(",
"t",
")",
":",
"g",
"=",
"'<llamadaprocedimiento> : EXECUTE ID PARIZQ PARDER PTCOMA'",
"t",
"[",
"0",
"]",
"=",
"Nodo",
"(",
"'EXECUTE'",
",",
"t",
"[",
"2",
"]",
",",
"[",
"]",
",",
"t",
".",
"lexer",
".",
"lineno",
",",
"0",
",",
"g",
")"
] | [
519,
0
] | [
522,
58
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
get_variants | () | return variants | **Obtiene las variantes actuales de elasticsearch**
Función encargada de obtener las variantes existentes en el índice
de ``elasticsearch`` a través del API aggregations. Se obtienen en un
diccionario con el ISO de la variante como llave y el nombre de
la variante como valor. Se agrega al diccionario de variantes el
estatus de la consulta (success o error).
:return: variantes
:rtype: dict
| **Obtiene las variantes actuales de elasticsearch** | def get_variants():
"""**Obtiene las variantes actuales de elasticsearch**
Función encargada de obtener las variantes existentes en el índice
de ``elasticsearch`` a través del API aggregations. Se obtienen en un
diccionario con el ISO de la variante como llave y el nombre de
la variante como valor. Se agrega al diccionario de variantes el
estatus de la consulta (success o error).
:return: variantes
:rtype: dict
"""
variants = {}
variant_filters = {
"size": 0,
"aggs": {
"variants": {
"terms": {
# TODO: depende del header del CSV
"field": "variant",
"size": 100 # TODO: Cambiar dinamicamente
}
}
}
}
try:
response = es.search(index=settings.INDEX, body=variant_filters)
results = response['aggregations']['variants']['buckets']
for data in results:
# Si la variante no es cadena vacía
if data['key']:
variant = data['key']
# TODO: Manejar caso donde no haya ISO
iso = variant[variant.find('(')+1:variant.find(')')]
variants[iso] = variant
variants['status'] = 'success'
except es_exceptions.ConnectionError as e:
LOGGER.error("No hay conexión a Elasticsearch::{}".format(e.info))
LOGGER.error("No se pudo conectar al indice::" + settings.INDEX)
LOGGER.error("URL::" + settings.ELASTIC_URL)
# Diccionario porque se utilizara el metodo items() en forms
variants = {'status': 'error'}
except es_exceptions.NotFoundError as e:
LOGGER.error("No se encontró el indice::" + settings.INDEX)
LOGGER.error("URL::" + settings.ELASTIC_URL)
variants = {'status': 'error'}
return variants | [
"def",
"get_variants",
"(",
")",
":",
"variants",
"=",
"{",
"}",
"variant_filters",
"=",
"{",
"\"size\"",
":",
"0",
",",
"\"aggs\"",
":",
"{",
"\"variants\"",
":",
"{",
"\"terms\"",
":",
"{",
"# TODO: depende del header del CSV",
"\"field\"",
":",
"\"variant\"",
",",
"\"size\"",
":",
"100",
"# TODO: Cambiar dinamicamente",
"}",
"}",
"}",
"}",
"try",
":",
"response",
"=",
"es",
".",
"search",
"(",
"index",
"=",
"settings",
".",
"INDEX",
",",
"body",
"=",
"variant_filters",
")",
"results",
"=",
"response",
"[",
"'aggregations'",
"]",
"[",
"'variants'",
"]",
"[",
"'buckets'",
"]",
"for",
"data",
"in",
"results",
":",
"# Si la variante no es cadena vacía",
"if",
"data",
"[",
"'key'",
"]",
":",
"variant",
"=",
"data",
"[",
"'key'",
"]",
"# TODO: Manejar caso donde no haya ISO",
"iso",
"=",
"variant",
"[",
"variant",
".",
"find",
"(",
"'('",
")",
"+",
"1",
":",
"variant",
".",
"find",
"(",
"')'",
")",
"]",
"variants",
"[",
"iso",
"]",
"=",
"variant",
"variants",
"[",
"'status'",
"]",
"=",
"'success'",
"except",
"es_exceptions",
".",
"ConnectionError",
"as",
"e",
":",
"LOGGER",
".",
"error",
"(",
"\"No hay conexión a Elasticsearch::{}\".",
"f",
"ormat(",
"e",
".",
"i",
"nfo)",
")",
"",
"LOGGER",
".",
"error",
"(",
"\"No se pudo conectar al indice::\"",
"+",
"settings",
".",
"INDEX",
")",
"LOGGER",
".",
"error",
"(",
"\"URL::\"",
"+",
"settings",
".",
"ELASTIC_URL",
")",
"# Diccionario porque se utilizara el metodo items() en forms",
"variants",
"=",
"{",
"'status'",
":",
"'error'",
"}",
"except",
"es_exceptions",
".",
"NotFoundError",
"as",
"e",
":",
"LOGGER",
".",
"error",
"(",
"\"No se encontró el indice::\" ",
" ",
"ettings.",
"I",
"NDEX)",
"",
"LOGGER",
".",
"error",
"(",
"\"URL::\"",
"+",
"settings",
".",
"ELASTIC_URL",
")",
"variants",
"=",
"{",
"'status'",
":",
"'error'",
"}",
"return",
"variants"
] | [
305,
0
] | [
351,
19
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_cadena | (t) | cadena : cualquiercadena
| cualquieridentificador | cadena : cualquiercadena
| cualquieridentificador | def p_cadena(t):
'''cadena : cualquiercadena
| cualquieridentificador'''
t[0] = t[1] | [
"def",
"p_cadena",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] | [
1364,
0
] | [
1367,
15
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
HolaViewSet.create | (self, request) | Crea un nuevo mensaje con el name que venga del front | Crea un nuevo mensaje con el name que venga del front | def create(self, request):
"""Crea un nuevo mensaje con el name que venga del front"""
serializer = self.serializers_class(data=request.data)
if serializer.is_valid():
name = serializer.validated_data.get('name')
message = f'Hola {name}'
return Response({'message': message})
else:
return Response(
serializer.errors,
status=status.HTTP_400_BAD_REQUEST) | [
"def",
"create",
"(",
"self",
",",
"request",
")",
":",
"serializer",
"=",
"self",
".",
"serializers_class",
"(",
"data",
"=",
"request",
".",
"data",
")",
"if",
"serializer",
".",
"is_valid",
"(",
")",
":",
"name",
"=",
"serializer",
".",
"validated_data",
".",
"get",
"(",
"'name'",
")",
"message",
"=",
"f'Hola {name}'",
"return",
"Response",
"(",
"{",
"'message'",
":",
"message",
"}",
")",
"else",
":",
"return",
"Response",
"(",
"serializer",
".",
"errors",
",",
"status",
"=",
"status",
".",
"HTTP_400_BAD_REQUEST",
")"
] | [
69,
4
] | [
80,
51
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_getstatus | (t) | contenidobegin : GET DIAGNOSTICS IDENTIFICADOR IGUAL ROW_COUNT PYC | contenidobegin : GET DIAGNOSTICS IDENTIFICADOR IGUAL ROW_COUNT PYC | def p_getstatus(t):
'''contenidobegin : GET DIAGNOSTICS IDENTIFICADOR IGUAL ROW_COUNT PYC'''
strGram = "<instruccion> ::= GET DIAGNOSTICS IDENTIFICADOR IGUAL ROW_COUNT PYC"
t[0] = Gets.Gets(t[3], t[5], '', t.lexer.lineno, t.lexer.lexpos, strGram) | [
"def",
"p_getstatus",
"(",
"t",
")",
":",
"strGram",
"=",
"\"<instruccion> ::= GET DIAGNOSTICS IDENTIFICADOR IGUAL ROW_COUNT PYC\"",
"t",
"[",
"0",
"]",
"=",
"Gets",
".",
"Gets",
"(",
"t",
"[",
"3",
"]",
",",
"t",
"[",
"5",
"]",
",",
"''",
",",
"t",
".",
"lexer",
".",
"lineno",
",",
"t",
".",
"lexer",
".",
"lexpos",
",",
"strGram",
")"
] | [
541,
0
] | [
544,
78
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
set_colors | (config) | return config | Escribe los colores del proyecto
Escribe en el diccionario de configuraciones el color primario,
secundario, color de los textos y color de contraste de los textos
:param config: Diccionario con la configuración
:type: dict
:return: Diccionario de configuraciones con los colores del
proyecto
:rtype: dict
| Escribe los colores del proyecto | def set_colors(config):
"""Escribe los colores del proyecto
Escribe en el diccionario de configuraciones el color primario,
secundario, color de los textos y color de contraste de los textos
:param config: Diccionario con la configuración
:type: dict
:return: Diccionario de configuraciones con los colores del
proyecto
:rtype: dict
"""
primary = '#fbda65'
primary_hover = '#fdecb2'
secondary = '#06a594'
secondary_hover = '#69c9be'
secondary_active = '#048476'
text_color = '#000000'
text_color_alt = '#ffffff'
text_fields = {
"button": text_color_alt,
"btnhover": primary,
"form": text_color,
"bold": secondary,
"highlight": secondary_active,
"nav": secondary,
"navhover": secondary_hover,
"navactive": secondary_active,
"result": text_color,
"footer": text_color,
"links": secondary,
"hoverlinks": secondary_hover
}
background_fields = {
"form": primary_hover,
"button": secondary,
"btnhover": secondary_hover,
"nav": primary,
"footer": text_color_alt,
"highlight": primary_hover
}
border_fields = {
"button": secondary,
"input": secondary
}
config['COLORS'] = {"text": text_fields, "background": background_fields,
"border": border_fields}
return config | [
"def",
"set_colors",
"(",
"config",
")",
":",
"primary",
"=",
"'#fbda65'",
"primary_hover",
"=",
"'#fdecb2'",
"secondary",
"=",
"'#06a594'",
"secondary_hover",
"=",
"'#69c9be'",
"secondary_active",
"=",
"'#048476'",
"text_color",
"=",
"'#000000'",
"text_color_alt",
"=",
"'#ffffff'",
"text_fields",
"=",
"{",
"\"button\"",
":",
"text_color_alt",
",",
"\"btnhover\"",
":",
"primary",
",",
"\"form\"",
":",
"text_color",
",",
"\"bold\"",
":",
"secondary",
",",
"\"highlight\"",
":",
"secondary_active",
",",
"\"nav\"",
":",
"secondary",
",",
"\"navhover\"",
":",
"secondary_hover",
",",
"\"navactive\"",
":",
"secondary_active",
",",
"\"result\"",
":",
"text_color",
",",
"\"footer\"",
":",
"text_color",
",",
"\"links\"",
":",
"secondary",
",",
"\"hoverlinks\"",
":",
"secondary_hover",
"}",
"background_fields",
"=",
"{",
"\"form\"",
":",
"primary_hover",
",",
"\"button\"",
":",
"secondary",
",",
"\"btnhover\"",
":",
"secondary_hover",
",",
"\"nav\"",
":",
"primary",
",",
"\"footer\"",
":",
"text_color_alt",
",",
"\"highlight\"",
":",
"primary_hover",
"}",
"border_fields",
"=",
"{",
"\"button\"",
":",
"secondary",
",",
"\"input\"",
":",
"secondary",
"}",
"config",
"[",
"'COLORS'",
"]",
"=",
"{",
"\"text\"",
":",
"text_fields",
",",
"\"background\"",
":",
"background_fields",
",",
"\"border\"",
":",
"border_fields",
"}",
"return",
"config"
] | [
119,
0
] | [
166,
17
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_l_sentencias2 | (t) | l_sentencias : sentencias | l_sentencias : sentencias | def p_l_sentencias2(t):
'l_sentencias : sentencias'
t[0] = [t[1]] | [
"def",
"p_l_sentencias2",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"[",
"t",
"[",
"1",
"]",
"]"
] | [
162,
0
] | [
164,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
IceCreamStand.show_flavors | (self) | Mostrar los sabores disponibles. | Mostrar los sabores disponibles. | def show_flavors(self):
"""Mostrar los sabores disponibles."""
print("\nTenemos disponibles los siguientes sabores:")
for flavor in self.flavors:
print("- " + flavor.title()) | [
"def",
"show_flavors",
"(",
"self",
")",
":",
"print",
"(",
"\"\\nTenemos disponibles los siguientes sabores:\"",
")",
"for",
"flavor",
"in",
"self",
".",
"flavors",
":",
"print",
"(",
"\"- \"",
"+",
"flavor",
".",
"title",
"(",
")",
")"
] | [
36,
4
] | [
40,
40
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones2 | (p) | funciones : SUBSTRING PABRE ID COMA NUMERO COMA NUMERO PCIERRA | funciones : SUBSTRING PABRE ID COMA NUMERO COMA NUMERO PCIERRA | def p_funciones2(p):
'funciones : SUBSTRING PABRE ID COMA NUMERO COMA NUMERO PCIERRA' | [
"def",
"p_funciones2",
"(",
"p",
")",
":"
] | [
304,
0
] | [
305,
68
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
contar_valles | (lista) | return conteo | Contar el número de valles
Esta función debe recibir como argumento una lista de -1's, 0's y 1's, y lo
que representan son las subidas y las bajadas en una ruta de caminata. -1
representa un paso hacia abajo, el 0 representa un paso hacia adelante y el
1 representa un paso hacia arriba, entonces por ejemplo, para la lista
[-1,1,0,1,1,-1,0,0,1,-1,1,1,-1,-1] representa la siguiente ruta:
/\
/\__/\/ \
_/
\/
El objetivo de esta función es devolver el número de valles que estén
representados en la lista, que para el ejemplo que se acaba de mostrar es
de 3 valles.
| Contar el número de valles | def contar_valles(lista):
'''Contar el número de valles
Esta función debe recibir como argumento una lista de -1's, 0's y 1's, y lo
que representan son las subidas y las bajadas en una ruta de caminata. -1
representa un paso hacia abajo, el 0 representa un paso hacia adelante y el
1 representa un paso hacia arriba, entonces por ejemplo, para la lista
[-1,1,0,1,1,-1,0,0,1,-1,1,1,-1,-1] representa la siguiente ruta:
/\
/\__/\/ \
_/
\/
El objetivo de esta función es devolver el número de valles que estén
representados en la lista, que para el ejemplo que se acaba de mostrar es
de 3 valles.
'''
conteo = 0
for i in lista:
if (i == -1):
conteo += 1
#print(conteo)
i += 1
#print(lista[i])
#print(lista)
#print(conteo)
return conteo | [
"def",
"contar_valles",
"(",
"lista",
")",
":",
"conteo",
"=",
"0",
"for",
"i",
"in",
"lista",
":",
"if",
"(",
"i",
"==",
"-",
"1",
")",
":",
"conteo",
"+=",
"1",
"#print(conteo)",
"i",
"+=",
"1",
"#print(lista[i])",
"#print(lista)",
"#print(conteo)",
"return",
"conteo"
] | [
37,
0
] | [
66,
17
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
AccountCheck.post_payment_check | (self, payment) | No usamos post() porque no puede obtener secuencia, hacemos
parecido a los statements donde odoo ya lo genera posteado
| No usamos post() porque no puede obtener secuencia, hacemos
parecido a los statements donde odoo ya lo genera posteado
| def post_payment_check(self, payment):
""" No usamos post() porque no puede obtener secuencia, hacemos
parecido a los statements donde odoo ya lo genera posteado
"""
# payment.post()
move = self.env['account.move'].with_context(
default_type='entry').create(payment._prepare_payment_moves())
move.post()
payment.write({'state': 'posted', 'move_name': move.name}) | [
"def",
"post_payment_check",
"(",
"self",
",",
"payment",
")",
":",
"# payment.post()",
"move",
"=",
"self",
".",
"env",
"[",
"'account.move'",
"]",
".",
"with_context",
"(",
"default_type",
"=",
"'entry'",
")",
".",
"create",
"(",
"payment",
".",
"_prepare_payment_moves",
"(",
")",
")",
"move",
".",
"post",
"(",
")",
"payment",
".",
"write",
"(",
"{",
"'state'",
":",
"'posted'",
",",
"'move_name'",
":",
"move",
".",
"name",
"}",
")"
] | [
474,
4
] | [
482,
66
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ArregloDinamico._incrementar | (self) | Incrementa la capacidad del arreglo | Incrementa la capacidad del arreglo | def _incrementar(self) -> None:
"""Incrementa la capacidad del arreglo"""
self._redimensionar(self._capacidad * self._factor) | [
"def",
"_incrementar",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_redimensionar",
"(",
"self",
".",
"_capacidad",
"*",
"self",
".",
"_factor",
")"
] | [
132,
4
] | [
134,
59
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones26 | (p) | funciones : SIN PABRE expresion PCIERRA | funciones : SIN PABRE expresion PCIERRA | def p_funciones26(p):
'funciones : SIN PABRE expresion PCIERRA' | [
"def",
"p_funciones26",
"(",
"p",
")",
":"
] | [
376,
0
] | [
377,
45
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ObjectTracker._algorithm | (self) | Método a implementar que realiza el algoritmo del modelo de seguimiento.
Este método es llamado por run(). No se espera que devuelva nada.
| Método a implementar que realiza el algoritmo del modelo de seguimiento. | def _algorithm(self) -> None:
"""Método a implementar que realiza el algoritmo del modelo de seguimiento.
Este método es llamado por run(). No se espera que devuelva nada.
""" | [
"def",
"_algorithm",
"(",
"self",
")",
"->",
"None",
":"
] | [
66,
4
] | [
70,
11
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones31 | (p) | funciones : SINH PABRE expresion PCIERRA | funciones : SINH PABRE expresion PCIERRA | def p_funciones31(p):
'funciones : SINH PABRE expresion PCIERRA' | [
"def",
"p_funciones31",
"(",
"p",
")",
":"
] | [
391,
0
] | [
392,
46
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_getstatus3 | (t) | contenidobegin : GET DIAGNOSTICS IDENTIFICADOR IGUAL PG_CONTEXT PYC | contenidobegin : GET DIAGNOSTICS IDENTIFICADOR IGUAL PG_CONTEXT PYC | def p_getstatus3(t):
'''contenidobegin : GET DIAGNOSTICS IDENTIFICADOR IGUAL PG_CONTEXT PYC'''
strGram = "<instruccion> ::= GET DIAGNOSTICS IDENTIFICADOR IGUAL PG_CONTEXT PYC"
t[0] = Gets.Gets(t[3], t[5], '', t.lexer.lineno, t.lexer.lexpos, strGram) | [
"def",
"p_getstatus3",
"(",
"t",
")",
":",
"strGram",
"=",
"\"<instruccion> ::= GET DIAGNOSTICS IDENTIFICADOR IGUAL PG_CONTEXT PYC\"",
"t",
"[",
"0",
"]",
"=",
"Gets",
".",
"Gets",
"(",
"t",
"[",
"3",
"]",
",",
"t",
"[",
"5",
"]",
",",
"''",
",",
"t",
".",
"lexer",
".",
"lineno",
",",
"t",
".",
"lexer",
".",
"lexpos",
",",
"strGram",
")"
] | [
550,
0
] | [
553,
78
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Main.__init__ | (self) | Constructor: Inicializa propiedades de instancia y ciclo REPL. | Constructor: Inicializa propiedades de instancia y ciclo REPL. | def __init__(self):
"""Constructor: Inicializa propiedades de instancia y ciclo REPL."""
self.comandos = {
"agregar": self.agregar,
"borrar": self.borrar,
"mostrar": self.mostrar,
"listar": self.listar,
"buscar": self.buscar,
"ayuda": self.ayuda,
"salir": self.salir
}
archivo = "agenda.db"
introduccion = strip(__doc__)
self.agenda = Estante(archivo)
if not self.agenda.esarchivo():
introduccion += '\nError: No se pudo abrir "{}"'.format(archivo)
REPL(self.comandos, introduccion).ciclo() | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"comandos",
"=",
"{",
"\"agregar\"",
":",
"self",
".",
"agregar",
",",
"\"borrar\"",
":",
"self",
".",
"borrar",
",",
"\"mostrar\"",
":",
"self",
".",
"mostrar",
",",
"\"listar\"",
":",
"self",
".",
"listar",
",",
"\"buscar\"",
":",
"self",
".",
"buscar",
",",
"\"ayuda\"",
":",
"self",
".",
"ayuda",
",",
"\"salir\"",
":",
"self",
".",
"salir",
"}",
"archivo",
"=",
"\"agenda.db\"",
"introduccion",
"=",
"strip",
"(",
"__doc__",
")",
"self",
".",
"agenda",
"=",
"Estante",
"(",
"archivo",
")",
"if",
"not",
"self",
".",
"agenda",
".",
"esarchivo",
"(",
")",
":",
"introduccion",
"+=",
"'\\nError: No se pudo abrir \"{}\"'",
".",
"format",
"(",
"archivo",
")",
"REPL",
"(",
"self",
".",
"comandos",
",",
"introduccion",
")",
".",
"ciclo",
"(",
")"
] | [
19,
4
] | [
35,
49
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
contar_digitos_pares | (n: int) | Cuenta los dígitos pares de un número entero.
:param n: número entero
:n type: int
:return: cantidad de dígitos pares
:rtype: int
| Cuenta los dígitos pares de un número entero. | def contar_digitos_pares(n: int) -> int:
"""Cuenta los dígitos pares de un número entero.
:param n: número entero
:n type: int
:return: cantidad de dígitos pares
:rtype: int
"""
if n < 10:
return 1 if n % 2 == 0 else 0
if n % 10 % 2 == 0:
return 1 + contar_digitos_pares(n // 10)
else:
return contar_digitos_pares(n // 10) | [
"def",
"contar_digitos_pares",
"(",
"n",
":",
"int",
")",
"->",
"int",
":",
"if",
"n",
"<",
"10",
":",
"return",
"1",
"if",
"n",
"%",
"2",
"==",
"0",
"else",
"0",
"if",
"n",
"%",
"10",
"%",
"2",
"==",
"0",
":",
"return",
"1",
"+",
"contar_digitos_pares",
"(",
"n",
"//",
"10",
")",
"else",
":",
"return",
"contar_digitos_pares",
"(",
"n",
"//",
"10",
")"
] | [
25,
0
] | [
38,
44
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
HolaViewSet.update | (self, request, pk=None) | return Response({'http_method': 'PUT'}) | Maneja la actualizacion completa del objeto por un ID | Maneja la actualizacion completa del objeto por un ID | def update(self, request, pk=None):
"""Maneja la actualizacion completa del objeto por un ID"""
return Response({'http_method': 'PUT'}) | [
"def",
"update",
"(",
"self",
",",
"request",
",",
"pk",
"=",
"None",
")",
":",
"return",
"Response",
"(",
"{",
"'http_method'",
":",
"'PUT'",
"}",
")"
] | [
86,
4
] | [
88,
47
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
_run_gdalinfo | (file, con_stats=True) | return gdalinfo_json | Ejecuta el gdalinfo en disco, con o sin stats. | Ejecuta el gdalinfo en disco, con o sin stats. | def _run_gdalinfo(file, con_stats=True):
"""Ejecuta el gdalinfo en disco, con o sin stats."""
stats_param = '-stats' if con_stats else ''
res = subprocess.check_output('gdalinfo -json {} {}'.format(stats_param, file), shell=True)
# BUG FIX para casos donde gdalinfo devuelve un json invalido con campostipo: "stdDev":inf,
res = res.replace(':inf,', ': "inf",').replace(':-inf,', ': "-inf",').replace(':nan,', ': "nan",')
try:
gdalinfo_json = json.loads(res)
except:
return {}
if con_stats:
# Eliminamos el archivo .aux.xml (PAM, Permanent Auxiliar Metadata) que se crea al aplicar gdalinfo -stats
try:
os.remove('{}.aux.xml'.format(file))
except:
pass
return gdalinfo_json | [
"def",
"_run_gdalinfo",
"(",
"file",
",",
"con_stats",
"=",
"True",
")",
":",
"stats_param",
"=",
"'-stats'",
"if",
"con_stats",
"else",
"''",
"res",
"=",
"subprocess",
".",
"check_output",
"(",
"'gdalinfo -json {} {}'",
".",
"format",
"(",
"stats_param",
",",
"file",
")",
",",
"shell",
"=",
"True",
")",
"# BUG FIX para casos donde gdalinfo devuelve un json invalido con campostipo: \"stdDev\":inf,",
"res",
"=",
"res",
".",
"replace",
"(",
"':inf,'",
",",
"': \"inf\",'",
")",
".",
"replace",
"(",
"':-inf,'",
",",
"': \"-inf\",'",
")",
".",
"replace",
"(",
"':nan,'",
",",
"': \"nan\",'",
")",
"try",
":",
"gdalinfo_json",
"=",
"json",
".",
"loads",
"(",
"res",
")",
"except",
":",
"return",
"{",
"}",
"if",
"con_stats",
":",
"# Eliminamos el archivo .aux.xml (PAM, Permanent Auxiliar Metadata) que se crea al aplicar gdalinfo -stats",
"try",
":",
"os",
".",
"remove",
"(",
"'{}.aux.xml'",
".",
"format",
"(",
"file",
")",
")",
"except",
":",
"pass",
"return",
"gdalinfo_json"
] | [
492,
0
] | [
509,
24
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
set_pdf_for_route | (request, ruta='') | return HttpResponse(list_rutas) | u"(para enviar PDF de la próxima edición)</b>:<br> | u"(para enviar PDF de la próxima edición)</b>:<br> | def set_pdf_for_route(request, ruta=''):
fjson = open(settings.JSON_RUTASPDF_PATH, 'a+')
fjson.seek(0)
items = []
try:
items = json.loads(fjson.read())
except Exception:
fjson.seek(0)
fjson.close()
list_rutas = u"Rutas seteadas actualmente<b> "
u"(para enviar PDF de la próxima edición)</b>:<br>"
for item in items:
list_rutas += unicode(item) + u"<br>"
if not ruta == "listar":
encontrada = (ruta in items)
if not encontrada:
items.append(unicode(str(ruta)))
fjson = open(settings.JSON_RUTASPDF_PATH, 'w')
fjson.write(json.dumps(items))
fjson.close()
list_rutas += str(ruta) + "<br>"
return HttpResponse((
u"<strong><u>EXITO:</u></strong> Se enviará el PDF de la próxima "
u"edición <br>" if not encontrada else
u"<strong><u>ERROR:</u></strong> La ruta ya se encuentra en la "
u"lista <br>") + u"<br>" + list_rutas)
return HttpResponse(list_rutas) | [
"def",
"set_pdf_for_route",
"(",
"request",
",",
"ruta",
"=",
"''",
")",
":",
"fjson",
"=",
"open",
"(",
"settings",
".",
"JSON_RUTASPDF_PATH",
",",
"'a+'",
")",
"fjson",
".",
"seek",
"(",
"0",
")",
"items",
"=",
"[",
"]",
"try",
":",
"items",
"=",
"json",
".",
"loads",
"(",
"fjson",
".",
"read",
"(",
")",
")",
"except",
"Exception",
":",
"fjson",
".",
"seek",
"(",
"0",
")",
"fjson",
".",
"close",
"(",
")",
"list_rutas",
"=",
"u\"Rutas seteadas actualmente<b> \"",
"for",
"item",
"in",
"items",
":",
"list_rutas",
"+=",
"unicode",
"(",
"item",
")",
"+",
"u\"<br>\"",
"if",
"not",
"ruta",
"==",
"\"listar\"",
":",
"encontrada",
"=",
"(",
"ruta",
"in",
"items",
")",
"if",
"not",
"encontrada",
":",
"items",
".",
"append",
"(",
"unicode",
"(",
"str",
"(",
"ruta",
")",
")",
")",
"fjson",
"=",
"open",
"(",
"settings",
".",
"JSON_RUTASPDF_PATH",
",",
"'w'",
")",
"fjson",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"items",
")",
")",
"fjson",
".",
"close",
"(",
")",
"list_rutas",
"+=",
"str",
"(",
"ruta",
")",
"+",
"\"<br>\"",
"return",
"HttpResponse",
"(",
"(",
"u\"<strong><u>EXITO:</u></strong> Se enviará el PDF de la próxima \"",
"u\"edición <br>\" ",
"f ",
"ot ",
"ncontrada ",
"lse",
"u\"<strong><u>ERROR:</u></strong> La ruta ya se encuentra en la \"",
"u\"lista <br>\"",
")",
"+",
"u\"<br>\"",
"+",
"list_rutas",
")",
"return",
"HttpResponse",
"(",
"list_rutas",
")"
] | [
93,
0
] | [
120,
35
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
Textos.__iter__ | (self) | Texto y metadata de cada párrafo. | Texto y metadata de cada párrafo. | def __iter__(self):
"""Texto y metadata de cada párrafo."""
self.n = 0
self.nprg = 0
for archivo in iterar_rutas(
self.absoluto,
aleatorio=self.aleatorio,
recursivo=self.recursivo,
exts=self.exts,
):
texto = leer_texto(archivo)
if texto:
self.n += 1
if self.chars:
texto = filtrar_cortas(texto, chars=self.chars)
comun = {
"id_file": f"{self.n:0>7}",
"archivo": archivo.name,
"fuente": archivo.parent.name,
}
for parag in texto.splitlines():
if parag:
self.nprg += 1
meta = {"id_parag": f"{self.nprg:0>7}", **comun}
if self.nprg % 10000 == 0:
msg = self.__repr__()
logger.info(msg)
yield parag, meta | [
"def",
"__iter__",
"(",
"self",
")",
":",
"self",
".",
"n",
"=",
"0",
"self",
".",
"nprg",
"=",
"0",
"for",
"archivo",
"in",
"iterar_rutas",
"(",
"self",
".",
"absoluto",
",",
"aleatorio",
"=",
"self",
".",
"aleatorio",
",",
"recursivo",
"=",
"self",
".",
"recursivo",
",",
"exts",
"=",
"self",
".",
"exts",
",",
")",
":",
"texto",
"=",
"leer_texto",
"(",
"archivo",
")",
"if",
"texto",
":",
"self",
".",
"n",
"+=",
"1",
"if",
"self",
".",
"chars",
":",
"texto",
"=",
"filtrar_cortas",
"(",
"texto",
",",
"chars",
"=",
"self",
".",
"chars",
")",
"comun",
"=",
"{",
"\"id_file\"",
":",
"f\"{self.n:0>7}\"",
",",
"\"archivo\"",
":",
"archivo",
".",
"name",
",",
"\"fuente\"",
":",
"archivo",
".",
"parent",
".",
"name",
",",
"}",
"for",
"parag",
"in",
"texto",
".",
"splitlines",
"(",
")",
":",
"if",
"parag",
":",
"self",
".",
"nprg",
"+=",
"1",
"meta",
"=",
"{",
"\"id_parag\"",
":",
"f\"{self.nprg:0>7}\"",
",",
"*",
"*",
"comun",
"}",
"if",
"self",
".",
"nprg",
"%",
"10000",
"==",
"0",
":",
"msg",
"=",
"self",
".",
"__repr__",
"(",
")",
"logger",
".",
"info",
"(",
"msg",
")",
"yield",
"parag",
",",
"meta"
] | [
281,
4
] | [
313,
41
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
DataCleaner.fecha_separada | (self, fields, new_field_name, keep_original=True,
inplace=False) | return parsed_series | Regla para fechas completas que están separadas en varios campos.
Args:
field (str): Campo a limpiar.
new_field_name (str): Sufijo para construir nombre del nuevo field.
Returns:
pandas.Series: Serie de strings limpios.
| Regla para fechas completas que están separadas en varios campos. | def fecha_separada(self, fields, new_field_name, keep_original=True,
inplace=False):
"""Regla para fechas completas que están separadas en varios campos.
Args:
field (str): Campo a limpiar.
new_field_name (str): Sufijo para construir nombre del nuevo field.
Returns:
pandas.Series: Serie de strings limpios.
"""
field_names = [self._normalize_field(field[0]) for field in fields]
time_format = " ".join([field[1] for field in fields])
# print(time_format)
# print(self.df[field_names])
concat_series = self.df[field_names].apply(
lambda x: ' '.join(x.map(str)),
axis=1
)
print(concat_series)
parsed_series = concat_series.apply(self._parse_datetime,
args=(time_format,))
print(parsed_series)
if inplace:
self.df["isodatetime_" + new_field_name] = parsed_series
if not keep_original:
for field in field_names:
self.remover_columnas(field)
return parsed_series | [
"def",
"fecha_separada",
"(",
"self",
",",
"fields",
",",
"new_field_name",
",",
"keep_original",
"=",
"True",
",",
"inplace",
"=",
"False",
")",
":",
"field_names",
"=",
"[",
"self",
".",
"_normalize_field",
"(",
"field",
"[",
"0",
"]",
")",
"for",
"field",
"in",
"fields",
"]",
"time_format",
"=",
"\" \"",
".",
"join",
"(",
"[",
"field",
"[",
"1",
"]",
"for",
"field",
"in",
"fields",
"]",
")",
"# print(time_format)",
"# print(self.df[field_names])",
"concat_series",
"=",
"self",
".",
"df",
"[",
"field_names",
"]",
".",
"apply",
"(",
"lambda",
"x",
":",
"' '",
".",
"join",
"(",
"x",
".",
"map",
"(",
"str",
")",
")",
",",
"axis",
"=",
"1",
")",
"print",
"(",
"concat_series",
")",
"parsed_series",
"=",
"concat_series",
".",
"apply",
"(",
"self",
".",
"_parse_datetime",
",",
"args",
"=",
"(",
"time_format",
",",
")",
")",
"print",
"(",
"parsed_series",
")",
"if",
"inplace",
":",
"self",
".",
"df",
"[",
"\"isodatetime_\"",
"+",
"new_field_name",
"]",
"=",
"parsed_series",
"if",
"not",
"keep_original",
":",
"for",
"field",
"in",
"field_names",
":",
"self",
".",
"remover_columnas",
"(",
"field",
")",
"return",
"parsed_series"
] | [
581,
4
] | [
613,
28
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_expreion_funciones | (p) | expresion : funciones | expresion : funciones | def p_expreion_funciones(p):
'expresion : funciones' | [
"def",
"p_expreion_funciones",
"(",
"p",
")",
":"
] | [
1069,
0
] | [
1070,
27
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_sentencia_function_definicion_function_2 | (t) | definicion_function : declaraciones_procedure BEGIN bloque END | definicion_function : declaraciones_procedure BEGIN bloque END | def p_sentencia_function_definicion_function_2(t):
'definicion_function : declaraciones_procedure BEGIN bloque END'
t[0] = Start('CUERPO_FUNCTION')
t[0].hijos.append(t[1])
t[0].hijos.append(t[3]) | [
"def",
"p_sentencia_function_definicion_function_2",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"Start",
"(",
"'CUERPO_FUNCTION'",
")",
"t",
"[",
"0",
"]",
".",
"hijos",
".",
"append",
"(",
"t",
"[",
"1",
"]",
")",
"t",
"[",
"0",
"]",
".",
"hijos",
".",
"append",
"(",
"t",
"[",
"3",
"]",
")"
] | [
1730,
0
] | [
1734,
27
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
TrackingVideo._draw_objects | (self, fid: int, frame: Image) | return frame | Realiza el dibujado en los objetos que aparecen en el frame actual.
:param fid: número del frame.
:param frame: frame.
:return: frame con los objetos dibujados.
| Realiza el dibujado en los objetos que aparecen en el frame actual. | def _draw_objects(self, fid: int, frame: Image) -> Image:
"""Realiza el dibujado en los objetos que aparecen en el frame actual.
:param fid: número del frame.
:param frame: frame.
:return: frame con los objetos dibujados.
"""
# Objetos detectados en el frame fid.
tracked_objects_in_frame = self.tracked_objects.frame_objects(fid)
# Dibujar la información de los objetos si aparecen en el frame actual.
for tracked_object_detection in tracked_objects_in_frame:
frame = self._draw_object(fid, frame, self.tracked_objects[tracked_object_detection.id],
tracked_object_detection)
return frame | [
"def",
"_draw_objects",
"(",
"self",
",",
"fid",
":",
"int",
",",
"frame",
":",
"Image",
")",
"->",
"Image",
":",
"# Objetos detectados en el frame fid.",
"tracked_objects_in_frame",
"=",
"self",
".",
"tracked_objects",
".",
"frame_objects",
"(",
"fid",
")",
"# Dibujar la información de los objetos si aparecen en el frame actual.",
"for",
"tracked_object_detection",
"in",
"tracked_objects_in_frame",
":",
"frame",
"=",
"self",
".",
"_draw_object",
"(",
"fid",
",",
"frame",
",",
"self",
".",
"tracked_objects",
"[",
"tracked_object_detection",
".",
"id",
"]",
",",
"tracked_object_detection",
")",
"return",
"frame"
] | [
106,
4
] | [
119,
20
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
ApiRequest._validsec | (self) | funcion que define si es necesario añadir un token de seguridad a las peticiones request en base a la confgiuracion de la clase
| funcion que define si es necesario añadir un token de seguridad a las peticiones request en base a la confgiuracion de la clase
| def _validsec(self):
""" funcion que define si es necesario añadir un token de seguridad a las peticiones request en base a la confgiuracion de la clase
"""
if self.sectoken:
if not self.token:
if not self.Auth():
raise ImposibleAuth
self.authheader={self.tokenrequest : self.token} | [
"def",
"_validsec",
"(",
"self",
")",
":",
"if",
"self",
".",
"sectoken",
":",
"if",
"not",
"self",
".",
"token",
":",
"if",
"not",
"self",
".",
"Auth",
"(",
")",
":",
"raise",
"ImposibleAuth",
"self",
".",
"authheader",
"=",
"{",
"self",
".",
"tokenrequest",
":",
"self",
".",
"token",
"}"
] | [
184,
4
] | [
191,
60
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Counter.calc_weeks | (self) | return int(self.calc_seconds() // WEEK) | Calcula los meses transcurridos | Calcula los meses transcurridos | def calc_weeks(self):
"""Calcula los meses transcurridos"""
return int(self.calc_seconds() // WEEK) | [
"def",
"calc_weeks",
"(",
"self",
")",
":",
"return",
"int",
"(",
"self",
".",
"calc_seconds",
"(",
")",
"//",
"WEEK",
")"
] | [
44,
4
] | [
47,
47
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
ethno_table_maker | (soup) | return table | **Crea la tabla html con información de ethnologue**
Con base en la variante en turno se crea, dinamicamente, una
cadena que contiene una tabla html que será rendereada por un
modal en la vista de busqueda.
:param soup: Objeto con la página ``html`` de ethnologue
:type: ``BeautifulSoup Object``
:return: Tabla en formato ``html``
:rtype: str
| **Crea la tabla html con información de ethnologue** | def ethno_table_maker(soup):
"""**Crea la tabla html con información de ethnologue**
Con base en la variante en turno se crea, dinamicamente, una
cadena que contiene una tabla html que será rendereada por un
modal en la vista de busqueda.
:param soup: Objeto con la página ``html`` de ethnologue
:type: ``BeautifulSoup Object``
:return: Tabla en formato ``html``
:rtype: str
"""
table = '<table class="table table-striped">'
base = soup.find('div', class_='title-wrapper')
title = soup.find('h1', id='page-title').text
fields = base.find_all_next('div', class_='views-field')
for i, field in enumerate(fields):
if i == 0:
table += f'''
<thead>
<tr class="table-info">
<th colspan="2"><h3>{title}</h3></th>
</tr>
<tr>
<th colspan="2">{field.text.strip()}</th>
</tr>
</thead>
<tbody>
'''
continue
content = field.find(class_='field-content').text
content = content if content else '<i class="fa fa-lock">'
table += f'''
<tr>
<th scope="row">
{field.find(class_='views-label').text}
</th>
<td>
{content}
</td>
</tr>
'''
table += "</tbody></table>"
return table | [
"def",
"ethno_table_maker",
"(",
"soup",
")",
":",
"table",
"=",
"'<table class=\"table table-striped\">'",
"base",
"=",
"soup",
".",
"find",
"(",
"'div'",
",",
"class_",
"=",
"'title-wrapper'",
")",
"title",
"=",
"soup",
".",
"find",
"(",
"'h1'",
",",
"id",
"=",
"'page-title'",
")",
".",
"text",
"fields",
"=",
"base",
".",
"find_all_next",
"(",
"'div'",
",",
"class_",
"=",
"'views-field'",
")",
"for",
"i",
",",
"field",
"in",
"enumerate",
"(",
"fields",
")",
":",
"if",
"i",
"==",
"0",
":",
"table",
"+=",
"f'''\n <thead>\n <tr class=\"table-info\">\n <th colspan=\"2\"><h3>{title}</h3></th>\n </tr>\n <tr>\n <th colspan=\"2\">{field.text.strip()}</th>\n </tr>\n </thead>\n <tbody>\n '''",
"continue",
"content",
"=",
"field",
".",
"find",
"(",
"class_",
"=",
"'field-content'",
")",
".",
"text",
"content",
"=",
"content",
"if",
"content",
"else",
"'<i class=\"fa fa-lock\">'",
"table",
"+=",
"f'''\n <tr>\n <th scope=\"row\">\n {field.find(class_='views-label').text}\n </th>\n <td>\n {content}\n </td>\n </tr>\n '''",
"table",
"+=",
"\"</tbody></table>\"",
"return",
"table"
] | [
225,
0
] | [
268,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
UserCallback.extract_userid | (user: str, *, cursor) | return userid | Obtiene el identificador de usuario a partir del nombre del mismo | Obtiene el identificador de usuario a partir del nombre del mismo | async def extract_userid(user: str, *, cursor) -> int:
"""Obtiene el identificador de usuario a partir del nombre del mismo"""
await cursor.execute(
"SELECT id FROM users WHERE user = %s LIMIT 1", (user,)
)
userid = await cursor.fetchone()
return userid | [
"async",
"def",
"extract_userid",
"(",
"user",
":",
"str",
",",
"*",
",",
"cursor",
")",
"->",
"int",
":",
"await",
"cursor",
".",
"execute",
"(",
"\"SELECT id FROM users WHERE user = %s LIMIT 1\"",
",",
"(",
"user",
",",
")",
")",
"userid",
"=",
"await",
"cursor",
".",
"fetchone",
"(",
")",
"return",
"userid"
] | [
185,
4
] | [
195,
21
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_funciones30 | (p) | funciones : COSH PABRE expresion PCIERRA | funciones : COSH PABRE expresion PCIERRA | def p_funciones30(p):
'funciones : COSH PABRE expresion PCIERRA' | [
"def",
"p_funciones30",
"(",
"p",
")",
":"
] | [
388,
0
] | [
389,
46
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
getStatus | (
apiclient: ApiClient,
token: str,
) | Obtiene el estado de un pago previamente creado, el parametro token
hace referencia a notification id, el cual se recibe luego de procesado
un pago
| Obtiene el estado de un pago previamente creado, el parametro token
hace referencia a notification id, el cual se recibe luego de procesado
un pago
| def getStatus(
apiclient: ApiClient,
token: str,
) -> Union[PaymentStatus, Error,]:
"""Obtiene el estado de un pago previamente creado, el parametro token
hace referencia a notification id, el cual se recibe luego de procesado
un pago
"""
url = f"{apiclient.api_url}/payment/getStatus"
params: Dict[str, Any] = {"apiKey": apiclient.api_key, "token": token}
signature = apiclient.make_signature(params)
params["s"] = signature
logging.debug("Before Request:" + str(params))
response = apiclient.get(url, params)
if response.status_code == 200:
return PaymentStatus.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",
"getStatus",
"(",
"apiclient",
":",
"ApiClient",
",",
"token",
":",
"str",
",",
")",
"->",
"Union",
"[",
"PaymentStatus",
",",
"Error",
",",
"]",
":",
"url",
"=",
"f\"{apiclient.api_url}/payment/getStatus\"",
"params",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
"=",
"{",
"\"apiKey\"",
":",
"apiclient",
".",
"api_key",
",",
"\"token\"",
":",
"token",
"}",
"signature",
"=",
"apiclient",
".",
"make_signature",
"(",
"params",
")",
"params",
"[",
"\"s\"",
"]",
"=",
"signature",
"logging",
".",
"debug",
"(",
"\"Before Request:\"",
"+",
"str",
"(",
"params",
")",
")",
"response",
"=",
"apiclient",
".",
"get",
"(",
"url",
",",
"params",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"PaymentStatus",
".",
"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",
")"
] | [
7,
0
] | [
30,
42
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones59 | (p) | funciones : SUM PABRE ID PCIERRA | funciones : SUM PABRE ID PCIERRA | def p_funciones59(p):
'funciones : SUM PABRE ID PCIERRA' | [
"def",
"p_funciones59",
"(",
"p",
")",
":"
] | [
475,
0
] | [
476,
38
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Textos.fuentes | (font,size) | return fuente | Crea una fuente pygame para usarla al imprimir en pantalla.
Parametros:
font (fuente): El nombre de la fuente a usar, debe estar instalada en el dispositivo.
size (int, float): Tamaño de la fuente a usar.
Returns:
fuente: pygame.font.SysFont
| Crea una fuente pygame para usarla al imprimir en pantalla.
Parametros:
font (fuente): El nombre de la fuente a usar, debe estar instalada en el dispositivo.
size (int, float): Tamaño de la fuente a usar.
Returns:
fuente: pygame.font.SysFont
| def fuentes(font,size):
"""Crea una fuente pygame para usarla al imprimir en pantalla.
Parametros:
font (fuente): El nombre de la fuente a usar, debe estar instalada en el dispositivo.
size (int, float): Tamaño de la fuente a usar.
Returns:
fuente: pygame.font.SysFont
"""
fuente = pygame.font.SysFont(font, size)
return fuente | [
"def",
"fuentes",
"(",
"font",
",",
"size",
")",
":",
"fuente",
"=",
"pygame",
".",
"font",
".",
"SysFont",
"(",
"font",
",",
"size",
")",
"return",
"fuente"
] | [
3,
4
] | [
14,
21
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
Configberry.findByMac | (self, mac) | return False | Busca entre todas las sections por la mac | Busca entre todas las sections por la mac | def findByMac(self, mac):
"Busca entre todas las sections por la mac"
for s in self.sections()[1:]:
if self.config.has_option(s, 'mac'):
mymac = self.config.get(s, 'mac')
print("mymac %s y la otra es mac %s" % (mymac, mac))
if mymac == mac:
print(s)
return (s, self.get_config_for_printer(s))
return False | [
"def",
"findByMac",
"(",
"self",
",",
"mac",
")",
":",
"for",
"s",
"in",
"self",
".",
"sections",
"(",
")",
"[",
"1",
":",
"]",
":",
"if",
"self",
".",
"config",
".",
"has_option",
"(",
"s",
",",
"'mac'",
")",
":",
"mymac",
"=",
"self",
".",
"config",
".",
"get",
"(",
"s",
",",
"'mac'",
")",
"print",
"(",
"\"mymac %s y la otra es mac %s\"",
"%",
"(",
"mymac",
",",
"mac",
")",
")",
"if",
"mymac",
"==",
"mac",
":",
"print",
"(",
"s",
")",
"return",
"(",
"s",
",",
"self",
".",
"get_config_for_printer",
"(",
"s",
")",
")",
"return",
"False"
] | [
30,
4
] | [
39,
20
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_sentencia_function_definicion_function | (t) | definicion_function : declaraciones_procedure BEGIN END | definicion_function : declaraciones_procedure BEGIN END | def p_sentencia_function_definicion_function(t):
'definicion_function : declaraciones_procedure BEGIN END'
t[0] = Start('CUERPO_FUNCTION')
t[0].hijos.append(t[1])
bloque = Bloque('BLOQUE_SENTENCIA')
t[0].hijos.append(bloque) | [
"def",
"p_sentencia_function_definicion_function",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"Start",
"(",
"'CUERPO_FUNCTION'",
")",
"t",
"[",
"0",
"]",
".",
"hijos",
".",
"append",
"(",
"t",
"[",
"1",
"]",
")",
"bloque",
"=",
"Bloque",
"(",
"'BLOQUE_SENTENCIA'",
")",
"t",
"[",
"0",
"]",
".",
"hijos",
".",
"append",
"(",
"bloque",
")"
] | [
1723,
0
] | [
1728,
29
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
Parser.build | (
self,
message: bytes,
*args, **kwargs
) | return hibrid.encrypt(
self.local_key,
self.session.destination,
self.session.source.private,
message,
*args, **kwargs
) | Cifra para realizar una petición al servidor.
Esta es la contraparte de `destroy()`
Args:
message:
El mensaje a cifrar
signing_key:
La clave de firmado
*args:
Argumentos variables para `hibrid.encrypt()`
**kwargs:
Argumentos claves variables para `hibrid.encrypt()`
Returns:
Los datos cifrados y firmados
| Cifra para realizar una petición al servidor.
Esta es la contraparte de `destroy()` | def build(
self,
message: bytes,
*args, **kwargs
) -> bytes:
"""Cifra para realizar una petición al servidor.
Esta es la contraparte de `destroy()`
Args:
message:
El mensaje a cifrar
signing_key:
La clave de firmado
*args:
Argumentos variables para `hibrid.encrypt()`
**kwargs:
Argumentos claves variables para `hibrid.encrypt()`
Returns:
Los datos cifrados y firmados
"""
return hibrid.encrypt(
self.local_key,
self.session.destination,
self.session.source.private,
message,
*args, **kwargs
) | [
"def",
"build",
"(",
"self",
",",
"message",
":",
"bytes",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"bytes",
":",
"return",
"hibrid",
".",
"encrypt",
"(",
"self",
".",
"local_key",
",",
"self",
".",
"session",
".",
"destination",
",",
"self",
".",
"session",
".",
"source",
".",
"private",
",",
"message",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | [
178,
4
] | [
212,
16
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
Frases.cumplimiento | (self, doc) | return doc | Cambia valores durante componente cumplimiento si falla filtros.
Parameters
----------
doc : spacy.tokens.Doc
Returns
-------
doc : spacy.tokens.Doc
| Cambia valores durante componente cumplimiento si falla filtros. | def cumplimiento(self, doc):
"""Cambia valores durante componente cumplimiento si falla filtros.
Parameters
----------
doc : spacy.tokens.Doc
Returns
-------
doc : spacy.tokens.Doc
"""
for token in doc:
if not self.token_cumple(token):
token._.set("ok_token", False)
return doc | [
"def",
"cumplimiento",
"(",
"self",
",",
"doc",
")",
":",
"for",
"token",
"in",
"doc",
":",
"if",
"not",
"self",
".",
"token_cumple",
"(",
"token",
")",
":",
"token",
".",
"_",
".",
"set",
"(",
"\"ok_token\"",
",",
"False",
")",
"return",
"doc"
] | [
150,
4
] | [
165,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_funciones50 | (p) | funciones : POWER PABRE expresion COMA expresion PCIERRA | funciones : POWER PABRE expresion COMA expresion PCIERRA | def p_funciones50(p):
'funciones : POWER PABRE expresion COMA expresion PCIERRA' | [
"def",
"p_funciones50",
"(",
"p",
")",
":"
] | [
448,
0
] | [
449,
62
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_inst_generales_ins | (t) | instrucciones_generales : instrucciones_generales instruccion2 | instrucciones_generales : instrucciones_generales instruccion2 | def p_inst_generales_ins(t):
'''instrucciones_generales : instrucciones_generales instruccion2'''
t[1].append(t[2])
t[0] = t[1] | [
"def",
"p_inst_generales_ins",
"(",
"t",
")",
":",
"t",
"[",
"1",
"]",
".",
"append",
"(",
"t",
"[",
"2",
"]",
")",
"t",
"[",
"0",
"]",
"=",
"t",
"[",
"1",
"]"
] | [
2262,
0
] | [
2265,
15
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
TraductorFiscal._imprimirPago | (self, ds, importe) | return self.comando.addPayment(ds, float(importe)) | Imprime una linea con la forma de pago y monto | Imprime una linea con la forma de pago y monto | def _imprimirPago(self, ds, importe):
"Imprime una linea con la forma de pago y monto"
self.factura["pagos"].append(dict(ds=ds, importe=importe))
return self.comando.addPayment(ds, float(importe)) | [
"def",
"_imprimirPago",
"(",
"self",
",",
"ds",
",",
"importe",
")",
":",
"self",
".",
"factura",
"[",
"\"pagos\"",
"]",
".",
"append",
"(",
"dict",
"(",
"ds",
"=",
"ds",
",",
"importe",
"=",
"importe",
")",
")",
"return",
"self",
".",
"comando",
".",
"addPayment",
"(",
"ds",
",",
"float",
"(",
"importe",
")",
")"
] | [
176,
4
] | [
179,
58
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
run | () | Anda creando una matriz números del 0-8 y loego los reorganiza de 3 ern 3 | Anda creando una matriz números del 0-8 y loego los reorganiza de 3 ern 3 | def run():
"""Anda creando una matriz números del 0-8 y loego los reorganiza de 3 ern 3"""
A = numpy.arange(9).reshape((3, 3))
"""Aki va a imprimir la matriz A, que tiene valores del 0 al 8, de 3 en 3"""
print(A)
"""Aquí va a impirmir el resultado de nuestra función"""
print(rebenale_primera_ultima_col(A)) | [
"def",
"run",
"(",
")",
":",
"A",
"=",
"numpy",
".",
"arange",
"(",
"9",
")",
".",
"reshape",
"(",
"(",
"3",
",",
"3",
")",
")",
"\"\"\"Aki va a imprimir la matriz A, que tiene valores del 0 al 8, de 3 en 3\"\"\"",
"print",
"(",
"A",
")",
"\"\"\"Aquí va a impirmir el resultado de nuestra función\"\"\"",
"print",
"(",
"rebenale_primera_ultima_col",
"(",
"A",
")",
")"
] | [
2,
0
] | [
8,
41
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
verify | (hash2text: str, password: str) | return hash_func.verify(hash2text, password) | Verifica si una contraseña es correcta
Args:
hash2text:
El hash generado por argon2 sobre la contraseña
password:
La contraseña a verificar
Returns:
**True** si la contraseña es correcta
| Verifica si una contraseña es correcta
Args:
hash2text:
El hash generado por argon2 sobre la contraseña | def verify(hash2text: str, password: str) -> bool:
"""Verifica si una contraseña es correcta
Args:
hash2text:
El hash generado por argon2 sobre la contraseña
password:
La contraseña a verificar
Returns:
**True** si la contraseña es correcta
"""
hash_params = argon2.extract_parameters(hash2text)
hash_func = argon2.PasswordHasher(
hash_params.time_cost,
hash_params.memory_cost,
hash_params.parallelism,
hash_params.hash_len,
hash_params.salt_len,
type=hash_params.type
)
return hash_func.verify(hash2text, password) | [
"def",
"verify",
"(",
"hash2text",
":",
"str",
",",
"password",
":",
"str",
")",
"->",
"bool",
":",
"hash_params",
"=",
"argon2",
".",
"extract_parameters",
"(",
"hash2text",
")",
"hash_func",
"=",
"argon2",
".",
"PasswordHasher",
"(",
"hash_params",
".",
"time_cost",
",",
"hash_params",
".",
"memory_cost",
",",
"hash_params",
".",
"parallelism",
",",
"hash_params",
".",
"hash_len",
",",
"hash_params",
".",
"salt_len",
",",
"type",
"=",
"hash_params",
".",
"type",
")",
"return",
"hash_func",
".",
"verify",
"(",
"hash2text",
",",
"password",
")"
] | [
3,
0
] | [
28,
48
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
_toHash | (data) | return md(l.encode()) | convierte las tuplas a hash | convierte las tuplas a hash | def _toHash(data):
"""convierte las tuplas a hash"""
if type(data) is str:
return md(data.encode())
l = ""
for x in data:
l = l + str(x)
return md(l.encode()) | [
"def",
"_toHash",
"(",
"data",
")",
":",
"if",
"type",
"(",
"data",
")",
"is",
"str",
":",
"return",
"md",
"(",
"data",
".",
"encode",
"(",
")",
")",
"l",
"=",
"\"\"",
"for",
"x",
"in",
"data",
":",
"l",
"=",
"l",
"+",
"str",
"(",
"x",
")",
"return",
"md",
"(",
"l",
".",
"encode",
"(",
")",
")"
] | [
83,
0
] | [
90,
25
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
area | (n: int, l:float) | return ((l**2) * n)/(4 * tan(pi/n)) | Calcula el área de un polígono regular.
:param l: longitud de un lado
:l type: float
:param n: numero de lados
:n type: int
:return: area del poligono
:rtype: float
| Calcula el área de un polígono regular.
:param l: longitud de un lado
:l type: float
:param n: numero de lados
:n type: int
:return: area del poligono
:rtype: float
| def area(n: int, l:float):
"""Calcula el área de un polígono regular.
:param l: longitud de un lado
:l type: float
:param n: numero de lados
:n type: int
:return: area del poligono
:rtype: float
"""
return ((l**2) * n)/(4 * tan(pi/n)) | [
"def",
"area",
"(",
"n",
":",
"int",
",",
"l",
":",
"float",
")",
":",
"return",
"(",
"(",
"l",
"**",
"2",
")",
"*",
"n",
")",
"/",
"(",
"4",
"*",
"tan",
"(",
"pi",
"/",
"n",
")",
")"
] | [
24,
0
] | [
34,
39
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
get_residue | (path: str, chain: str, residue: str) | Funcion que pide como input un path de tipo str de un archivo
pdb, el nombre de una cadena de tipo str, y el nombre de un
residuo de tipo str, devolviendo una lista de los residuos de esa
cadena contenidos en el archivo pdb | Funcion que pide como input un path de tipo str de un archivo
pdb, el nombre de una cadena de tipo str, y el nombre de un
residuo de tipo str, devolviendo una lista de los residuos de esa
cadena contenidos en el archivo pdb | def get_residue(path: str, chain: str, residue: str):
"""Funcion que pide como input un path de tipo str de un archivo
pdb, el nombre de una cadena de tipo str, y el nombre de un
residuo de tipo str, devolviendo una lista de los residuos de esa
cadena contenidos en el archivo pdb"""
try:
# Obtener nombre del archivo del path
name = search(r'[^/]*pdb$', path)
# Verificar si es un archivo pdb
if name is None:
raise SystemExit(f"El path = '{path}' "
f"no es de un archivo pdb")
name = name.group(0)
# Obtener estructura del archivo
parser = PDB.PDBParser(QUIET=True)
struc = parser.get_structure(name, path)
# Obtener los residuos y guardarlos en la lista
rs_chain = []
for model in struc:
for rs in model.child_dict[chain]:
if rs.get_resname() == residue:
rs_chain.append(rs)
return rs_chain
except FileNotFoundError as ex:
raise SystemExit("El archivo no se pudo abrir: "
+ ex.strerror) | [
"def",
"get_residue",
"(",
"path",
":",
"str",
",",
"chain",
":",
"str",
",",
"residue",
":",
"str",
")",
":",
"try",
":",
"# Obtener nombre del archivo del path",
"name",
"=",
"search",
"(",
"r'[^/]*pdb$'",
",",
"path",
")",
"# Verificar si es un archivo pdb",
"if",
"name",
"is",
"None",
":",
"raise",
"SystemExit",
"(",
"f\"El path = '{path}' \"",
"f\"no es de un archivo pdb\"",
")",
"name",
"=",
"name",
".",
"group",
"(",
"0",
")",
"# Obtener estructura del archivo",
"parser",
"=",
"PDB",
".",
"PDBParser",
"(",
"QUIET",
"=",
"True",
")",
"struc",
"=",
"parser",
".",
"get_structure",
"(",
"name",
",",
"path",
")",
"# Obtener los residuos y guardarlos en la lista",
"rs_chain",
"=",
"[",
"]",
"for",
"model",
"in",
"struc",
":",
"for",
"rs",
"in",
"model",
".",
"child_dict",
"[",
"chain",
"]",
":",
"if",
"rs",
".",
"get_resname",
"(",
")",
"==",
"residue",
":",
"rs_chain",
".",
"append",
"(",
"rs",
")",
"return",
"rs_chain",
"except",
"FileNotFoundError",
"as",
"ex",
":",
"raise",
"SystemExit",
"(",
"\"El archivo no se pudo abrir: \"",
"+",
"ex",
".",
"strerror",
")"
] | [
59,
0
] | [
88,
39
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
RoomViewSet.destroy | (self, request, *args, **kwargs) | return Response(mensaje, status=status.HTTP_204_NO_CONTENT) | Después del resumen de partida, se eliminan los datos de la DB | Después del resumen de partida, se eliminan los datos de la DB | def destroy(self, request, *args, **kwargs):
"""Después del resumen de partida, se eliminan los datos de la DB """
instance = self.get_object()
self.perform_destroy(instance)
mensaje={
'info':'Datos eliminados.'
}
return Response(mensaje, status=status.HTTP_204_NO_CONTENT) | [
"def",
"destroy",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"instance",
"=",
"self",
".",
"get_object",
"(",
")",
"self",
".",
"perform_destroy",
"(",
"instance",
")",
"mensaje",
"=",
"{",
"'info'",
":",
"'Datos eliminados.'",
"}",
"return",
"Response",
"(",
"mensaje",
",",
"status",
"=",
"status",
".",
"HTTP_204_NO_CONTENT",
")"
] | [
52,
4
] | [
59,
67
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
MapServerLayer.dame_metadatos_asociado_a_banda | (self) | Esta version del metodo tiene en cuenta el raster_layer del mapa actual,
o sea, solo devuelve metadatos de ese "subproducto", pensado para llamar desde la vista detalle del mapa
| Esta version del metodo tiene en cuenta el raster_layer del mapa actual,
o sea, solo devuelve metadatos de ese "subproducto", pensado para llamar desde la vista detalle del mapa
| def dame_metadatos_asociado_a_banda(self):
""" Esta version del metodo tiene en cuenta el raster_layer del mapa actual,
o sea, solo devuelve metadatos de ese "subproducto", pensado para llamar desde la vista detalle del mapa
"""
if self.bandas != '':
if len(self.capa.gdal_metadata['subdatasets']) > 0:
for b in self.capa.gdal_metadata['subdatasets']:
if b.get('identificador') == self.bandas:
return [sorted(b['gdalinfo']['metadata'][''].iteritems())]
else:
try:
res = []
bandas = str(self.bandas).split(',') # array de bandas, Ej: ['4'], ['5', '6']
for b in self.capa.gdal_metadata['gdalinfo']['bands']:
if str(b['band']) in bandas:
metadatos = b['metadata']['']
metadatos['BAND'] = b['band']
res.append(sorted(metadatos.iteritems()))
return res
except:
return []
else:
return [] | [
"def",
"dame_metadatos_asociado_a_banda",
"(",
"self",
")",
":",
"if",
"self",
".",
"bandas",
"!=",
"''",
":",
"if",
"len",
"(",
"self",
".",
"capa",
".",
"gdal_metadata",
"[",
"'subdatasets'",
"]",
")",
">",
"0",
":",
"for",
"b",
"in",
"self",
".",
"capa",
".",
"gdal_metadata",
"[",
"'subdatasets'",
"]",
":",
"if",
"b",
".",
"get",
"(",
"'identificador'",
")",
"==",
"self",
".",
"bandas",
":",
"return",
"[",
"sorted",
"(",
"b",
"[",
"'gdalinfo'",
"]",
"[",
"'metadata'",
"]",
"[",
"''",
"]",
".",
"iteritems",
"(",
")",
")",
"]",
"else",
":",
"try",
":",
"res",
"=",
"[",
"]",
"bandas",
"=",
"str",
"(",
"self",
".",
"bandas",
")",
".",
"split",
"(",
"','",
")",
"# array de bandas, Ej: ['4'], ['5', '6']",
"for",
"b",
"in",
"self",
".",
"capa",
".",
"gdal_metadata",
"[",
"'gdalinfo'",
"]",
"[",
"'bands'",
"]",
":",
"if",
"str",
"(",
"b",
"[",
"'band'",
"]",
")",
"in",
"bandas",
":",
"metadatos",
"=",
"b",
"[",
"'metadata'",
"]",
"[",
"''",
"]",
"metadatos",
"[",
"'BAND'",
"]",
"=",
"b",
"[",
"'band'",
"]",
"res",
".",
"append",
"(",
"sorted",
"(",
"metadatos",
".",
"iteritems",
"(",
")",
")",
")",
"return",
"res",
"except",
":",
"return",
"[",
"]",
"else",
":",
"return",
"[",
"]"
] | [
714,
4
] | [
736,
21
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ModelGraphs.plot_loss | (history, title="Model Loss") | Imprime una gráfica mostrando la pérdida por epoch obtenida en un entrenamiento | Imprime una gráfica mostrando la pérdida por epoch obtenida en un entrenamiento | def plot_loss(history, title="Model Loss"):
"""Imprime una gráfica mostrando la pérdida por epoch obtenida en un entrenamiento"""
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title(title)
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Val'], loc='upper right')
plt.show() | [
"def",
"plot_loss",
"(",
"history",
",",
"title",
"=",
"\"Model Loss\"",
")",
":",
"plt",
".",
"plot",
"(",
"history",
".",
"history",
"[",
"'loss'",
"]",
")",
"plt",
".",
"plot",
"(",
"history",
".",
"history",
"[",
"'val_loss'",
"]",
")",
"plt",
".",
"title",
"(",
"title",
")",
"plt",
".",
"ylabel",
"(",
"'Loss'",
")",
"plt",
".",
"xlabel",
"(",
"'Epoch'",
")",
"plt",
".",
"legend",
"(",
"[",
"'Train'",
",",
"'Val'",
"]",
",",
"loc",
"=",
"'upper right'",
")",
"plt",
".",
"show",
"(",
")"
] | [
17,
4
] | [
25,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
CampoCambio.brother | (self, campo) | return self.cambio.campos.filter(campo=campo).first() | campo cambiado en base a otro campo del mismo cambio | campo cambiado en base a otro campo del mismo cambio | def brother(self, campo):
""" campo cambiado en base a otro campo del mismo cambio """
return self.cambio.campos.filter(campo=campo).first() | [
"def",
"brother",
"(",
"self",
",",
"campo",
")",
":",
"return",
"self",
".",
"cambio",
".",
"campos",
".",
"filter",
"(",
"campo",
"=",
"campo",
")",
".",
"first",
"(",
")"
] | [
50,
4
] | [
52,
61
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
Battery.upgrade_battery | (self) | Actualice la batería si es posible. | Actualice la batería si es posible. | def upgrade_battery(self):
"""Actualice la batería si es posible."""
if self.battery_size == 60:
self.battery_size = 85
print("Actualizó la batería a 85 kWh.")
else:
print("La batería ya está actualizada") | [
"def",
"upgrade_battery",
"(",
"self",
")",
":",
"if",
"self",
".",
"battery_size",
"==",
"60",
":",
"self",
".",
"battery_size",
"=",
"85",
"print",
"(",
"\"Actualizó la batería a 85 kWh.\")",
"",
"else",
":",
"print",
"(",
"\"La batería ya está actualizada\")",
""
] | [
56,
4
] | [
62,
53
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_llamada_funciones1_expresiones | (t) | llamadafunciones : ID PARIZQ listaExpresiones PARDR | llamadafunciones : ID PARIZQ listaExpresiones PARDR | def p_llamada_funciones1_expresiones(t):
'''llamadafunciones : ID PARIZQ listaExpresiones PARDR'''
global columna
t[0] = Llamada(1, t[1], t[3], lexer.lineno, columna) | [
"def",
"p_llamada_funciones1_expresiones",
"(",
"t",
")",
":",
"global",
"columna",
"t",
"[",
"0",
"]",
"=",
"Llamada",
"(",
"1",
",",
"t",
"[",
"1",
"]",
",",
"t",
"[",
"3",
"]",
",",
"lexer",
".",
"lineno",
",",
"columna",
")"
] | [
1755,
0
] | [
1758,
56
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
ModelBase.get_field_info_dict | (cls, field) | return out | Obtiene la información del campo indicado, en un diccionario. | Obtiene la información del campo indicado, en un diccionario. | def get_field_info_dict(cls, field) -> dict:
"""Obtiene la información del campo indicado, en un diccionario."""
out = {
"name": field.name,
"verbose_name": getattr(field, "verbose_name", field.name.replace("_", " ")),
"help_text": getattr(field, "help_text", ""),
"max_length": getattr(field, "max_length", None),
"blank": getattr(field, "blank", None),
"null": getattr(field, "null", None),
"editable": getattr(field, "editable", False),
"choices": getattr(field, "choices", None),
"type": field.__class__.__name__
}
default = getattr(field, "default", "_NOT_PROVIDED")
if default == models.fields.NOT_PROVIDED:
out["default"] = "_NOT_PROVIDED"
else:
try:
out["default"] = default()
except (TypeError):
out["default"] = default
try:
out["related_model"] = field.related_model._meta.model_name
out["related_app"] = field.related_model._meta.app_label
except (AttributeError):
out["related_model"] = None
out["related_app"] = None
return out | [
"def",
"get_field_info_dict",
"(",
"cls",
",",
"field",
")",
"->",
"dict",
":",
"out",
"=",
"{",
"\"name\"",
":",
"field",
".",
"name",
",",
"\"verbose_name\"",
":",
"getattr",
"(",
"field",
",",
"\"verbose_name\"",
",",
"field",
".",
"name",
".",
"replace",
"(",
"\"_\"",
",",
"\" \"",
")",
")",
",",
"\"help_text\"",
":",
"getattr",
"(",
"field",
",",
"\"help_text\"",
",",
"\"\"",
")",
",",
"\"max_length\"",
":",
"getattr",
"(",
"field",
",",
"\"max_length\"",
",",
"None",
")",
",",
"\"blank\"",
":",
"getattr",
"(",
"field",
",",
"\"blank\"",
",",
"None",
")",
",",
"\"null\"",
":",
"getattr",
"(",
"field",
",",
"\"null\"",
",",
"None",
")",
",",
"\"editable\"",
":",
"getattr",
"(",
"field",
",",
"\"editable\"",
",",
"False",
")",
",",
"\"choices\"",
":",
"getattr",
"(",
"field",
",",
"\"choices\"",
",",
"None",
")",
",",
"\"type\"",
":",
"field",
".",
"__class__",
".",
"__name__",
"}",
"default",
"=",
"getattr",
"(",
"field",
",",
"\"default\"",
",",
"\"_NOT_PROVIDED\"",
")",
"if",
"default",
"==",
"models",
".",
"fields",
".",
"NOT_PROVIDED",
":",
"out",
"[",
"\"default\"",
"]",
"=",
"\"_NOT_PROVIDED\"",
"else",
":",
"try",
":",
"out",
"[",
"\"default\"",
"]",
"=",
"default",
"(",
")",
"except",
"(",
"TypeError",
")",
":",
"out",
"[",
"\"default\"",
"]",
"=",
"default",
"try",
":",
"out",
"[",
"\"related_model\"",
"]",
"=",
"field",
".",
"related_model",
".",
"_meta",
".",
"model_name",
"out",
"[",
"\"related_app\"",
"]",
"=",
"field",
".",
"related_model",
".",
"_meta",
".",
"app_label",
"except",
"(",
"AttributeError",
")",
":",
"out",
"[",
"\"related_model\"",
"]",
"=",
"None",
"out",
"[",
"\"related_app\"",
"]",
"=",
"None",
"return",
"out"
] | [
151,
4
] | [
178,
18
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
DNARecord.rev_comp | (self) | return t_seq | Obtiene la cadena complementaria reversa. | Obtiene la cadena complementaria reversa. | def rev_comp(self):
"""Obtiene la cadena complementaria reversa."""
# Obtener elementos unicos
nt_list = list(set(self.seq))
t_seq = self.seq
# Reemplazar los nucleotidos con el diccionario
for nt in nt_list:
t_seq = t_seq.replace(nt, complement[nt])
# Devolver en mayusculas
t_seq = t_seq.upper()
return t_seq | [
"def",
"rev_comp",
"(",
"self",
")",
":",
"# Obtener elementos unicos",
"nt_list",
"=",
"list",
"(",
"set",
"(",
"self",
".",
"seq",
")",
")",
"t_seq",
"=",
"self",
".",
"seq",
"# Reemplazar los nucleotidos con el diccionario",
"for",
"nt",
"in",
"nt_list",
":",
"t_seq",
"=",
"t_seq",
".",
"replace",
"(",
"nt",
",",
"complement",
"[",
"nt",
"]",
")",
"# Devolver en mayusculas",
"t_seq",
"=",
"t_seq",
".",
"upper",
"(",
")",
"return",
"t_seq"
] | [
100,
4
] | [
110,
20
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_lwhenvarios | (t) | lwhenv : cuandos | lwhenv : cuandos | def p_lwhenvarios(t):
''' lwhenv : cuandos'''
t[0] = [t[1]] | [
"def",
"p_lwhenvarios",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"[",
"t",
"[",
"1",
"]",
"]"
] | [
2672,
0
] | [
2674,
17
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_funciones21 | (p) | funciones : ATAN2D PABRE expresion COMA expresion PCIERRA | funciones : ATAN2D PABRE expresion COMA expresion PCIERRA | def p_funciones21(p):
'funciones : ATAN2D PABRE expresion COMA expresion PCIERRA' | [
"def",
"p_funciones21",
"(",
"p",
")",
":"
] | [
361,
0
] | [
362,
63
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
get_ultimas_transferencias | (limit=5) | return transferencias[:limit] | Dominios que pasan de un registrante a otros
Pueden no ser transferencias sino sino solo casos
donde el dominio esta libre poco tiempo y
lo registra otra persona. Pasa con dominios valiosos
| Dominios que pasan de un registrante a otros
Pueden no ser transferencias sino sino solo casos
donde el dominio esta libre poco tiempo y
lo registra otra persona. Pasa con dominios valiosos
| def get_ultimas_transferencias(limit=5):
""" Dominios que pasan de un registrante a otros
Pueden no ser transferencias sino sino solo casos
donde el dominio esta libre poco tiempo y
lo registra otra persona. Pasa con dominios valiosos
"""
transferencias = CampoCambio.objects\
.filter(campo='registrant_legal_uid')\
.exclude(anterior__exact="")\
.exclude(nuevo__exact="")\
.order_by('-cambio__momento')
return transferencias[:limit] | [
"def",
"get_ultimas_transferencias",
"(",
"limit",
"=",
"5",
")",
":",
"transferencias",
"=",
"CampoCambio",
".",
"objects",
".",
"filter",
"(",
"campo",
"=",
"'registrant_legal_uid'",
")",
".",
"exclude",
"(",
"anterior__exact",
"=",
"\"\"",
")",
".",
"exclude",
"(",
"nuevo__exact",
"=",
"\"\"",
")",
".",
"order_by",
"(",
"'-cambio__momento'",
")",
"return",
"transferencias",
"[",
":",
"limit",
"]"
] | [
25,
0
] | [
37,
33
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
p_inst_generales3 | (t) | instrucciones_generales : encabezado | instrucciones_generales : encabezado | def p_inst_generales3(t):
'''instrucciones_generales : encabezado'''
arr = []
arr1 = []
arr1.append('encabezado')
arr1.append(t[1])
arr.append(arr1)
t[0] = arr | [
"def",
"p_inst_generales3",
"(",
"t",
")",
":",
"arr",
"=",
"[",
"]",
"arr1",
"=",
"[",
"]",
"arr1",
".",
"append",
"(",
"'encabezado'",
")",
"arr1",
".",
"append",
"(",
"t",
"[",
"1",
"]",
")",
"arr",
".",
"append",
"(",
"arr1",
")",
"t",
"[",
"0",
"]",
"=",
"arr"
] | [
2251,
0
] | [
2260,
14
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_argument_funciones_binarias | (t) | argument : funcionesbinarias | argument : funcionesbinarias | def p_argument_funciones_binarias(t):
'''argument : funcionesbinarias''' | [
"def",
"p_argument_funciones_binarias",
"(",
"t",
")",
":"
] | [
449,
0
] | [
450,
39
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_opcion_from_1_0_0_1_0_1_0_0_ordenno | (t) | opcion_from : ID opcion_sobrenombre GROUP BY campos_c ORDER BY campos_c | opcion_from : ID opcion_sobrenombre GROUP BY campos_c ORDER BY campos_c | def p_opcion_from_1_0_0_1_0_1_0_0_ordenno(t):
'opcion_from : ID opcion_sobrenombre GROUP BY campos_c ORDER BY campos_c' | [
"def",
"p_opcion_from_1_0_0_1_0_1_0_0_ordenno",
"(",
"t",
")",
":"
] | [
1796,
0
] | [
1797,
79
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
p_liberar_funtion | (t) | liberar : DROP FUNCTION existencia lnombres | liberar : DROP FUNCTION existencia lnombres | def p_liberar_funtion(t):
'''liberar : DROP FUNCTION existencia lnombres'''
t[0] = Drop_Function(t[4]) | [
"def",
"p_liberar_funtion",
"(",
"t",
")",
":",
"t",
"[",
"0",
"]",
"=",
"Drop_Function",
"(",
"t",
"[",
"4",
"]",
")"
] | [
1807,
0
] | [
1809,
31
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
PointTracker._matching_step | (self,
frame_actual: int,
objects_actual: List[Object]) | return matched_objects | Paso que realiza el emparejamiento de los objetos.
Proceso:
#. Se buscan todos los objetos que constan como registrados (es decir, se han seguido
hasta hace poco).
#. Comprobar que hay algún objeto registrado o se ha detectado algún objeto en el frame
actual, si no, no hay emparejamiento que realizar.
#. Ordenar los objetos actuales y registrados por puntuación, así se harán el
emparejamiento con ellos primeramente.
#. Para cada objeto del frame actual: calcular su distancia y emparejarlo con el que
más cerca esté de los registrados, si la distancia es menor que un factor dado.
#. Finalmente se devuelven todos los emparejamientos realizados.
:param frame_actual: identificador del frame actual.
:param objects_actual: lista de objetos del frame actual.
:return: lista de emparejamientos si es que se ha realizado alguno, si no, None.
| Paso que realiza el emparejamiento de los objetos. | def _matching_step(self,
frame_actual: int,
objects_actual: List[Object]) -> Optional[List[MatchedObject]]:
"""Paso que realiza el emparejamiento de los objetos.
Proceso:
#. Se buscan todos los objetos que constan como registrados (es decir, se han seguido
hasta hace poco).
#. Comprobar que hay algún objeto registrado o se ha detectado algún objeto en el frame
actual, si no, no hay emparejamiento que realizar.
#. Ordenar los objetos actuales y registrados por puntuación, así se harán el
emparejamiento con ellos primeramente.
#. Para cada objeto del frame actual: calcular su distancia y emparejarlo con el que
más cerca esté de los registrados, si la distancia es menor que un factor dado.
#. Finalmente se devuelven todos los emparejamientos realizados.
:param frame_actual: identificador del frame actual.
:param objects_actual: lista de objetos del frame actual.
:return: lista de emparejamientos si es que se ha realizado alguno, si no, None.
"""
matched_objects = []
registered_tracked_objects = self.objects.registered_tracked_objects()
# Comprobar si hay algún objeto con el que poder emparejar.
if len(registered_tracked_objects) == 0:
return None
# Comprobar si hay algún objeto en el frame actual con el que poder emparejar.
if len(objects_actual) == 0:
return None
# Ordenar los objetos del frame actual por puntuación, así se hará el emparejamiento de
# ellos primero.
objects_actual.sort(reverse=True, key=lambda obj: obj.score)
# Ordenar los objetos registrados por puntuación también.
registered_tracked_objects.sort(reverse=True, key=lambda tobj: tobj[-1].object.score)
# Emparejar cada uno de los objetos del frame actual con los registrados.
for object_actual in objects_actual:
# Calcular las distancias del objeto actual a los registrados.
distances = [euclidean_norm(object_actual.center, tracked_object[-1].object.center)
for tracked_object in registered_tracked_objects]
# Obtener el objeto registro al que menor distancia existe.
index = distances.index(min(distances))
match = self.MatchedObject(previous=registered_tracked_objects[index],
actual=object_actual)
# Lista de objetos previous ya emparejados.
matched_registered_objects = [match.previous for match in matched_objects]
# Comprobación si el objeto registrado con el que se va a emparejar ya ha sido
# emparejado.
object_previous_matched = match.previous in matched_registered_objects
if not object_previous_matched and distances[index] <= self.max_distance_allowed:
previous_object_id = registered_tracked_objects[index].id
# Actualizar el objeto seguido con el nuevo emparejamiento.
self.objects.update_object(object_actual, previous_object_id, frame_actual)
# Guardar la información de los emparejamientos realizados.
matched_objects.append(match)
return matched_objects | [
"def",
"_matching_step",
"(",
"self",
",",
"frame_actual",
":",
"int",
",",
"objects_actual",
":",
"List",
"[",
"Object",
"]",
")",
"->",
"Optional",
"[",
"List",
"[",
"MatchedObject",
"]",
"]",
":",
"matched_objects",
"=",
"[",
"]",
"registered_tracked_objects",
"=",
"self",
".",
"objects",
".",
"registered_tracked_objects",
"(",
")",
"# Comprobar si hay algún objeto con el que poder emparejar.",
"if",
"len",
"(",
"registered_tracked_objects",
")",
"==",
"0",
":",
"return",
"None",
"# Comprobar si hay algún objeto en el frame actual con el que poder emparejar.",
"if",
"len",
"(",
"objects_actual",
")",
"==",
"0",
":",
"return",
"None",
"# Ordenar los objetos del frame actual por puntuación, así se hará el emparejamiento de",
"# ellos primero.",
"objects_actual",
".",
"sort",
"(",
"reverse",
"=",
"True",
",",
"key",
"=",
"lambda",
"obj",
":",
"obj",
".",
"score",
")",
"# Ordenar los objetos registrados por puntuación también.",
"registered_tracked_objects",
".",
"sort",
"(",
"reverse",
"=",
"True",
",",
"key",
"=",
"lambda",
"tobj",
":",
"tobj",
"[",
"-",
"1",
"]",
".",
"object",
".",
"score",
")",
"# Emparejar cada uno de los objetos del frame actual con los registrados.",
"for",
"object_actual",
"in",
"objects_actual",
":",
"# Calcular las distancias del objeto actual a los registrados.",
"distances",
"=",
"[",
"euclidean_norm",
"(",
"object_actual",
".",
"center",
",",
"tracked_object",
"[",
"-",
"1",
"]",
".",
"object",
".",
"center",
")",
"for",
"tracked_object",
"in",
"registered_tracked_objects",
"]",
"# Obtener el objeto registro al que menor distancia existe.",
"index",
"=",
"distances",
".",
"index",
"(",
"min",
"(",
"distances",
")",
")",
"match",
"=",
"self",
".",
"MatchedObject",
"(",
"previous",
"=",
"registered_tracked_objects",
"[",
"index",
"]",
",",
"actual",
"=",
"object_actual",
")",
"# Lista de objetos previous ya emparejados.",
"matched_registered_objects",
"=",
"[",
"match",
".",
"previous",
"for",
"match",
"in",
"matched_objects",
"]",
"# Comprobación si el objeto registrado con el que se va a emparejar ya ha sido",
"# emparejado.",
"object_previous_matched",
"=",
"match",
".",
"previous",
"in",
"matched_registered_objects",
"if",
"not",
"object_previous_matched",
"and",
"distances",
"[",
"index",
"]",
"<=",
"self",
".",
"max_distance_allowed",
":",
"previous_object_id",
"=",
"registered_tracked_objects",
"[",
"index",
"]",
".",
"id",
"# Actualizar el objeto seguido con el nuevo emparejamiento.",
"self",
".",
"objects",
".",
"update_object",
"(",
"object_actual",
",",
"previous_object_id",
",",
"frame_actual",
")",
"# Guardar la información de los emparejamientos realizados.",
"matched_objects",
".",
"append",
"(",
"match",
")",
"return",
"matched_objects"
] | [
39,
4
] | [
92,
30
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
move_files | (file_path: str, data_dictionary: dict) | Función para mover los archivos XML a las carpetas que se les indiquen.
Args:
file_path (str): Recibe la ruta del directorio en donde están los archivos XML.
data_dictionary (dict): Recibe el diccionario con los nombres de las carpetas,
y la lista de los archivos XML.
| Función para mover los archivos XML a las carpetas que se les indiquen. | def move_files(file_path: str, data_dictionary: dict) -> None:
""" Función para mover los archivos XML a las carpetas que se les indiquen.
Args:
file_path (str): Recibe la ruta del directorio en donde están los archivos XML.
data_dictionary (dict): Recibe el diccionario con los nombres de las carpetas,
y la lista de los archivos XML.
"""
try:
file_counter: int = 0
for folder_number in data_dictionary:
print(print_color(text=f'▼ {folder_number}', color=color_yellow_console))
mkdir_folder(number=folder_number)
for xml_file in data_dictionary[folder_number]:
file_counter += 1
file_size: int = os.stat(xml_file).st_size
shutil.move(f"{file_path}/{xml_file}", f"{file_path}/{str(folder_number)}/{xml_file}")
print_file_in_console: str = print_color(text=xml_file, color=color_blue_console)
print_text_size: str = print_color(text='Size Bytes', color=color_green_console)
print_size: str = print_color(text=str(file_size), color=color_yellow_console)
print(f" ►{print_file_in_console} {print_text_size} ► {print_size}")
print(f"{print_color(text='Total xml', color=color_green_console)} ► ► {file_counter} ◄ ◄")
except Exception as error_in_move_files:
print(print_color(
text="Error en mover los archivos XML",
color=color_red_console,
message_exception=error_in_move_files)) | [
"def",
"move_files",
"(",
"file_path",
":",
"str",
",",
"data_dictionary",
":",
"dict",
")",
"->",
"None",
":",
"try",
":",
"file_counter",
":",
"int",
"=",
"0",
"for",
"folder_number",
"in",
"data_dictionary",
":",
"print",
"(",
"print_color",
"(",
"text",
"=",
"f'▼ {folder_number}', ",
"c",
"lor=c",
"o",
"lor_yellow_console))",
"",
"",
"mkdir_folder",
"(",
"number",
"=",
"folder_number",
")",
"for",
"xml_file",
"in",
"data_dictionary",
"[",
"folder_number",
"]",
":",
"file_counter",
"+=",
"1",
"file_size",
":",
"int",
"=",
"os",
".",
"stat",
"(",
"xml_file",
")",
".",
"st_size",
"shutil",
".",
"move",
"(",
"f\"{file_path}/{xml_file}\"",
",",
"f\"{file_path}/{str(folder_number)}/{xml_file}\"",
")",
"print_file_in_console",
":",
"str",
"=",
"print_color",
"(",
"text",
"=",
"xml_file",
",",
"color",
"=",
"color_blue_console",
")",
"print_text_size",
":",
"str",
"=",
"print_color",
"(",
"text",
"=",
"'Size Bytes'",
",",
"color",
"=",
"color_green_console",
")",
"print_size",
":",
"str",
"=",
"print_color",
"(",
"text",
"=",
"str",
"(",
"file_size",
")",
",",
"color",
"=",
"color_yellow_console",
")",
"print",
"(",
"f\" ►{print_file_in_console} {print_text_size} ► {print_size}\")",
"",
"print",
"(",
"f\"{print_color(text='Total xml', color=color_green_console)} ► ► {file_counter} ◄ ◄\")",
"",
"except",
"Exception",
"as",
"error_in_move_files",
":",
"print",
"(",
"print_color",
"(",
"text",
"=",
"\"Error en mover los archivos XML\"",
",",
"color",
"=",
"color_red_console",
",",
"message_exception",
"=",
"error_in_move_files",
")",
")"
] | [
125,
0
] | [
151,
51
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
|
mayor_promedio_anual | (dict_: Dict[str, int], regiones: Tuple[str, ...]) | return max(regiones, key=dict_.get) | Determina la región con mayor promedio anual dentro de un
conjunto de regiones.
:param dict_: Diccionario con los promedios anuales de las regiones.
:dict_ type: Dict[str, int]
:param regiones: Tupla con las regiones a evaluar.
:regiones type: Tuple[str, ...]
:return: Nombre de la región con mayor promedio anual.
:rtype: str
| Determina la región con mayor promedio anual dentro de un
conjunto de regiones.
:param dict_: Diccionario con los promedios anuales de las regiones.
:dict_ type: Dict[str, int]
:param regiones: Tupla con las regiones a evaluar.
:regiones type: Tuple[str, ...]
:return: Nombre de la región con mayor promedio anual.
:rtype: str
| def mayor_promedio_anual(dict_: Dict[str, int], regiones: Tuple[str, ...]) -> str:
"""Determina la región con mayor promedio anual dentro de un
conjunto de regiones.
:param dict_: Diccionario con los promedios anuales de las regiones.
:dict_ type: Dict[str, int]
:param regiones: Tupla con las regiones a evaluar.
:regiones type: Tuple[str, ...]
:return: Nombre de la región con mayor promedio anual.
:rtype: str
"""
return max(regiones, key=dict_.get) | [
"def",
"mayor_promedio_anual",
"(",
"dict_",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
",",
"regiones",
":",
"Tuple",
"[",
"str",
",",
"...",
"]",
")",
"->",
"str",
":",
"return",
"max",
"(",
"regiones",
",",
"key",
"=",
"dict_",
".",
"get",
")"
] | [
63,
0
] | [
74,
39
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
DataCleaner.fecha_simple | (self, field, time_format, keep_original=False,
inplace=False) | return parsed_series | Regla para fechas sin hora, sin día o sin mes.
Args:
field (str): Campo a limpiar.
time_format (str): Formato temporal del campo.
Returns:
pandas.Series: Serie de strings limpios
| Regla para fechas sin hora, sin día o sin mes. | def fecha_simple(self, field, time_format, keep_original=False,
inplace=False):
"""Regla para fechas sin hora, sin día o sin mes.
Args:
field (str): Campo a limpiar.
time_format (str): Formato temporal del campo.
Returns:
pandas.Series: Serie de strings limpios
"""
field = self._normalize_field(field)
series = self.df[field]
parsed_series = series.apply(self._parse_date,
args=(time_format,))
if inplace:
self._update_series(field=field, prefix="isodate",
keep_original=keep_original,
new_series=parsed_series)
return parsed_series | [
"def",
"fecha_simple",
"(",
"self",
",",
"field",
",",
"time_format",
",",
"keep_original",
"=",
"False",
",",
"inplace",
"=",
"False",
")",
":",
"field",
"=",
"self",
".",
"_normalize_field",
"(",
"field",
")",
"series",
"=",
"self",
".",
"df",
"[",
"field",
"]",
"parsed_series",
"=",
"series",
".",
"apply",
"(",
"self",
".",
"_parse_date",
",",
"args",
"=",
"(",
"time_format",
",",
")",
")",
"if",
"inplace",
":",
"self",
".",
"_update_series",
"(",
"field",
"=",
"field",
",",
"prefix",
"=",
"\"isodate\"",
",",
"keep_original",
"=",
"keep_original",
",",
"new_series",
"=",
"parsed_series",
")",
"return",
"parsed_series"
] | [
529,
4
] | [
550,
28
] | null | python | es | ['es', 'es', 'es'] | True | true | null |
separar_numeros | (texto) | return re.sub(r'([A-Za-zÀ-Üà-ü]{2,}?|\))(\d+)', r'\1 \2', nuevo) | Separa números de palabras que los tienen.
Parameters
----------
texto : str
Returns
-------
str
Texto con números separados de palabras.
| Separa números de palabras que los tienen. | def separar_numeros(texto):
"""Separa números de palabras que los tienen.
Parameters
----------
texto : str
Returns
-------
str
Texto con números separados de palabras.
"""
nuevo = re.sub(r'(\d+)([A-Za-zÀ-Üà-ü]{2,}?|\()', r'\1 \2', texto)
return re.sub(r'([A-Za-zÀ-Üà-ü]{2,}?|\))(\d+)', r'\1 \2', nuevo) | [
"def",
"separar_numeros",
"(",
"texto",
")",
":",
"nuevo",
"=",
"re",
".",
"sub",
"(",
"r'(\\d+)([A-Za-zÀ-Üà-ü]{2,}?|\\()', r'",
"\\",
" \\2', te",
"x",
"o)",
"",
"return",
"re",
".",
"sub",
"(",
"r'([A-Za-zÀ-Üà-ü]{2,}?|\\))(\\d+)', r'",
"\\",
" \\2', nu",
"e",
"o)",
""
] | [
63,
0
] | [
77,
72
] | 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.