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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PoseRealsense.__init__ | (self, **kwargs) | Les paramètres sont à définir dans le fichier posenet.ini | Les paramètres sont à définir dans le fichier posenet.ini | def __init__(self, **kwargs):
"""Les paramètres sont à définir dans le fichier posenet.ini"""
self.threshold = kwargs.get('threshold', 0.2)
self.around = kwargs.get('around', 5)
self.width = kwargs.get('width_input', 1280)
self.height = kwargs.get('height_input', 720)
self.set_pipeline()
self.get_engine()
self.osc = OscClient(**kwargs)
self.get_colors() | [
"def",
"__init__",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"threshold",
"=",
"kwargs",
".",
"get",
"(",
"'threshold'",
",",
"0.2",
")",
"self",
".",
"around",
"=",
"kwargs",
".",
"get",
"(",
"'around'",
",",
"5",
")",
"self",
".",
"width",
"=",
"kwargs",
".",
"get",
"(",
"'width_input'",
",",
"1280",
")",
"self",
".",
"height",
"=",
"kwargs",
".",
"get",
"(",
"'height_input'",
",",
"720",
")",
"self",
".",
"set_pipeline",
"(",
")",
"self",
".",
"get_engine",
"(",
")",
"self",
".",
"osc",
"=",
"OscClient",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"get_colors",
"(",
")"
] | [
83,
4
] | [
94,
25
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
parcourt_arbre_avec_parent | (arbre, f) | Appelle f(noeud_parent.valeur, noeud.valeur) pour chaque noeud
de l'arbre à partir de la racine. | Appelle f(noeud_parent.valeur, noeud.valeur) pour chaque noeud
de l'arbre à partir de la racine. | def parcourt_arbre_avec_parent(arbre, f):
"""Appelle f(noeud_parent.valeur, noeud.valeur) pour chaque noeud
de l'arbre à partir de la racine."""
def parcourt_arbre_recursif(noeud_parent, noeud, f):
if noeud != None:
f(noeud_parent.valeur, noeud.valeur)
parcourt_arbre_recursif(noeud, noeud.gauche, f)
parcourt_arbre_recursif(noeud, noeud.droite, f)
if arbre.noeud != None:
parcourt_arbre_recursif(arbre.noeud, arbre.noeud.gauche, f)
parcourt_arbre_recursif(arbre.noeud, arbre.noeud.droite, f) | [
"def",
"parcourt_arbre_avec_parent",
"(",
"arbre",
",",
"f",
")",
":",
"def",
"parcourt_arbre_recursif",
"(",
"noeud_parent",
",",
"noeud",
",",
"f",
")",
":",
"if",
"noeud",
"!=",
"None",
":",
"f",
"(",
"noeud_parent",
".",
"valeur",
",",
"noeud",
".",
"valeur",
")",
"parcourt_arbre_recursif",
"(",
"noeud",
",",
"noeud",
".",
"gauche",
",",
"f",
")",
"parcourt_arbre_recursif",
"(",
"noeud",
",",
"noeud",
".",
"droite",
",",
"f",
")",
"if",
"arbre",
".",
"noeud",
"!=",
"None",
":",
"parcourt_arbre_recursif",
"(",
"arbre",
".",
"noeud",
",",
"arbre",
".",
"noeud",
".",
"gauche",
",",
"f",
")",
"parcourt_arbre_recursif",
"(",
"arbre",
".",
"noeud",
",",
"arbre",
".",
"noeud",
".",
"droite",
",",
"f",
")"
] | [
101,
0
] | [
112,
67
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Xp.bdd_set_xp | (self, userID: int, points: int, Type: str='add', guild: int=None) | Ajoute/reset de l'xp à un utilisateur dans la database | Ajoute/reset de l'xp à un utilisateur dans la database | async def bdd_set_xp(self, userID: int, points: int, Type: str='add', guild: int=None):
"""Ajoute/reset de l'xp à un utilisateur dans la database"""
try:
if not self.bot.database_online:
self.bot.unload_extension("fcts.xp")
return None
if points < 0:
return True
if guild is None:
cnx = self.bot.cnx_frm
else:
cnx = self.bot.cnx_xp
table = await self.get_table(guild)
cursor = cnx.cursor(dictionary = True)
if Type=='add':
query = ("INSERT INTO `{t}` (`userID`,`xp`) VALUES ('{u}','{p}') ON DUPLICATE KEY UPDATE xp = xp + '{p}';".format(t=table,p=points,u=userID))
else:
query = ("INSERT INTO `{t}` (`userID`,`xp`) VALUES ('{u}','{p}') ON DUPLICATE KEY UPDATE xp = '{p}';".format(t=table,p=points,u=userID))
cursor.execute(query)
cnx.commit()
cursor.close()
return True
except Exception as e:
await self.bot.get_cog('Errors').on_error(e,None)
return False | [
"async",
"def",
"bdd_set_xp",
"(",
"self",
",",
"userID",
":",
"int",
",",
"points",
":",
"int",
",",
"Type",
":",
"str",
"=",
"'add'",
",",
"guild",
":",
"int",
"=",
"None",
")",
":",
"try",
":",
"if",
"not",
"self",
".",
"bot",
".",
"database_online",
":",
"self",
".",
"bot",
".",
"unload_extension",
"(",
"\"fcts.xp\"",
")",
"return",
"None",
"if",
"points",
"<",
"0",
":",
"return",
"True",
"if",
"guild",
"is",
"None",
":",
"cnx",
"=",
"self",
".",
"bot",
".",
"cnx_frm",
"else",
":",
"cnx",
"=",
"self",
".",
"bot",
".",
"cnx_xp",
"table",
"=",
"await",
"self",
".",
"get_table",
"(",
"guild",
")",
"cursor",
"=",
"cnx",
".",
"cursor",
"(",
"dictionary",
"=",
"True",
")",
"if",
"Type",
"==",
"'add'",
":",
"query",
"=",
"(",
"\"INSERT INTO `{t}` (`userID`,`xp`) VALUES ('{u}','{p}') ON DUPLICATE KEY UPDATE xp = xp + '{p}';\"",
".",
"format",
"(",
"t",
"=",
"table",
",",
"p",
"=",
"points",
",",
"u",
"=",
"userID",
")",
")",
"else",
":",
"query",
"=",
"(",
"\"INSERT INTO `{t}` (`userID`,`xp`) VALUES ('{u}','{p}') ON DUPLICATE KEY UPDATE xp = '{p}';\"",
".",
"format",
"(",
"t",
"=",
"table",
",",
"p",
"=",
"points",
",",
"u",
"=",
"userID",
")",
")",
"cursor",
".",
"execute",
"(",
"query",
")",
"cnx",
".",
"commit",
"(",
")",
"cursor",
".",
"close",
"(",
")",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"await",
"self",
".",
"bot",
".",
"get_cog",
"(",
"'Errors'",
")",
".",
"on_error",
"(",
"e",
",",
"None",
")",
"return",
"False"
] | [
368,
4
] | [
392,
24
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Map.bouger_hitbox | (self, x, y) | Déplace les hitboxs de collision
Permets de déplacer les hitboxs de collisions, utilisé lors du
Déplacement du personnage ou de la camera
| Déplace les hitboxs de collision
Permets de déplacer les hitboxs de collisions, utilisé lors du
Déplacement du personnage ou de la camera
| def bouger_hitbox(self, x, y):
"""Déplace les hitboxs de collision
Permets de déplacer les hitboxs de collisions, utilisé lors du
Déplacement du personnage ou de la camera
"""
# nouvelle_liste va écraser la liste des constantes de collision pour les tuiles
for hitbox in cc.groupes["tuile"]: # Je parcours le contenu du groupe
hitbox.rect.move_ip(x, y) | [
"def",
"bouger_hitbox",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# nouvelle_liste va écraser la liste des constantes de collision pour les tuiles",
"for",
"hitbox",
"in",
"cc",
".",
"groupes",
"[",
"\"tuile\"",
"]",
":",
"# Je parcours le contenu du groupe",
"hitbox",
".",
"rect",
".",
"move_ip",
"(",
"x",
",",
"y",
")"
] | [
79,
4
] | [
86,
37
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
domoticz_rename_device | (idx, nom) | return req.status_code | renomme un device dans domoticz
| renomme un device dans domoticz
| def domoticz_rename_device(idx, nom):
''' renomme un device dans domoticz
'''
nom = str(nom)
# renomme un device domoticz
myurl=url_domoticz+'command¶m=renamedevice&idx='+idx+'&name='+nom
req=requests.get(myurl)
if debug:
print(u' '.join((u'GET-> ',myurl,' : ',str(req.status_code))).encode('utf-8'))
if (req.status_code != 200):
http_error(req.status_code,req.reason) # Appel fonction sur erreur HTTP
return req.status_code | [
"def",
"domoticz_rename_device",
"(",
"idx",
",",
"nom",
")",
":",
"nom",
"=",
"str",
"(",
"nom",
")",
"# renomme un device domoticz",
"myurl",
"=",
"url_domoticz",
"+",
"'command¶m=renamedevice&idx='",
"+",
"idx",
"+",
"'&name='",
"+",
"nom",
"req",
"=",
"requests",
".",
"get",
"(",
"myurl",
")",
"if",
"debug",
":",
"print",
"(",
"u' '",
".",
"join",
"(",
"(",
"u'GET-> '",
",",
"myurl",
",",
"' : '",
",",
"str",
"(",
"req",
".",
"status_code",
")",
")",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"if",
"(",
"req",
".",
"status_code",
"!=",
"200",
")",
":",
"http_error",
"(",
"req",
".",
"status_code",
",",
"req",
".",
"reason",
")",
"# Appel fonction sur erreur HTTP",
"return",
"req",
".",
"status_code"
] | [
259,
0
] | [
271,
26
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
CNN.load | (self) | Récupère un modèle déjà entrainé pour inférer. | Récupère un modèle déjà entrainé pour inférer. | def load(self):
"""Récupère un modèle déjà entrainé pour inférer."""
self.load_state_dict(torch.load('./models/model_' + self.name_model + '_' + str(self.input_window) + '_days_to_' + str(self.output_window) + '_hours.pt')) | [
"def",
"load",
"(",
"self",
")",
":",
"self",
".",
"load_state_dict",
"(",
"torch",
".",
"load",
"(",
"'./models/model_'",
"+",
"self",
".",
"name_model",
"+",
"'_'",
"+",
"str",
"(",
"self",
".",
"input_window",
")",
"+",
"'_days_to_'",
"+",
"str",
"(",
"self",
".",
"output_window",
")",
"+",
"'_hours.pt'",
")",
")"
] | [
79,
4
] | [
81,
162
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Etude_pics | (G,d,mu,t,nbu=100,ndigits=2,nb=50,conv=False,steps=1000,trial=5) | return np.array(Mat) | Fonction donnant le nombres de pics obtenue en simulant nb modele de Deffuant sur le graphe G avec distribution initiale uniforme, pics comptés avec une précision ndigits jusqu'au temps nb pour une valeur de palié et de capacité d'adaptation donné.
Argument :
G : graphe Networkx
d : palié de Deffuant (0<=d<=1)
mu : capacité d'adaptation (0<=mu<=1/2)
t : temps de simulation
nbu : multiplicateur du temps de simulation ( par défaut nbu=100)
ndigits : précision de détection des pics et du test de convergence( par défaut ndigit=2)
nb : nombre de simulation réalisé (par défaut nb=50)
conv: si True ne compte un résulat qu'une fois la convergence atteint ou si la convergence a échoué (par défaut conv=False
steps: nombre d'étapes entre 2 tests de convergence (par défaut =1000)
trial: nombre de test de convergence réaliser au maximum, au bout de trial essais la fonction retroune le résultat même si la convergence n'as pas eux lieu (par défaut trial=5)
Sortie : np.array de taille nb contenant les nb valeurs de nombre de pics obtenue pour chaque simulation | Fonction donnant le nombres de pics obtenue en simulant nb modele de Deffuant sur le graphe G avec distribution initiale uniforme, pics comptés avec une précision ndigits jusqu'au temps nb pour une valeur de palié et de capacité d'adaptation donné. | def Etude_pics(G,d,mu,t,nbu=100,ndigits=2,nb=50,conv=False,steps=1000,trial=5):
'''Fonction donnant le nombres de pics obtenue en simulant nb modele de Deffuant sur le graphe G avec distribution initiale uniforme, pics comptés avec une précision ndigits jusqu'au temps nb pour une valeur de palié et de capacité d'adaptation donné.
Argument :
G : graphe Networkx
d : palié de Deffuant (0<=d<=1)
mu : capacité d'adaptation (0<=mu<=1/2)
t : temps de simulation
nbu : multiplicateur du temps de simulation ( par défaut nbu=100)
ndigits : précision de détection des pics et du test de convergence( par défaut ndigit=2)
nb : nombre de simulation réalisé (par défaut nb=50)
conv: si True ne compte un résulat qu'une fois la convergence atteint ou si la convergence a échoué (par défaut conv=False
steps: nombre d'étapes entre 2 tests de convergence (par défaut =1000)
trial: nombre de test de convergence réaliser au maximum, au bout de trial essais la fonction retroune le résultat même si la convergence n'as pas eux lieu (par défaut trial=5)
Sortie : np.array de taille nb contenant les nb valeurs de nombre de pics obtenue pour chaque simulation'''
Mat=[]
for i in range(nb):
Ma=Simulator(G,d,mu,t,nbu=nbu,conv=conv,steps=steps,trial=trial,ndigits=ndigits)
n=len(Detecte_pic(Ma[-1],ndigits=ndigits))
Mat.append(n)
return np.array(Mat) | [
"def",
"Etude_pics",
"(",
"G",
",",
"d",
",",
"mu",
",",
"t",
",",
"nbu",
"=",
"100",
",",
"ndigits",
"=",
"2",
",",
"nb",
"=",
"50",
",",
"conv",
"=",
"False",
",",
"steps",
"=",
"1000",
",",
"trial",
"=",
"5",
")",
":",
"Mat",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"nb",
")",
":",
"Ma",
"=",
"Simulator",
"(",
"G",
",",
"d",
",",
"mu",
",",
"t",
",",
"nbu",
"=",
"nbu",
",",
"conv",
"=",
"conv",
",",
"steps",
"=",
"steps",
",",
"trial",
"=",
"trial",
",",
"ndigits",
"=",
"ndigits",
")",
"n",
"=",
"len",
"(",
"Detecte_pic",
"(",
"Ma",
"[",
"-",
"1",
"]",
",",
"ndigits",
"=",
"ndigits",
")",
")",
"Mat",
".",
"append",
"(",
"n",
")",
"return",
"np",
".",
"array",
"(",
"Mat",
")"
] | [
131,
0
] | [
154,
24
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Layer.handle_enable_ows_status | (self) | Gérer le statut d'activation de la couche de données SIG. | Gérer le statut d'activation de la couche de données SIG. | def handle_enable_ows_status(self):
"""Gérer le statut d'activation de la couche de données SIG."""
ws_name = self.resource.dataset.organisation.slug
if self.resource.ogc_services:
MRAHandler.enable_layer(ws_name, self.name)
# TODO: Comment on gère les ressources CKAN service ???
else:
MRAHandler.disable_layer(ws_name, self.name) | [
"def",
"handle_enable_ows_status",
"(",
"self",
")",
":",
"ws_name",
"=",
"self",
".",
"resource",
".",
"dataset",
".",
"organisation",
".",
"slug",
"if",
"self",
".",
"resource",
".",
"ogc_services",
":",
"MRAHandler",
".",
"enable_layer",
"(",
"ws_name",
",",
"self",
".",
"name",
")",
"# TODO: Comment on gère les ressources CKAN service ???",
"else",
":",
"MRAHandler",
".",
"disable_layer",
"(",
"ws_name",
",",
"self",
".",
"name",
")"
] | [
450,
4
] | [
457,
56
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Crud.get_ticket | (self) | return self.ctx.get("ticket") | Obtenir le ticket de la base de données lors de la prise | Obtenir le ticket de la base de données lors de la prise | def get_ticket(self):
""" Obtenir le ticket de la base de données lors de la prise """
return self.ctx.get("ticket") | [
"def",
"get_ticket",
"(",
"self",
")",
":",
"return",
"self",
".",
"ctx",
".",
"get",
"(",
"\"ticket\"",
")"
] | [
279,
4
] | [
281,
37
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
init | () | Initialise le simulateur | Initialise le simulateur | def init():
"""Initialise le simulateur"""
# Instanciation de Bullet
physicsClient = p.connect(p.GUI)
p.setGravity(0, 0, -10)
# Chargement du sol
planeId = p.loadURDF(dirname+'/plane.urdf')
p.setPhysicsEngineParameter(fixedTimeStep=dt) | [
"def",
"init",
"(",
")",
":",
"# Instanciation de Bullet",
"physicsClient",
"=",
"p",
".",
"connect",
"(",
"p",
".",
"GUI",
")",
"p",
".",
"setGravity",
"(",
"0",
",",
"0",
",",
"-",
"10",
")",
"# Chargement du sol",
"planeId",
"=",
"p",
".",
"loadURDF",
"(",
"dirname",
"+",
"'/plane.urdf'",
")",
"p",
".",
"setPhysicsEngineParameter",
"(",
"fixedTimeStep",
"=",
"dt",
")"
] | [
15,
0
] | [
24,
49
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
bitset.is_set | (self, pos) | return (self.bits[pos // 8] & (1 << (pos % 8))) != 0 | lit l'état du bit `pos` | lit l'état du bit `pos` | def is_set(self, pos):
""" lit l'état du bit `pos` """
assert pos >= 0 and pos < self.taille
return (self.bits[pos // 8] & (1 << (pos % 8))) != 0 | [
"def",
"is_set",
"(",
"self",
",",
"pos",
")",
":",
"assert",
"pos",
">=",
"0",
"and",
"pos",
"<",
"self",
".",
"taille",
"return",
"(",
"self",
".",
"bits",
"[",
"pos",
"//",
"8",
"]",
"&",
"(",
"1",
"<<",
"(",
"pos",
"%",
"8",
")",
")",
")",
"!=",
"0"
] | [
23,
4
] | [
26,
60
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
integral_optimised | (f, a, b, method_I, epsilon) | return I_2n | Calcul d'intégrale optimisé | Calcul d'intégrale optimisé | def integral_optimised(f, a, b, method_I, epsilon):
"Calcul d'intégrale optimisé"
n = 2
I_n = integral_rect(f, t_0 = a, T = b, n = n, method = method_I)
n *= 2
I_2n = integral_rect(f, t_0 = a, T = b, n = n, method = method_I)
while np.abs (I_2n - I_n) > epsilon:
I_n = I_2n
I_2n = (1./2)*I_n + ((b - a)/(2*n)) * sum(f, a, b, n)
n = 2 * n
return I_2n | [
"def",
"integral_optimised",
"(",
"f",
",",
"a",
",",
"b",
",",
"method_I",
",",
"epsilon",
")",
":",
"n",
"=",
"2",
"I_n",
"=",
"integral_rect",
"(",
"f",
",",
"t_0",
"=",
"a",
",",
"T",
"=",
"b",
",",
"n",
"=",
"n",
",",
"method",
"=",
"method_I",
")",
"n",
"*=",
"2",
"I_2n",
"=",
"integral_rect",
"(",
"f",
",",
"t_0",
"=",
"a",
",",
"T",
"=",
"b",
",",
"n",
"=",
"n",
",",
"method",
"=",
"method_I",
")",
"while",
"np",
".",
"abs",
"(",
"I_2n",
"-",
"I_n",
")",
">",
"epsilon",
":",
"I_n",
"=",
"I_2n",
"I_2n",
"=",
"(",
"1.",
"/",
"2",
")",
"*",
"I_n",
"+",
"(",
"(",
"b",
"-",
"a",
")",
"/",
"(",
"2",
"*",
"n",
")",
")",
"*",
"sum",
"(",
"f",
",",
"a",
",",
"b",
",",
"n",
")",
"n",
"=",
"2",
"*",
"n",
"return",
"I_2n"
] | [
83,
0
] | [
93,
12
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
SegmentBord.calcul_vecteur_fin | (self) | propose une seconde extrémité connaissant la première,
beaucoup plus loin en conservant la meme orientation,
du moment qu'on traverse l'image | propose une seconde extrémité connaissant la première,
beaucoup plus loin en conservant la meme orientation,
du moment qu'on traverse l'image | def calcul_vecteur_fin(self):
"""propose une seconde extrémité connaissant la première,
beaucoup plus loin en conservant la meme orientation,
du moment qu'on traverse l'image"""
t = self.dim.x + self.dim.y
self.b.x = int(self.a.x + self.vecteur.x * t)
self.b.y = int(self.a.y + self.vecteur.y * t) | [
"def",
"calcul_vecteur_fin",
"(",
"self",
")",
":",
"t",
"=",
"self",
".",
"dim",
".",
"x",
"+",
"self",
".",
"dim",
".",
"y",
"self",
".",
"b",
".",
"x",
"=",
"int",
"(",
"self",
".",
"a",
".",
"x",
"+",
"self",
".",
"vecteur",
".",
"x",
"*",
"t",
")",
"self",
".",
"b",
".",
"y",
"=",
"int",
"(",
"self",
".",
"a",
".",
"y",
"+",
"self",
".",
"vecteur",
".",
"y",
"*",
"t",
")"
] | [
152,
4
] | [
158,
53
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
FenetrePrincipale.debug | (self) | Gère le sous-menu de débug | Gère le sous-menu de débug | def debug(self):
"""Gère le sous-menu de débug"""
self.DEBUG = not self.DEBUG | [
"def",
"debug",
"(",
"self",
")",
":",
"self",
".",
"DEBUG",
"=",
"not",
"self",
".",
"DEBUG"
] | [
80,
1
] | [
82,
29
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
setJoints | (robot, joints) | Définis les angles cibles pour les moteurs du robot
Arguments:
int -- identifiant du robot
joints {list} -- liste des positions cibles (rad)
| Définis les angles cibles pour les moteurs du robot | def setJoints(robot, joints):
"""Définis les angles cibles pour les moteurs du robot
Arguments:
int -- identifiant du robot
joints {list} -- liste des positions cibles (rad)
"""
jointsMap = [0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14]
for k in range(len(joints)):
jointInfo = p.getJointInfo(robot, jointsMap[k])
p.setJointMotorControl2(
robot, jointInfo[0], p.POSITION_CONTROL, joints[k]) | [
"def",
"setJoints",
"(",
"robot",
",",
"joints",
")",
":",
"jointsMap",
"=",
"[",
"0",
",",
"1",
",",
"2",
",",
"4",
",",
"5",
",",
"6",
",",
"8",
",",
"9",
",",
"10",
",",
"12",
",",
"13",
",",
"14",
"]",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"joints",
")",
")",
":",
"jointInfo",
"=",
"p",
".",
"getJointInfo",
"(",
"robot",
",",
"jointsMap",
"[",
"k",
"]",
")",
"p",
".",
"setJointMotorControl2",
"(",
"robot",
",",
"jointInfo",
"[",
"0",
"]",
",",
"p",
".",
"POSITION_CONTROL",
",",
"joints",
"[",
"k",
"]",
")"
] | [
36,
0
] | [
47,
63
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
corde.__init__ | (self, nb, p1, p2, m, k, g, f, l) | initialisation d'une corde
@param nb nombre de points
@param p1 = x1,y1 coordoonn�es du premier point (fixe)
@param p2 = x2,y2 coordoonn�es du dernier point (fixe)
@param m masse de la corde,
r�partie entre tous les pointstous les points
@param k raideur de l'�lastique
@param g intensit� de l'apesanteur,
valeur positive
@param f vitesse de freinage
@param l longueur de la corde | initialisation d'une corde
| def __init__(self, nb, p1, p2, m, k, g, f, l) :
"""initialisation d'une corde
@param nb nombre de points
@param p1 = x1,y1 coordoonn�es du premier point (fixe)
@param p2 = x2,y2 coordoonn�es du dernier point (fixe)
@param m masse de la corde,
r�partie entre tous les pointstous les points
@param k raideur de l'�lastique
@param g intensit� de l'apesanteur,
valeur positive
@param f vitesse de freinage
@param l longueur de la corde"""
x1,y1 = p1[0], p1[1]
x2,y2 = p2[0], p2[1]
self.list = []
self.vitesse = []
for i in range (0,nb) :
x = x1 + float (i) * (x2 - x1) / float (nb - 1)
y = y1 + float (i) * (y2 - y1) / float (nb - 1)
self.list.append ( point (x,y, float (m) / nb))
self.vitesse.append (point (0,0,0))
self.k = k * nb
self.g = g
self.l = float (l) / (nb-1)
self.f = f | [
"def",
"__init__",
"(",
"self",
",",
"nb",
",",
"p1",
",",
"p2",
",",
"m",
",",
"k",
",",
"g",
",",
"f",
",",
"l",
")",
":",
"x1",
",",
"y1",
"=",
"p1",
"[",
"0",
"]",
",",
"p1",
"[",
"1",
"]",
"x2",
",",
"y2",
"=",
"p2",
"[",
"0",
"]",
",",
"p2",
"[",
"1",
"]",
"self",
".",
"list",
"=",
"[",
"]",
"self",
".",
"vitesse",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"nb",
")",
":",
"x",
"=",
"x1",
"+",
"float",
"(",
"i",
")",
"*",
"(",
"x2",
"-",
"x1",
")",
"/",
"float",
"(",
"nb",
"-",
"1",
")",
"y",
"=",
"y1",
"+",
"float",
"(",
"i",
")",
"*",
"(",
"y2",
"-",
"y1",
")",
"/",
"float",
"(",
"nb",
"-",
"1",
")",
"self",
".",
"list",
".",
"append",
"(",
"point",
"(",
"x",
",",
"y",
",",
"float",
"(",
"m",
")",
"/",
"nb",
")",
")",
"self",
".",
"vitesse",
".",
"append",
"(",
"point",
"(",
"0",
",",
"0",
",",
"0",
")",
")",
"self",
".",
"k",
"=",
"k",
"*",
"nb",
"self",
".",
"g",
"=",
"g",
"self",
".",
"l",
"=",
"float",
"(",
"l",
")",
"/",
"(",
"nb",
"-",
"1",
")",
"self",
".",
"f",
"=",
"f"
] | [
36,
4
] | [
60,
18
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Board.getPieceAtIndex | (self, index) | return self.shapes[index] | Renvoie une piece a l'index index | Renvoie une piece a l'index index | def getPieceAtIndex(self, index):
"""Renvoie une piece a l'index index"""
return self.shapes[index] | [
"def",
"getPieceAtIndex",
"(",
"self",
",",
"index",
")",
":",
"return",
"self",
".",
"shapes",
"[",
"index",
"]"
] | [
118,
1
] | [
120,
27
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
SegmentBord.premier | (self) | définit le premier segment, horizontal, part du bord gauche | définit le premier segment, horizontal, part du bord gauche | def premier(self):
"""définit le premier segment, horizontal, part du bord gauche"""
self.angle = 0
self.fin = Point(0, 0)
self.calcul_vecteur() | [
"def",
"premier",
"(",
"self",
")",
":",
"self",
".",
"angle",
"=",
"0",
"self",
".",
"fin",
"=",
"Point",
"(",
"0",
",",
"0",
")",
"self",
".",
"calcul_vecteur",
"(",
")"
] | [
54,
4
] | [
58,
29
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
f_credit | (masterx,mastery) | attributions : option "Prise En Main" du sous menu "Outils" (l.afpt)
description : ouvre la page des crédits (dans l'application)
paramètres : - masterx => largeur de la fenêtre au moment de l'appelle de la fonction
- mastery => hauteur de la fenêtre au moment de l'appelle de la fonction | attributions : option "Prise En Main" du sous menu "Outils" (l.afpt)
description : ouvre la page des crédits (dans l'application)
paramètres : - masterx => largeur de la fenêtre au moment de l'appelle de la fonction
- mastery => hauteur de la fenêtre au moment de l'appelle de la fonction | def f_credit(masterx,mastery):
"""attributions : option "Prise En Main" du sous menu "Outils" (l.afpt)
description : ouvre la page des crédits (dans l'application)
paramètres : - masterx => largeur de la fenêtre au moment de l'appelle de la fonction
- mastery => hauteur de la fenêtre au moment de l'appelle de la fonction"""
credit_master = tk.Tk()
credit_master.title('Prise en main')
credit_master.geometry(f'{masterx-30}x{mastery-30}') # on ajuste la taille de la fenêtre en fonction de la taille de la fenêtre récupérée en paramètre
credit_master.geometry("+40+60")
credit_master.config(bg='#022c43')
credit_master.mainloop() | [
"def",
"f_credit",
"(",
"masterx",
",",
"mastery",
")",
":",
"credit_master",
"=",
"tk",
".",
"Tk",
"(",
")",
"credit_master",
".",
"title",
"(",
"'Prise en main'",
")",
"credit_master",
".",
"geometry",
"(",
"f'{masterx-30}x{mastery-30}'",
")",
"# on ajuste la taille de la fenêtre en fonction de la taille de la fenêtre récupérée en paramètre",
"credit_master",
".",
"geometry",
"(",
"\"+40+60\"",
")",
"credit_master",
".",
"config",
"(",
"bg",
"=",
"'#022c43'",
")",
"credit_master",
".",
"mainloop",
"(",
")"
] | [
297,
0
] | [
307,
28
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
__init__ | (self, decalage) | Constructeur, fournir le décalage souhaité | Constructeur, fournir le décalage souhaité | def __init__(self, decalage):
'''Constructeur, fournir le décalage souhaité'''
self.decalage = decalage % 26 | [
"def",
"__init__",
"(",
"self",
",",
"decalage",
")",
":",
"self",
".",
"decalage",
"=",
"decalage",
"%",
"26"
] | [
5,
4
] | [
7,
37
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
enregistre_operation | (op, valeur1) | return valeur1, "0", op | Mémorise l'opération en vu d'un futur clic sur le bouton '='. | Mémorise l'opération en vu d'un futur clic sur le bouton '='. | def enregistre_operation(op, valeur1):
"""Mémorise l'opération en vu d'un futur clic sur le bouton '='."""
return valeur1, "0", op | [
"def",
"enregistre_operation",
"(",
"op",
",",
"valeur1",
")",
":",
"return",
"valeur1",
",",
"\"0\"",
",",
"op"
] | [
90,
0
] | [
92,
27
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Admin.main_idea | (self, ctx: MyContext) | Ajouter une idée dans le salon des idées, en français et anglais | Ajouter une idée dans le salon des idées, en français et anglais | async def main_idea(self, ctx: MyContext):
"""Ajouter une idée dans le salon des idées, en français et anglais"""
pass | [
"async",
"def",
"main_idea",
"(",
"self",
",",
"ctx",
":",
"MyContext",
")",
":",
"pass"
] | [
896,
4
] | [
898,
12
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Crud.get_element_param | (self, element, params, default=None) | Obtenir la valeur d'un paramètre d'un élément | Obtenir la valeur d'un paramètre d'un élément | def get_element_param(self, element, params, default=None):
""" Obtenir la valeur d'un paramètre d'un élément """
if self.application["tables"][self.ctx["table_id"]]["elements"][element].get("params", None):
return self.application["tables"][self.ctx["table_id"]]["elements"][element].get("params").get(params, default)
else:
return default | [
"def",
"get_element_param",
"(",
"self",
",",
"element",
",",
"params",
",",
"default",
"=",
"None",
")",
":",
"if",
"self",
".",
"application",
"[",
"\"tables\"",
"]",
"[",
"self",
".",
"ctx",
"[",
"\"table_id\"",
"]",
"]",
"[",
"\"elements\"",
"]",
"[",
"element",
"]",
".",
"get",
"(",
"\"params\"",
",",
"None",
")",
":",
"return",
"self",
".",
"application",
"[",
"\"tables\"",
"]",
"[",
"self",
".",
"ctx",
"[",
"\"table_id\"",
"]",
"]",
"[",
"\"elements\"",
"]",
"[",
"element",
"]",
".",
"get",
"(",
"\"params\"",
")",
".",
"get",
"(",
"params",
",",
"default",
")",
"else",
":",
"return",
"default"
] | [
538,
4
] | [
543,
26
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
etude | (n) | Détermine les automorphismes de Z/nZ. | Détermine les automorphismes de Z/nZ. | def etude(n):
'''Détermine les automorphismes de Z/nZ.'''
print(f'n = {n}\nordres = {ordres(n)}\n')
Bl, Bf = quasi_isomorphismes(n)
for bl, bf in zip(Bl,Bf):
print(list(map(bf, range(n))))
if not est_morphisme(bf, n):
print('n\'est pas un isomorphisme.\n')
else:
print('est un isomorphisme.\n') | [
"def",
"etude",
"(",
"n",
")",
":",
"print",
"(",
"f'n = {n}\\nordres = {ordres(n)}\\n'",
")",
"Bl",
",",
"Bf",
"=",
"quasi_isomorphismes",
"(",
"n",
")",
"for",
"bl",
",",
"bf",
"in",
"zip",
"(",
"Bl",
",",
"Bf",
")",
":",
"print",
"(",
"list",
"(",
"map",
"(",
"bf",
",",
"range",
"(",
"n",
")",
")",
")",
")",
"if",
"not",
"est_morphisme",
"(",
"bf",
",",
"n",
")",
":",
"print",
"(",
"'n\\'est pas un isomorphisme.\\n'",
")",
"else",
":",
"print",
"(",
"'est un isomorphisme.\\n'",
")"
] | [
7,
0
] | [
16,
43
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
ig.closeOrders | (self, dealId, orderType, *args) | SEUL un Deal ID devrait etre passé, avec MARKET type | SEUL un Deal ID devrait etre passé, avec MARKET type | def closeOrders(self, dealId, orderType, *args):
"""SEUL un Deal ID devrait etre passé, avec MARKET type"""
if orderType == "MARKET":
level = None
url = [self.serverAddr, "/positions/otc"]
url0 = self.serverAddr + "/positions/" + dealId
h0 = {
'IG-ACCOUNT-ID': Var.data.get('accountId'),
'Authorization': Var.data.get('oauthToken').get('token_type') + " " + Var.data.get('oauthToken').get('access_token'),
'Version': '1',
'X-IG-API-KEY': Id.apiKey,
}
h1 = {
'IG-ACCOUNT-ID': Var.data.get('accountId'),
'Authorization': Var.data.get('oauthToken').get('token_type') + " " + Var.data.get('oauthToken').get('access_token'),
'Version': '1',
'X-IG-API-KEY': Id.apiKey,
'_method': "DELETE"
}
# Verifie et ajuste le sens et la taille par rapport a l'initiale
r0 = requests.get(url0, headers=h0)
raw0 = r0.json()
print(raw0)
if (raw0.get("position").get("direction")) == "BUY":
CloseDir = "SELL"
else:
CloseDir = "BUY"
initialSize = raw0.get("position").get("dealSize")
initialeLevel = raw0.get("position").get("openLevel")
if float(initialSize) == int(initialSize):
initialSize = int(initialSize)
payloads = {
"dealId": dealId,
"epic": None,
"expiry": None,
"direction": CloseDir,
"size": str(initialSize),
"level": level,
"orderType": orderType,
"timeInForce": None,
"quoteId": None
}
print(json.dumps(payloads))
r = requests.post(str("").join(url), headers=h1,
data=json.dumps(payloads))
if r.status_code == 200:
dealref = r.json().get("dealReference")
url1 = self.serverAddr + "/confirms/" + dealref
r1 = requests.get(url1, headers=h0)
raw1 = r1.json()
if raw1.get("dealStatus") == "ACCEPTED":
# print(raw1)
Var.cleanedDeal["CloseTime"].append(raw1.get("date"))
Var.cleanedDeal["OpenTime"].append(raw1.get("dealId"))
Var.cleanedDeal["closelevel"].append(raw1.get("level"))
Var.cleanedDeal["profit"].append(raw1.get("profit"))
Var.cleanedDeal["entrylevel"].append(initialeLevel)
elif (raw1.get("dealStatus")) == "REJECTED":
print("Rejected")
else:
print("Erreur: ")
print(r1.status_code)
Var.PnL = + (round(float(raw1.get("profit")), 2))
else:
print("erreur:", r.status_code)
print(r.json()) | [
"def",
"closeOrders",
"(",
"self",
",",
"dealId",
",",
"orderType",
",",
"*",
"args",
")",
":",
"if",
"orderType",
"==",
"\"MARKET\"",
":",
"level",
"=",
"None",
"url",
"=",
"[",
"self",
".",
"serverAddr",
",",
"\"/positions/otc\"",
"]",
"url0",
"=",
"self",
".",
"serverAddr",
"+",
"\"/positions/\"",
"+",
"dealId",
"h0",
"=",
"{",
"'IG-ACCOUNT-ID'",
":",
"Var",
".",
"data",
".",
"get",
"(",
"'accountId'",
")",
",",
"'Authorization'",
":",
"Var",
".",
"data",
".",
"get",
"(",
"'oauthToken'",
")",
".",
"get",
"(",
"'token_type'",
")",
"+",
"\" \"",
"+",
"Var",
".",
"data",
".",
"get",
"(",
"'oauthToken'",
")",
".",
"get",
"(",
"'access_token'",
")",
",",
"'Version'",
":",
"'1'",
",",
"'X-IG-API-KEY'",
":",
"Id",
".",
"apiKey",
",",
"}",
"h1",
"=",
"{",
"'IG-ACCOUNT-ID'",
":",
"Var",
".",
"data",
".",
"get",
"(",
"'accountId'",
")",
",",
"'Authorization'",
":",
"Var",
".",
"data",
".",
"get",
"(",
"'oauthToken'",
")",
".",
"get",
"(",
"'token_type'",
")",
"+",
"\" \"",
"+",
"Var",
".",
"data",
".",
"get",
"(",
"'oauthToken'",
")",
".",
"get",
"(",
"'access_token'",
")",
",",
"'Version'",
":",
"'1'",
",",
"'X-IG-API-KEY'",
":",
"Id",
".",
"apiKey",
",",
"'_method'",
":",
"\"DELETE\"",
"}",
"# Verifie et ajuste le sens et la taille par rapport a l'initiale",
"r0",
"=",
"requests",
".",
"get",
"(",
"url0",
",",
"headers",
"=",
"h0",
")",
"raw0",
"=",
"r0",
".",
"json",
"(",
")",
"print",
"(",
"raw0",
")",
"if",
"(",
"raw0",
".",
"get",
"(",
"\"position\"",
")",
".",
"get",
"(",
"\"direction\"",
")",
")",
"==",
"\"BUY\"",
":",
"CloseDir",
"=",
"\"SELL\"",
"else",
":",
"CloseDir",
"=",
"\"BUY\"",
"initialSize",
"=",
"raw0",
".",
"get",
"(",
"\"position\"",
")",
".",
"get",
"(",
"\"dealSize\"",
")",
"initialeLevel",
"=",
"raw0",
".",
"get",
"(",
"\"position\"",
")",
".",
"get",
"(",
"\"openLevel\"",
")",
"if",
"float",
"(",
"initialSize",
")",
"==",
"int",
"(",
"initialSize",
")",
":",
"initialSize",
"=",
"int",
"(",
"initialSize",
")",
"payloads",
"=",
"{",
"\"dealId\"",
":",
"dealId",
",",
"\"epic\"",
":",
"None",
",",
"\"expiry\"",
":",
"None",
",",
"\"direction\"",
":",
"CloseDir",
",",
"\"size\"",
":",
"str",
"(",
"initialSize",
")",
",",
"\"level\"",
":",
"level",
",",
"\"orderType\"",
":",
"orderType",
",",
"\"timeInForce\"",
":",
"None",
",",
"\"quoteId\"",
":",
"None",
"}",
"print",
"(",
"json",
".",
"dumps",
"(",
"payloads",
")",
")",
"r",
"=",
"requests",
".",
"post",
"(",
"str",
"(",
"\"\"",
")",
".",
"join",
"(",
"url",
")",
",",
"headers",
"=",
"h1",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"payloads",
")",
")",
"if",
"r",
".",
"status_code",
"==",
"200",
":",
"dealref",
"=",
"r",
".",
"json",
"(",
")",
".",
"get",
"(",
"\"dealReference\"",
")",
"url1",
"=",
"self",
".",
"serverAddr",
"+",
"\"/confirms/\"",
"+",
"dealref",
"r1",
"=",
"requests",
".",
"get",
"(",
"url1",
",",
"headers",
"=",
"h0",
")",
"raw1",
"=",
"r1",
".",
"json",
"(",
")",
"if",
"raw1",
".",
"get",
"(",
"\"dealStatus\"",
")",
"==",
"\"ACCEPTED\"",
":",
"# print(raw1)",
"Var",
".",
"cleanedDeal",
"[",
"\"CloseTime\"",
"]",
".",
"append",
"(",
"raw1",
".",
"get",
"(",
"\"date\"",
")",
")",
"Var",
".",
"cleanedDeal",
"[",
"\"OpenTime\"",
"]",
".",
"append",
"(",
"raw1",
".",
"get",
"(",
"\"dealId\"",
")",
")",
"Var",
".",
"cleanedDeal",
"[",
"\"closelevel\"",
"]",
".",
"append",
"(",
"raw1",
".",
"get",
"(",
"\"level\"",
")",
")",
"Var",
".",
"cleanedDeal",
"[",
"\"profit\"",
"]",
".",
"append",
"(",
"raw1",
".",
"get",
"(",
"\"profit\"",
")",
")",
"Var",
".",
"cleanedDeal",
"[",
"\"entrylevel\"",
"]",
".",
"append",
"(",
"initialeLevel",
")",
"elif",
"(",
"raw1",
".",
"get",
"(",
"\"dealStatus\"",
")",
")",
"==",
"\"REJECTED\"",
":",
"print",
"(",
"\"Rejected\"",
")",
"else",
":",
"print",
"(",
"\"Erreur: \"",
")",
"print",
"(",
"r1",
".",
"status_code",
")",
"Var",
".",
"PnL",
"=",
"+",
"(",
"round",
"(",
"float",
"(",
"raw1",
".",
"get",
"(",
"\"profit\"",
")",
")",
",",
"2",
")",
")",
"else",
":",
"print",
"(",
"\"erreur:\"",
",",
"r",
".",
"status_code",
")",
"print",
"(",
"r",
".",
"json",
"(",
")",
")"
] | [
352,
4
] | [
429,
27
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
resultatAppel | () | Controleur de la route '/resultatAppel' | Controleur de la route '/resultatAppel' | def resultatAppel():
"Controleur de la route '/resultatAppel' "
def requeteListeAppelClasse(conn, cur, result):
values = (session['user']['idSuperieur'],) + tuple([champ for champ in result])
if len(values) == 2:
values = values + (values[1],)
requete = """
SELECT statut, eleve.nom AS nomCandidat, eleve.prenom AS prenomCandidat, lycee.nom AS nomLycee, (note1 * coefNote1 + note2 * coefNote2)/(coefNote1 + coefNote2) AS moyenne
FROM ((superieur JOIN candidature USING(idSuperieur)) JOIN eleve USING(idEleve)) JOIN lycee USING(idLycee)
WHERE idSuperieur = ? AND statut IN (?, ?)
ORDER BY moyenne DESC ;
"""
cur.execute(requete, values)
return cur.fetchall()
#analyse du formulaire
if request.method == 'POST':
#ouverture du formulaire
result = request.form
#ouverture de la BDD
conn = sqlite3.connect('monavenir.db')
conn.row_factory = sqlite3.Row #pour récupérer les lignes sous forme de dictionnaire
cur = conn.cursor()
#requete
liste_appel = requeteListeAppelClasse(conn, cur, result)
#fermeture de la BDD
cur.close()
conn.close()
return render_template("resultatAppel.html", liste_appel = liste_appel) | [
"def",
"resultatAppel",
"(",
")",
":",
"def",
"requeteListeAppelClasse",
"(",
"conn",
",",
"cur",
",",
"result",
")",
":",
"values",
"=",
"(",
"session",
"[",
"'user'",
"]",
"[",
"'idSuperieur'",
"]",
",",
")",
"+",
"tuple",
"(",
"[",
"champ",
"for",
"champ",
"in",
"result",
"]",
")",
"if",
"len",
"(",
"values",
")",
"==",
"2",
":",
"values",
"=",
"values",
"+",
"(",
"values",
"[",
"1",
"]",
",",
")",
"requete",
"=",
"\"\"\"\r\n SELECT statut, eleve.nom AS nomCandidat, eleve.prenom AS prenomCandidat, lycee.nom AS nomLycee, (note1 * coefNote1 + note2 * coefNote2)/(coefNote1 + coefNote2) AS moyenne\r\n FROM ((superieur JOIN candidature USING(idSuperieur)) JOIN eleve USING(idEleve)) JOIN lycee USING(idLycee)\r\n WHERE idSuperieur = ? AND statut IN (?, ?)\r\n ORDER BY moyenne DESC ;\r\n \"\"\"",
"cur",
".",
"execute",
"(",
"requete",
",",
"values",
")",
"return",
"cur",
".",
"fetchall",
"(",
")",
"#analyse du formulaire \r",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"#ouverture du formulaire \r",
"result",
"=",
"request",
".",
"form",
"#ouverture de la BDD\r",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"'monavenir.db'",
")",
"conn",
".",
"row_factory",
"=",
"sqlite3",
".",
"Row",
"#pour récupérer les lignes sous forme de dictionnaire \r",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"#requete \r",
"liste_appel",
"=",
"requeteListeAppelClasse",
"(",
"conn",
",",
"cur",
",",
"result",
")",
"#fermeture de la BDD\r",
"cur",
".",
"close",
"(",
")",
"conn",
".",
"close",
"(",
")",
"return",
"render_template",
"(",
"\"resultatAppel.html\"",
",",
"liste_appel",
"=",
"liste_appel",
")"
] | [
637,
0
] | [
666,
79
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Control.flip_state | (self) | Gestion de self.state qui est aussi une autre classe | Gestion de self.state qui est aussi une autre classe | def flip_state(self):
"""Gestion de self.state qui est aussi une autre classe"""
previous, self.state_name = self.state_name, self.state.next
persist = self.state.cleanup()
self.state = self.state_dict[self.state_name]
self.state.startup(self.current_time, persist)
self.state.previous = previous | [
"def",
"flip_state",
"(",
"self",
")",
":",
"previous",
",",
"self",
".",
"state_name",
"=",
"self",
".",
"state_name",
",",
"self",
".",
"state",
".",
"next",
"persist",
"=",
"self",
".",
"state",
".",
"cleanup",
"(",
")",
"self",
".",
"state",
"=",
"self",
".",
"state_dict",
"[",
"self",
".",
"state_name",
"]",
"self",
".",
"state",
".",
"startup",
"(",
"self",
".",
"current_time",
",",
"persist",
")",
"self",
".",
"state",
".",
"previous",
"=",
"previous"
] | [
44,
4
] | [
50,
38
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
quasi_isomorphismes | (n, plat = True) | Retourne les bijections [[0, n-1]] préservant l'ordre dans Z/nZ. | Retourne les bijections [[0, n-1]] préservant l'ordre dans Z/nZ. | def quasi_isomorphismes(n, plat = True):
'''Retourne les bijections [[0, n-1]] préservant l'ordre dans Z/nZ.'''
E = range(n)
ordre_n = lambda k: ordre(k, n)
# partitionner [[1, n]] par ordre
partition = [[k for k in E if ordre_n(k) == o] for o in ordres(n)]
# obtenir les permutés de chaque classe
permutes_par_classe = [itertools.permutations(partition[i]) for i in range(len(partition))]
# produit cartésien des permutés
produit = itertools.product(*permutes_par_classe)
# aplatir
if plat:
B = [list(itertools.chain.from_iterable(b)) for b in produit]
def faire_fonction(b):
'''convertit liste en bijection'''
return lambda i: b[B[0].index(i)]
return B, map(faire_fonction, B)
else:
return produit | [
"def",
"quasi_isomorphismes",
"(",
"n",
",",
"plat",
"=",
"True",
")",
":",
"E",
"=",
"range",
"(",
"n",
")",
"ordre_n",
"=",
"lambda",
"k",
":",
"ordre",
"(",
"k",
",",
"n",
")",
"# partitionner [[1, n]] par ordre",
"partition",
"=",
"[",
"[",
"k",
"for",
"k",
"in",
"E",
"if",
"ordre_n",
"(",
"k",
")",
"==",
"o",
"]",
"for",
"o",
"in",
"ordres",
"(",
"n",
")",
"]",
"# obtenir les permutés de chaque classe",
"permutes_par_classe",
"=",
"[",
"itertools",
".",
"permutations",
"(",
"partition",
"[",
"i",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"partition",
")",
")",
"]",
"# produit cartésien des permutés",
"produit",
"=",
"itertools",
".",
"product",
"(",
"*",
"permutes_par_classe",
")",
"# aplatir",
"if",
"plat",
":",
"B",
"=",
"[",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"b",
")",
")",
"for",
"b",
"in",
"produit",
"]",
"def",
"faire_fonction",
"(",
"b",
")",
":",
"'''convertit liste en bijection'''",
"return",
"lambda",
"i",
":",
"b",
"[",
"B",
"[",
"0",
"]",
".",
"index",
"(",
"i",
")",
"]",
"return",
"B",
",",
"map",
"(",
"faire_fonction",
",",
"B",
")",
"else",
":",
"return",
"produit"
] | [
19,
0
] | [
37,
22
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Crud.sql_insert_record | (self, elements) | Création de l'enregistrement du formulaire courant | Création de l'enregistrement du formulaire courant | def sql_insert_record(self, elements):
""" Création de l'enregistrement du formulaire courant """
sql = "INSERT INTO " + self.get_table_id() + " ("
params = {}
b_first = True
for element in elements:
if self.get_field_prop(element, "type") == "counter":
continue
crudel = elements[element].get("crudel")
if crudel.is_read_only():
continue
if crudel.is_virtual():
continue
if b_first:
b_first = False
else:
sql += ", "
sql += element
params[element] = crudel.get_value()
sql += ") VALUES ("
b_first = True
for element in elements:
if self.get_field_prop(element, "type") == "counter":
continue
crudel = elements[element].get("crudel")
if crudel.is_read_only():
continue
if crudel.is_virtual():
continue
if b_first:
b_first = False
else:
sql += ", "
sql += ":" + element
sql += ")"
# on remplace les {rubrique} par leur valeur
sql = self.replace_from_dict(sql, params)
# print sql, params
self.exec_sql(self.get_basename(), sql, params)
# post_sql
if self.get_form_prop("sql_post", "") != "":
sql = self.replace_from_dict(self.get_form_prop("sql_post"), params)
self.exec_sql(self.get_basename(), sql, params) | [
"def",
"sql_insert_record",
"(",
"self",
",",
"elements",
")",
":",
"sql",
"=",
"\"INSERT INTO \"",
"+",
"self",
".",
"get_table_id",
"(",
")",
"+",
"\" (\"",
"params",
"=",
"{",
"}",
"b_first",
"=",
"True",
"for",
"element",
"in",
"elements",
":",
"if",
"self",
".",
"get_field_prop",
"(",
"element",
",",
"\"type\"",
")",
"==",
"\"counter\"",
":",
"continue",
"crudel",
"=",
"elements",
"[",
"element",
"]",
".",
"get",
"(",
"\"crudel\"",
")",
"if",
"crudel",
".",
"is_read_only",
"(",
")",
":",
"continue",
"if",
"crudel",
".",
"is_virtual",
"(",
")",
":",
"continue",
"if",
"b_first",
":",
"b_first",
"=",
"False",
"else",
":",
"sql",
"+=",
"\", \"",
"sql",
"+=",
"element",
"params",
"[",
"element",
"]",
"=",
"crudel",
".",
"get_value",
"(",
")",
"sql",
"+=",
"\") VALUES (\"",
"b_first",
"=",
"True",
"for",
"element",
"in",
"elements",
":",
"if",
"self",
".",
"get_field_prop",
"(",
"element",
",",
"\"type\"",
")",
"==",
"\"counter\"",
":",
"continue",
"crudel",
"=",
"elements",
"[",
"element",
"]",
".",
"get",
"(",
"\"crudel\"",
")",
"if",
"crudel",
".",
"is_read_only",
"(",
")",
":",
"continue",
"if",
"crudel",
".",
"is_virtual",
"(",
")",
":",
"continue",
"if",
"b_first",
":",
"b_first",
"=",
"False",
"else",
":",
"sql",
"+=",
"\", \"",
"sql",
"+=",
"\":\"",
"+",
"element",
"sql",
"+=",
"\")\"",
"# on remplace les {rubrique} par leur valeur",
"sql",
"=",
"self",
".",
"replace_from_dict",
"(",
"sql",
",",
"params",
")",
"# print sql, params",
"self",
".",
"exec_sql",
"(",
"self",
".",
"get_basename",
"(",
")",
",",
"sql",
",",
"params",
")",
"# post_sql",
"if",
"self",
".",
"get_form_prop",
"(",
"\"sql_post\"",
",",
"\"\"",
")",
"!=",
"\"\"",
":",
"sql",
"=",
"self",
".",
"replace_from_dict",
"(",
"self",
".",
"get_form_prop",
"(",
"\"sql_post\"",
")",
",",
"params",
")",
"self",
".",
"exec_sql",
"(",
"self",
".",
"get_basename",
"(",
")",
",",
"sql",
",",
"params",
")"
] | [
638,
4
] | [
680,
59
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Xp.add_xp | (self, msg: discord.Message) | Attribue un certain nombre d'xp à un message | Attribue un certain nombre d'xp à un message | async def add_xp(self, msg: discord.Message):
"""Attribue un certain nombre d'xp à un message"""
if msg.author.bot or msg.guild is None or not self.bot.xp_enabled:
return
used_xp_type = await self.bot.get_config(msg.guild.id,'xp_type')
if not ( await self.check_noxp(msg) and await self.bot.get_config(msg.guild.id,'enable_xp') ):
return
rate = await self.bot.get_config(msg.guild.id,'xp_rate')
if self.sus is None:
if self.bot.get_cog('Utilities'):
await self.reload_sus()
else:
self.sus = set()
if self.bot.zombie_mode:
return
if used_xp_type == 0:
await self.add_xp_0(msg,rate)
elif used_xp_type==1:
await self.add_xp_1(msg,rate)
elif used_xp_type==2:
await self.add_xp_2(msg,rate) | [
"async",
"def",
"add_xp",
"(",
"self",
",",
"msg",
":",
"discord",
".",
"Message",
")",
":",
"if",
"msg",
".",
"author",
".",
"bot",
"or",
"msg",
".",
"guild",
"is",
"None",
"or",
"not",
"self",
".",
"bot",
".",
"xp_enabled",
":",
"return",
"used_xp_type",
"=",
"await",
"self",
".",
"bot",
".",
"get_config",
"(",
"msg",
".",
"guild",
".",
"id",
",",
"'xp_type'",
")",
"if",
"not",
"(",
"await",
"self",
".",
"check_noxp",
"(",
"msg",
")",
"and",
"await",
"self",
".",
"bot",
".",
"get_config",
"(",
"msg",
".",
"guild",
".",
"id",
",",
"'enable_xp'",
")",
")",
":",
"return",
"rate",
"=",
"await",
"self",
".",
"bot",
".",
"get_config",
"(",
"msg",
".",
"guild",
".",
"id",
",",
"'xp_rate'",
")",
"if",
"self",
".",
"sus",
"is",
"None",
":",
"if",
"self",
".",
"bot",
".",
"get_cog",
"(",
"'Utilities'",
")",
":",
"await",
"self",
".",
"reload_sus",
"(",
")",
"else",
":",
"self",
".",
"sus",
"=",
"set",
"(",
")",
"if",
"self",
".",
"bot",
".",
"zombie_mode",
":",
"return",
"if",
"used_xp_type",
"==",
"0",
":",
"await",
"self",
".",
"add_xp_0",
"(",
"msg",
",",
"rate",
")",
"elif",
"used_xp_type",
"==",
"1",
":",
"await",
"self",
".",
"add_xp_1",
"(",
"msg",
",",
"rate",
")",
"elif",
"used_xp_type",
"==",
"2",
":",
"await",
"self",
".",
"add_xp_2",
"(",
"msg",
",",
"rate",
")"
] | [
77,
4
] | [
97,
41
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
dechiffre | (n, d, *crypt) | return asci | `*crypt` est une liste des blocks à déchiffrer | `*crypt` est une liste des blocks à déchiffrer | def dechiffre(n, d, *crypt):
""" `*crypt` est une liste des blocks à déchiffrer"""
#dechiffrage des blocs
resultat = [str((int(i)**d)%n) for i in crypt]
#on rajoute les 0 en debut de blocs pour refaire des blocs de 4
for i, s in enumerate(resultat):
if len(s) < 4:
while len(s) < 4:
s = '0' + s
resultat[i] = s
#on refait des groupes de 3 et on les convertie directement en ascii
g = ''.join(resultat)
asci = ''
d , f = 0 , 3
while f < len(g):
asci = asci + chr(int(g[d:f])) #conversion ascii
d , f = f , f + 3
return asci | [
"def",
"dechiffre",
"(",
"n",
",",
"d",
",",
"*",
"crypt",
")",
":",
"#dechiffrage des blocs",
"resultat",
"=",
"[",
"str",
"(",
"(",
"int",
"(",
"i",
")",
"**",
"d",
")",
"%",
"n",
")",
"for",
"i",
"in",
"crypt",
"]",
"#on rajoute les 0 en debut de blocs pour refaire des blocs de 4",
"for",
"i",
",",
"s",
"in",
"enumerate",
"(",
"resultat",
")",
":",
"if",
"len",
"(",
"s",
")",
"<",
"4",
":",
"while",
"len",
"(",
"s",
")",
"<",
"4",
":",
"s",
"=",
"'0'",
"+",
"s",
"resultat",
"[",
"i",
"]",
"=",
"s",
"#on refait des groupes de 3 et on les convertie directement en ascii",
"g",
"=",
"''",
".",
"join",
"(",
"resultat",
")",
"asci",
"=",
"''",
"d",
",",
"f",
"=",
"0",
",",
"3",
"while",
"f",
"<",
"len",
"(",
"g",
")",
":",
"asci",
"=",
"asci",
"+",
"chr",
"(",
"int",
"(",
"g",
"[",
"d",
":",
"f",
"]",
")",
")",
"#conversion ascii",
"d",
",",
"f",
"=",
"f",
",",
"f",
"+",
"3",
"return",
"asci"
] | [
0,
0
] | [
19,
15
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
get_filepath | (date, data_source='data') | return os.path.join(data_source, f'data_seating_{date}.csv') | Renvoie le filepath d'un fichier donné
Args:
date (string): string contenant la date sous
le format {jour}{Mois abbrégé}
-> exemple : 7Nov
Returns:
string
| Renvoie le filepath d'un fichier donné | def get_filepath(date, data_source='data'):
"""Renvoie le filepath d'un fichier donné
Args:
date (string): string contenant la date sous
le format {jour}{Mois abbrégé}
-> exemple : 7Nov
Returns:
string
"""
return os.path.join(data_source, f'data_seating_{date}.csv') | [
"def",
"get_filepath",
"(",
"date",
",",
"data_source",
"=",
"'data'",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"data_source",
",",
"f'data_seating_{date}.csv'",
")"
] | [
17,
0
] | [
28,
64
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
classement | () | return redirect(url_for('interface')) | Fonction de classement des candidatures
Temps d'exécution long !
| Fonction de classement des candidatures
Temps d'exécution long !
| def classement():
"""Fonction de classement des candidatures
Temps d'exécution long !
"""
conn = sqlite3.connect('monavenir.db')
cur = conn.cursor()
#on récupère tous les idSuperieur des établissements du supérieur
cur.execute("SELECT idSuperieur FROM superieur ;")
#pour chaque établissement
liste_idSuperieur = cur.fetchall()
#ici on a récupéré une liste de tuple
requeteClassement = """
SELECT candidature.idEleve AS idAttente, (note1 * coefNote1 + note2 * coefNote2)/(coefNote1 + coefNote2) AS moyenne
FROM (superieur JOIN candidature USING(idSuperieur)) JOIN eleve USING(idEleve)
WHERE idSuperieur = ?
ORDER BY moyenne DESC
LIMIT ? ;
"""
for etab in liste_idSuperieur:
idSuperieur = int(etab[0])
#on récupère les quotas d'admis et de file d'attente
cur.execute("SELECT nbAdmis, nbAppel FROM superieur WHERE idSuperieur = ?;", (idSuperieur,))
quotas = cur.fetchone()
nbAdmis = int(quotas[0])
nbAppel = int(quotas[1])
#on fixe le statut des en attente
cur.execute(requeteClassement, (idSuperieur, nbAppel))
liste_attente = cur.fetchall()
#on fixe le statut des candidats dans la liste d'appel
for k in range(nbAppel):
if k < nbAdmis:
cur.execute("UPDATE candidature SET statut = 'admis' WHERE idEleve = ? AND idSuperieur = ? ;", (liste_attente[k][0],idSuperieur))
else:
cur.execute("UPDATE candidature SET statut = 'enAttente' WHERE idEleve = ? AND idSuperieur = ? ;", (liste_attente[k][0],idSuperieur))
#on enregistre les modifs précédentes
conn.commit()
#enfin on fixe le statut des refusés
cur.execute("UPDATE candidature SET statut = 'refuse' WHERE idSuperieur = ? AND statut = 'nonTraite';", (idSuperieur,))
#on enregistre
conn.commit()
return redirect(url_for('interface')) | [
"def",
"classement",
"(",
")",
":",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"'monavenir.db'",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"#on récupère tous les idSuperieur des établissements du supérieur\r",
"cur",
".",
"execute",
"(",
"\"SELECT idSuperieur FROM superieur ;\"",
")",
"#pour chaque établissement\r",
"liste_idSuperieur",
"=",
"cur",
".",
"fetchall",
"(",
")",
"#ici on a récupéré une liste de tuple\r",
"requeteClassement",
"=",
"\"\"\"\r\n SELECT candidature.idEleve AS idAttente, (note1 * coefNote1 + note2 * coefNote2)/(coefNote1 + coefNote2) AS moyenne\r\n FROM (superieur JOIN candidature USING(idSuperieur)) JOIN eleve USING(idEleve) \r\n WHERE idSuperieur = ?\r\n ORDER BY moyenne DESC\r\n LIMIT ? ;\r\n \"\"\"",
"for",
"etab",
"in",
"liste_idSuperieur",
":",
"idSuperieur",
"=",
"int",
"(",
"etab",
"[",
"0",
"]",
")",
"#on récupère les quotas d'admis et de file d'attente\r",
"cur",
".",
"execute",
"(",
"\"SELECT nbAdmis, nbAppel FROM superieur WHERE idSuperieur = ?;\"",
",",
"(",
"idSuperieur",
",",
")",
")",
"quotas",
"=",
"cur",
".",
"fetchone",
"(",
")",
"nbAdmis",
"=",
"int",
"(",
"quotas",
"[",
"0",
"]",
")",
"nbAppel",
"=",
"int",
"(",
"quotas",
"[",
"1",
"]",
")",
"#on fixe le statut des en attente \r",
"cur",
".",
"execute",
"(",
"requeteClassement",
",",
"(",
"idSuperieur",
",",
"nbAppel",
")",
")",
"liste_attente",
"=",
"cur",
".",
"fetchall",
"(",
")",
"#on fixe le statut des candidats dans la liste d'appel\r",
"for",
"k",
"in",
"range",
"(",
"nbAppel",
")",
":",
"if",
"k",
"<",
"nbAdmis",
":",
"cur",
".",
"execute",
"(",
"\"UPDATE candidature SET statut = 'admis' WHERE idEleve = ? AND idSuperieur = ? ;\"",
",",
"(",
"liste_attente",
"[",
"k",
"]",
"[",
"0",
"]",
",",
"idSuperieur",
")",
")",
"else",
":",
"cur",
".",
"execute",
"(",
"\"UPDATE candidature SET statut = 'enAttente' WHERE idEleve = ? AND idSuperieur = ? ;\"",
",",
"(",
"liste_attente",
"[",
"k",
"]",
"[",
"0",
"]",
",",
"idSuperieur",
")",
")",
"#on enregistre les modifs précédentes\r",
"conn",
".",
"commit",
"(",
")",
"#enfin on fixe le statut des refusés\r",
"cur",
".",
"execute",
"(",
"\"UPDATE candidature SET statut = 'refuse' WHERE idSuperieur = ? AND statut = 'nonTraite';\"",
",",
"(",
"idSuperieur",
",",
")",
")",
"#on enregistre \r",
"conn",
".",
"commit",
"(",
")",
"return",
"redirect",
"(",
"url_for",
"(",
"'interface'",
")",
")"
] | [
274,
0
] | [
314,
41
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Checker.get_updated_feed | (self) | return feed_last_updated | Recupere la date de dernière mise à jour du flux ATOM | Recupere la date de dernière mise à jour du flux ATOM | def get_updated_feed(self):
"""Recupere la date de dernière mise à jour du flux ATOM"""
if not self.feeddata:
self.load_feed()
NS = {'a': 'http://www.w3.org/2005/Atom'}
strdate = self.feeddata.xpath('/a:feed/a:updated/text()', namespaces=NS)[0]
feed_last_updated = datetime.datetime.strptime(strdate[:19], "%Y-%m-%dT%H:%M:%S")
return feed_last_updated | [
"def",
"get_updated_feed",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"feeddata",
":",
"self",
".",
"load_feed",
"(",
")",
"NS",
"=",
"{",
"'a'",
":",
"'http://www.w3.org/2005/Atom'",
"}",
"strdate",
"=",
"self",
".",
"feeddata",
".",
"xpath",
"(",
"'/a:feed/a:updated/text()'",
",",
"namespaces",
"=",
"NS",
")",
"[",
"0",
"]",
"feed_last_updated",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"strdate",
"[",
":",
"19",
"]",
",",
"\"%Y-%m-%dT%H:%M:%S\"",
")",
"return",
"feed_last_updated"
] | [
44,
4
] | [
52,
32
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Resource.synchronize | (self, url=None, filename=None, content_type=None,
file_extras=None, with_user=None) | Synchronizer le jeu de données avec l'instance de CKAN. | Synchronizer le jeu de données avec l'instance de CKAN. | def synchronize(self, url=None, filename=None, content_type=None,
file_extras=None, with_user=None):
"""Synchronizer le jeu de données avec l'instance de CKAN."""
# Identifiant de la resource CKAN :
id = str(self.ckan_id)
ckan_resource = {}
try:
ckan_resource = CkanHandler.get_resource(id)
except Exception as e:
logger.warning(e)
# Définition des propriétés du « package » :
data = {
'crs': self.crs and self.crs.description or '',
'name': self.title,
'description': self.description,
'data_type': self.data_type,
'extracting_service': str(self.extractable or False), # I <3 CKAN
'format': self.format_type and self.format_type.ckan_format,
'view_type': self.format_type and self.format_type.ckan_view,
'id': id,
'lang': self.lang,
'restricted_by_jurisdiction': str(self.geo_restriction),
'url': url and url or '',
'api': ckan_resource.get('api', '{}'),
}
# (0) Aucune restriction
if self.restricted_level == 'public':
restricted = json.dumps({'level': 'public'})
# (1) Uniquement pour un utilisateur connecté
elif self.restricted_level == 'registered':
restricted = json.dumps({'level': 'registered'})
# (2) Seulement les utilisateurs indiquées
elif self.restricted_level == 'only_allowed_users':
restricted = json.dumps({
'allowed_users': ','.join(
self.profiles_allowed.exists() and [
p.user.username for p
in self.profiles_allowed.all()] or []),
'level': 'only_allowed_users'})
# (3) Les utilisateurs de cette organisation
elif self.restricted_level == 'same_organization':
restricted = json.dumps({
'allowed_users': ','.join(
get_all_users_for_organisations(
self.organisations_allowed.all())),
'level': 'only_allowed_users'})
# (3) Les utilisateurs des organisations indiquées
elif self.restricted_level == 'any_organization':
restricted = json.dumps({
'allowed_users': ','.join(
get_all_users_for_organisations(
self.organisations_allowed.all())),
'level': 'only_allowed_users'})
# (4) Les utilisateurs partenaires IDGO
elif self.restricted_level == 'only_idgo_partners':
restricted = json.dumps({
'allowed_groups': ['idgo-partner'],
'level': 'only_group_member'})
data['restricted'] = restricted
if self.referenced_url:
data['url'] = self.referenced_url
if self.dl_url and filename:
downloaded_file = File(open(filename, 'rb'))
data['upload'] = downloaded_file
data['size'] = downloaded_file.size
data['mimetype'] = content_type
if self.up_file and file_extras:
data['upload'] = self.up_file.file
data['size'] = file_extras.get('size')
data['mimetype'] = file_extras.get('mimetype')
if self.ftp_file:
if not url and filename:
data['upload'] = self.ftp_file.file
data['size'] = self.ftp_file.size
if url or filename:
if self.format_type and (
type(self.format_type.mimetype) is list and len(self.format_type.mimetype)
):
data['mimetype'] = self.format_type.mimetype[0]
else:
data['mimetype'] = 'text/plain'
# data['force_url_type'] = 'upload' # NON PREVU PAR CKAN API
if self.data_type == 'raw':
if self.ftp_file or self.dl_url or self.up_file:
data['resource_type'] = 'file.upload'
elif self.referenced_url:
data['resource_type'] = 'file'
if self.data_type == 'annexe':
data['resource_type'] = 'documentation'
if self.data_type == 'service':
data['resource_type'] = 'api'
ckan_package = CkanHandler.get_package(str(self.dataset.ckan_id))
if with_user:
username = with_user.username
apikey = CkanHandler.get_user(username)['apikey']
with CkanUserHandler(apikey=apikey) as ckan:
ckan.publish_resource(ckan_package, **data)
else:
return CkanHandler.publish_resource(ckan_package, **data) | [
"def",
"synchronize",
"(",
"self",
",",
"url",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"file_extras",
"=",
"None",
",",
"with_user",
"=",
"None",
")",
":",
"# Identifiant de la resource CKAN :",
"id",
"=",
"str",
"(",
"self",
".",
"ckan_id",
")",
"ckan_resource",
"=",
"{",
"}",
"try",
":",
"ckan_resource",
"=",
"CkanHandler",
".",
"get_resource",
"(",
"id",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"e",
")",
"# Définition des propriétés du « package » :",
"data",
"=",
"{",
"'crs'",
":",
"self",
".",
"crs",
"and",
"self",
".",
"crs",
".",
"description",
"or",
"''",
",",
"'name'",
":",
"self",
".",
"title",
",",
"'description'",
":",
"self",
".",
"description",
",",
"'data_type'",
":",
"self",
".",
"data_type",
",",
"'extracting_service'",
":",
"str",
"(",
"self",
".",
"extractable",
"or",
"False",
")",
",",
"# I <3 CKAN",
"'format'",
":",
"self",
".",
"format_type",
"and",
"self",
".",
"format_type",
".",
"ckan_format",
",",
"'view_type'",
":",
"self",
".",
"format_type",
"and",
"self",
".",
"format_type",
".",
"ckan_view",
",",
"'id'",
":",
"id",
",",
"'lang'",
":",
"self",
".",
"lang",
",",
"'restricted_by_jurisdiction'",
":",
"str",
"(",
"self",
".",
"geo_restriction",
")",
",",
"'url'",
":",
"url",
"and",
"url",
"or",
"''",
",",
"'api'",
":",
"ckan_resource",
".",
"get",
"(",
"'api'",
",",
"'{}'",
")",
",",
"}",
"# (0) Aucune restriction",
"if",
"self",
".",
"restricted_level",
"==",
"'public'",
":",
"restricted",
"=",
"json",
".",
"dumps",
"(",
"{",
"'level'",
":",
"'public'",
"}",
")",
"# (1) Uniquement pour un utilisateur connecté",
"elif",
"self",
".",
"restricted_level",
"==",
"'registered'",
":",
"restricted",
"=",
"json",
".",
"dumps",
"(",
"{",
"'level'",
":",
"'registered'",
"}",
")",
"# (2) Seulement les utilisateurs indiquées",
"elif",
"self",
".",
"restricted_level",
"==",
"'only_allowed_users'",
":",
"restricted",
"=",
"json",
".",
"dumps",
"(",
"{",
"'allowed_users'",
":",
"','",
".",
"join",
"(",
"self",
".",
"profiles_allowed",
".",
"exists",
"(",
")",
"and",
"[",
"p",
".",
"user",
".",
"username",
"for",
"p",
"in",
"self",
".",
"profiles_allowed",
".",
"all",
"(",
")",
"]",
"or",
"[",
"]",
")",
",",
"'level'",
":",
"'only_allowed_users'",
"}",
")",
"# (3) Les utilisateurs de cette organisation",
"elif",
"self",
".",
"restricted_level",
"==",
"'same_organization'",
":",
"restricted",
"=",
"json",
".",
"dumps",
"(",
"{",
"'allowed_users'",
":",
"','",
".",
"join",
"(",
"get_all_users_for_organisations",
"(",
"self",
".",
"organisations_allowed",
".",
"all",
"(",
")",
")",
")",
",",
"'level'",
":",
"'only_allowed_users'",
"}",
")",
"# (3) Les utilisateurs des organisations indiquées",
"elif",
"self",
".",
"restricted_level",
"==",
"'any_organization'",
":",
"restricted",
"=",
"json",
".",
"dumps",
"(",
"{",
"'allowed_users'",
":",
"','",
".",
"join",
"(",
"get_all_users_for_organisations",
"(",
"self",
".",
"organisations_allowed",
".",
"all",
"(",
")",
")",
")",
",",
"'level'",
":",
"'only_allowed_users'",
"}",
")",
"# (4) Les utilisateurs partenaires IDGO",
"elif",
"self",
".",
"restricted_level",
"==",
"'only_idgo_partners'",
":",
"restricted",
"=",
"json",
".",
"dumps",
"(",
"{",
"'allowed_groups'",
":",
"[",
"'idgo-partner'",
"]",
",",
"'level'",
":",
"'only_group_member'",
"}",
")",
"data",
"[",
"'restricted'",
"]",
"=",
"restricted",
"if",
"self",
".",
"referenced_url",
":",
"data",
"[",
"'url'",
"]",
"=",
"self",
".",
"referenced_url",
"if",
"self",
".",
"dl_url",
"and",
"filename",
":",
"downloaded_file",
"=",
"File",
"(",
"open",
"(",
"filename",
",",
"'rb'",
")",
")",
"data",
"[",
"'upload'",
"]",
"=",
"downloaded_file",
"data",
"[",
"'size'",
"]",
"=",
"downloaded_file",
".",
"size",
"data",
"[",
"'mimetype'",
"]",
"=",
"content_type",
"if",
"self",
".",
"up_file",
"and",
"file_extras",
":",
"data",
"[",
"'upload'",
"]",
"=",
"self",
".",
"up_file",
".",
"file",
"data",
"[",
"'size'",
"]",
"=",
"file_extras",
".",
"get",
"(",
"'size'",
")",
"data",
"[",
"'mimetype'",
"]",
"=",
"file_extras",
".",
"get",
"(",
"'mimetype'",
")",
"if",
"self",
".",
"ftp_file",
":",
"if",
"not",
"url",
"and",
"filename",
":",
"data",
"[",
"'upload'",
"]",
"=",
"self",
".",
"ftp_file",
".",
"file",
"data",
"[",
"'size'",
"]",
"=",
"self",
".",
"ftp_file",
".",
"size",
"if",
"url",
"or",
"filename",
":",
"if",
"self",
".",
"format_type",
"and",
"(",
"type",
"(",
"self",
".",
"format_type",
".",
"mimetype",
")",
"is",
"list",
"and",
"len",
"(",
"self",
".",
"format_type",
".",
"mimetype",
")",
")",
":",
"data",
"[",
"'mimetype'",
"]",
"=",
"self",
".",
"format_type",
".",
"mimetype",
"[",
"0",
"]",
"else",
":",
"data",
"[",
"'mimetype'",
"]",
"=",
"'text/plain'",
"# data['force_url_type'] = 'upload' # NON PREVU PAR CKAN API",
"if",
"self",
".",
"data_type",
"==",
"'raw'",
":",
"if",
"self",
".",
"ftp_file",
"or",
"self",
".",
"dl_url",
"or",
"self",
".",
"up_file",
":",
"data",
"[",
"'resource_type'",
"]",
"=",
"'file.upload'",
"elif",
"self",
".",
"referenced_url",
":",
"data",
"[",
"'resource_type'",
"]",
"=",
"'file'",
"if",
"self",
".",
"data_type",
"==",
"'annexe'",
":",
"data",
"[",
"'resource_type'",
"]",
"=",
"'documentation'",
"if",
"self",
".",
"data_type",
"==",
"'service'",
":",
"data",
"[",
"'resource_type'",
"]",
"=",
"'api'",
"ckan_package",
"=",
"CkanHandler",
".",
"get_package",
"(",
"str",
"(",
"self",
".",
"dataset",
".",
"ckan_id",
")",
")",
"if",
"with_user",
":",
"username",
"=",
"with_user",
".",
"username",
"apikey",
"=",
"CkanHandler",
".",
"get_user",
"(",
"username",
")",
"[",
"'apikey'",
"]",
"with",
"CkanUserHandler",
"(",
"apikey",
"=",
"apikey",
")",
"as",
"ckan",
":",
"ckan",
".",
"publish_resource",
"(",
"ckan_package",
",",
"*",
"*",
"data",
")",
"else",
":",
"return",
"CkanHandler",
".",
"publish_resource",
"(",
"ckan_package",
",",
"*",
"*",
"data",
")"
] | [
852,
4
] | [
968,
69
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
get_params_return_utils | (listeGroupes, groupe) | return limit_return_intra, limit_return_inter_groupe, limit_return_inter_paquets | Permet d'avoir les paramètres de branching adaptés à chaque cas.
| Permet d'avoir les paramètres de branching adaptés à chaque cas.
| def get_params_return_utils(listeGroupes, groupe):
"""Permet d'avoir les paramètres de branching adaptés à chaque cas.
"""
taille_groupe = listeGroupes[groupe].get_nombre_passagers()
other_groupes_same_taille=0
for groupe2 in list(listeGroupes.keys()):
if listeGroupes[groupe2].get_nombre_passagers()==taille_groupe and groupe2!=groupe:
other_groupes_same_taille+=1
if other_groupes_same_taille <= 2:
limit_return_intra = 3
limit_return_inter_groupe = 2
limit_return_inter_paquets = 5
else:
limit_return_intra = 3
limit_return_inter_groupe = 5
limit_return_inter_paquets = 1
return limit_return_intra, limit_return_inter_groupe, limit_return_inter_paquets | [
"def",
"get_params_return_utils",
"(",
"listeGroupes",
",",
"groupe",
")",
":",
"taille_groupe",
"=",
"listeGroupes",
"[",
"groupe",
"]",
".",
"get_nombre_passagers",
"(",
")",
"other_groupes_same_taille",
"=",
"0",
"for",
"groupe2",
"in",
"list",
"(",
"listeGroupes",
".",
"keys",
"(",
")",
")",
":",
"if",
"listeGroupes",
"[",
"groupe2",
"]",
".",
"get_nombre_passagers",
"(",
")",
"==",
"taille_groupe",
"and",
"groupe2",
"!=",
"groupe",
":",
"other_groupes_same_taille",
"+=",
"1",
"if",
"other_groupes_same_taille",
"<=",
"2",
":",
"limit_return_intra",
"=",
"3",
"limit_return_inter_groupe",
"=",
"2",
"limit_return_inter_paquets",
"=",
"5",
"else",
":",
"limit_return_intra",
"=",
"3",
"limit_return_inter_groupe",
"=",
"5",
"limit_return_inter_paquets",
"=",
"1",
"return",
"limit_return_intra",
",",
"limit_return_inter_groupe",
",",
"limit_return_inter_paquets"
] | [
373,
0
] | [
389,
84
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
bellman_ford_impl | (m, s) | return dist_a, arc_vers | Implémentation de Bellman-Ford sans gestion de cycles négatifs.
m - matrice d'adjacence pondérée.
s - sommet de départ.
Renvoie la liste des distances aux autres sommets et la liste des
arcs constituant les plus courts chemins.
| Implémentation de Bellman-Ford sans gestion de cycles négatifs.
m - matrice d'adjacence pondérée.
s - sommet de départ.
Renvoie la liste des distances aux autres sommets et la liste des
arcs constituant les plus courts chemins.
| def bellman_ford_impl(m, s):
"""Implémentation de Bellman-Ford sans gestion de cycles négatifs.
m - matrice d'adjacence pondérée.
s - sommet de départ.
Renvoie la liste des distances aux autres sommets et la liste des
arcs constituant les plus courts chemins.
"""
dist_a = [None for _ in range(len(m))] # distances à l'infini
dist_a[s] = 0 # distance à lui-même
arc_vers = [None for _ in range(len(m))] # résultat
queue = [s]
while len(queue) != 0:
v = queue.pop(0)
recalcule_bellman_ford(m, v, dist_a, arc_vers, queue)
return dist_a, arc_vers | [
"def",
"bellman_ford_impl",
"(",
"m",
",",
"s",
")",
":",
"dist_a",
"=",
"[",
"None",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"m",
")",
")",
"]",
"# distances à l'infini",
"dist_a",
"[",
"s",
"]",
"=",
"0",
"# distance à lui-même",
"arc_vers",
"=",
"[",
"None",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"m",
")",
")",
"]",
"# résultat",
"queue",
"=",
"[",
"s",
"]",
"while",
"len",
"(",
"queue",
")",
"!=",
"0",
":",
"v",
"=",
"queue",
".",
"pop",
"(",
"0",
")",
"recalcule_bellman_ford",
"(",
"m",
",",
"v",
",",
"dist_a",
",",
"arc_vers",
",",
"queue",
")",
"return",
"dist_a",
",",
"arc_vers"
] | [
189,
0
] | [
205,
27
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
num | (s) | Permet de convertir une chaine en entier en évitant les exeptions | Permet de convertir une chaine en entier en évitant les exeptions | def num(s):
""" Permet de convertir une chaine en entier en évitant les exeptions"""
try:
return int(s)
except ValueError:
return 0 | [
"def",
"num",
"(",
"s",
")",
":",
"try",
":",
"return",
"int",
"(",
"s",
")",
"except",
"ValueError",
":",
"return",
"0"
] | [
18,
0
] | [
23,
16
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
DatasetShow.get | (self, request, dataset_name) | Voir le jeu de données. | Voir le jeu de données. | def get(self, request, dataset_name):
"""Voir le jeu de données."""
datasets = handler_get_request(request)
for dataset in datasets:
if dataset.slug == dataset_name:
return JsonResponse(serialize(dataset), safe=True)
raise Http404() | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"dataset_name",
")",
":",
"datasets",
"=",
"handler_get_request",
"(",
"request",
")",
"for",
"dataset",
"in",
"datasets",
":",
"if",
"dataset",
".",
"slug",
"==",
"dataset_name",
":",
"return",
"JsonResponse",
"(",
"serialize",
"(",
"dataset",
")",
",",
"safe",
"=",
"True",
")",
"raise",
"Http404",
"(",
")"
] | [
306,
4
] | [
312,
23
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Storage.create_many_nodes_by_name | (self, names, coords) | Crée plusieurs noeuds en spécifiant leur nom | Crée plusieurs noeuds en spécifiant leur nom | def create_many_nodes_by_name(self, names, coords):
"""Crée plusieurs noeuds en spécifiant leur nom"""
cursor = self.connection.cursor()
cursor.executemany(
'INSERT INTO nodes (name, x, y, color) VALUES (?, ?, ?, "grey")',
[(name, coords[0], coords[1]) for name in names],
)
self.connection.commit() | [
"def",
"create_many_nodes_by_name",
"(",
"self",
",",
"names",
",",
"coords",
")",
":",
"cursor",
"=",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"executemany",
"(",
"'INSERT INTO nodes (name, x, y, color) VALUES (?, ?, ?, \"grey\")'",
",",
"[",
"(",
"name",
",",
"coords",
"[",
"0",
"]",
",",
"coords",
"[",
"1",
"]",
")",
"for",
"name",
"in",
"names",
"]",
",",
")",
"self",
".",
"connection",
".",
"commit",
"(",
")"
] | [
73,
4
] | [
80,
32
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
facette.normale | (self, p, rayon) | retourne la normale au point de coordonn�e p et connaissant le rayon | retourne la normale au point de coordonn�e p et connaissant le rayon | def normale (self, p, rayon) :
"""retourne la normale au point de coordonn�e p et connaissant le rayon"""
if rayon.direction.scalaire (self.vnorm) < 0 :
return self.vnorm
else :
return - self.vnorm | [
"def",
"normale",
"(",
"self",
",",
"p",
",",
"rayon",
")",
":",
"if",
"rayon",
".",
"direction",
".",
"scalaire",
"(",
"self",
".",
"vnorm",
")",
"<",
"0",
":",
"return",
"self",
".",
"vnorm",
"else",
":",
"return",
"-",
"self",
".",
"vnorm"
] | [
50,
4
] | [
55,
31
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Map.bouger | (self, x, y) | Déplacer la map
Déplace:
- Les 3 couches esthétiques de tuiles
- La 4 ème couche qui passe par-dessus le personnage
| Déplacer la map
Déplace:
- Les 3 couches esthétiques de tuiles
- La 4 ème couche qui passe par-dessus le personnage
| def bouger(self, x, y):
"""Déplacer la map
Déplace:
- Les 3 couches esthétiques de tuiles
- La 4 ème couche qui passe par-dessus le personnage
"""
cp.map.x_camera += x # Bouger la camera
cp.map.y_camera += y | [
"def",
"bouger",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"cp",
".",
"map",
".",
"x_camera",
"+=",
"x",
"# Bouger la camera",
"cp",
".",
"map",
".",
"y_camera",
"+=",
"y"
] | [
88,
4
] | [
95,
28
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
trouve_valeur_dans_arbre_rouge_noir | (arbre, valeur) | return noeud | Trouve une valeur dans l'arbre rouge-noir. | Trouve une valeur dans l'arbre rouge-noir. | def trouve_valeur_dans_arbre_rouge_noir(arbre, valeur):
"""Trouve une valeur dans l'arbre rouge-noir."""
noeud = arbre.noeud
while noeud != None and noeud.valeur != valeur:
if valeur < noeud.valeur:
noeud = noeud.gauche
else:
noeud = noeud.droite
return noeud | [
"def",
"trouve_valeur_dans_arbre_rouge_noir",
"(",
"arbre",
",",
"valeur",
")",
":",
"noeud",
"=",
"arbre",
".",
"noeud",
"while",
"noeud",
"!=",
"None",
"and",
"noeud",
".",
"valeur",
"!=",
"valeur",
":",
"if",
"valeur",
"<",
"noeud",
".",
"valeur",
":",
"noeud",
"=",
"noeud",
".",
"gauche",
"else",
":",
"noeud",
"=",
"noeud",
".",
"droite",
"return",
"noeud"
] | [
129,
0
] | [
138,
16
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Crud.set_app | (self, val) | Valoriser le nom de l'application courante | Valoriser le nom de l'application courante | def set_app(self, val):
""" Valoriser le nom de l'application courante """
self.ctx["app"] = val | [
"def",
"set_app",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"ctx",
"[",
"\"app\"",
"]",
"=",
"val"
] | [
274,
4
] | [
276,
29
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Objet.normale | (self, p, rayon) | return None | retourne la normale au point de coordonnée p, et connaissant le rayon | retourne la normale au point de coordonnée p, et connaissant le rayon | def normale(self, p, rayon):
"""retourne la normale au point de coordonnée p, et connaissant le rayon"""
return None | [
"def",
"normale",
"(",
"self",
",",
"p",
",",
"rayon",
")",
":",
"return",
"None"
] | [
256,
4
] | [
258,
19
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
forensic | () | brute force / comprendre le problème ... | brute force / comprendre le problème ... | def forensic():
""" brute force / comprendre le problème ... """
def is_strange(i):
l = len(str(i))
if l == 1:
return True
if i % l != 0:
return False
return is_strange(i // l)
def construction(i):
s = str(i)
l = len(s)
if l == 1: return "1" + " (" + s + ")"
return str(l) + " " + construction(i // l)
n = 0
l = 0
for i in range(100, 100000):
if is_strange(i):
if l != len(str(i)):
l = len(str(i))
n = 0
n += 1
print("{:3} {:10} {}".format(n, i, construction(i))) | [
"def",
"forensic",
"(",
")",
":",
"def",
"is_strange",
"(",
"i",
")",
":",
"l",
"=",
"len",
"(",
"str",
"(",
"i",
")",
")",
"if",
"l",
"==",
"1",
":",
"return",
"True",
"if",
"i",
"%",
"l",
"!=",
"0",
":",
"return",
"False",
"return",
"is_strange",
"(",
"i",
"//",
"l",
")",
"def",
"construction",
"(",
"i",
")",
":",
"s",
"=",
"str",
"(",
"i",
")",
"l",
"=",
"len",
"(",
"s",
")",
"if",
"l",
"==",
"1",
":",
"return",
"\"1\"",
"+",
"\" (\"",
"+",
"s",
"+",
"\")\"",
"return",
"str",
"(",
"l",
")",
"+",
"\" \"",
"+",
"construction",
"(",
"i",
"//",
"l",
")",
"n",
"=",
"0",
"l",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"100",
",",
"100000",
")",
":",
"if",
"is_strange",
"(",
"i",
")",
":",
"if",
"l",
"!=",
"len",
"(",
"str",
"(",
"i",
")",
")",
":",
"l",
"=",
"len",
"(",
"str",
"(",
"i",
")",
")",
"n",
"=",
"0",
"n",
"+=",
"1",
"print",
"(",
"\"{:3} {:10} {}\"",
".",
"format",
"(",
"n",
",",
"i",
",",
"construction",
"(",
"i",
")",
")",
")"
] | [
15,
0
] | [
42,
64
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
create_weighted_dict | (nodes, relations) | return result | Crée une liste d'adjacence pondérée à partir d'une liste de noeuds et de relations | Crée une liste d'adjacence pondérée à partir d'une liste de noeuds et de relations | def create_weighted_dict(nodes, relations):
"""Crée une liste d'adjacence pondérée à partir d'une liste de noeuds et de relations"""
# Similaire à la fonction create_dict, sauf qu'on renseigne aussi les poids des relations
result = {}
for node in nodes:
id = node[0]
neighbours_dict = {}
for relation in relations:
start = relation[0]
end = relation[1]
oriented = relation[2] == 1
weight = relation[3]
if start == id:
neighbours_dict[end] = weight
elif end == id and not oriented:
neighbours_dict[start] = weight
result[id] = neighbours_dict
return result | [
"def",
"create_weighted_dict",
"(",
"nodes",
",",
"relations",
")",
":",
"# Similaire à la fonction create_dict, sauf qu'on renseigne aussi les poids des relations",
"result",
"=",
"{",
"}",
"for",
"node",
"in",
"nodes",
":",
"id",
"=",
"node",
"[",
"0",
"]",
"neighbours_dict",
"=",
"{",
"}",
"for",
"relation",
"in",
"relations",
":",
"start",
"=",
"relation",
"[",
"0",
"]",
"end",
"=",
"relation",
"[",
"1",
"]",
"oriented",
"=",
"relation",
"[",
"2",
"]",
"==",
"1",
"weight",
"=",
"relation",
"[",
"3",
"]",
"if",
"start",
"==",
"id",
":",
"neighbours_dict",
"[",
"end",
"]",
"=",
"weight",
"elif",
"end",
"==",
"id",
"and",
"not",
"oriented",
":",
"neighbours_dict",
"[",
"start",
"]",
"=",
"weight",
"result",
"[",
"id",
"]",
"=",
"neighbours_dict",
"return",
"result"
] | [
26,
0
] | [
43,
17
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Calculatrice.supprimerResultat | (self) | On reset le texte des deux LineEdit | On reset le texte des deux LineEdit | def supprimerResultat(self):
"""On reset le texte des deux LineEdit"""
self.le_resultat.setText('0')
self.le_operation.setText('') | [
"def",
"supprimerResultat",
"(",
"self",
")",
":",
"self",
".",
"le_resultat",
".",
"setText",
"(",
"'0'",
")",
"self",
".",
"le_operation",
".",
"setText",
"(",
"''",
")"
] | [
71,
1
] | [
74,
31
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
is_edi_cde_cli.getNumCommandeClient | (self, ref_article_client) | Recherche du numéro de commande client à partir de la référence article | Recherche du numéro de commande client à partir de la référence article | def getNumCommandeClient(self, ref_article_client):
"""Recherche du numéro de commande client à partir de la référence article"""
for obj in self:
num_commande_client = "??"
SaleOrder = self.getSaleOrder(ref_article_client)
if SaleOrder:
num_commande_client = SaleOrder.client_order_ref
return num_commande_client | [
"def",
"getNumCommandeClient",
"(",
"self",
",",
"ref_article_client",
")",
":",
"for",
"obj",
"in",
"self",
":",
"num_commande_client",
"=",
"\"??\"",
"SaleOrder",
"=",
"self",
".",
"getSaleOrder",
"(",
"ref_article_client",
")",
"if",
"SaleOrder",
":",
"num_commande_client",
"=",
"SaleOrder",
".",
"client_order_ref",
"return",
"num_commande_client"
] | [
412,
4
] | [
419,
38
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Screen.OMtopx | (self, OM) | return (self.mtopx(OM[0])+xshift, ymax-self.mtopx(OM[1])) | Convertit les positions en m vers des coords en pixels
Retourne un tuple | Convertit les positions en m vers des coords en pixels
Retourne un tuple | def OMtopx(self, OM):
'''Convertit les positions en m vers des coords en pixels
Retourne un tuple '''
xshift = self.worldrect[0]
ymax = self.worldrect[1]+self.worldrect[3]
return (self.mtopx(OM[0])+xshift, ymax-self.mtopx(OM[1])) | [
"def",
"OMtopx",
"(",
"self",
",",
"OM",
")",
":",
"xshift",
"=",
"self",
".",
"worldrect",
"[",
"0",
"]",
"ymax",
"=",
"self",
".",
"worldrect",
"[",
"1",
"]",
"+",
"self",
".",
"worldrect",
"[",
"3",
"]",
"return",
"(",
"self",
".",
"mtopx",
"(",
"OM",
"[",
"0",
"]",
")",
"+",
"xshift",
",",
"ymax",
"-",
"self",
".",
"mtopx",
"(",
"OM",
"[",
"1",
"]",
")",
")"
] | [
146,
4
] | [
151,
65
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
get_points_3D | (xys, depth, depth_intrinsic, around) | return points_3D | Calcul des coordonnées 3D dans un repère centré sur la caméra,
avec le z = profondeur
La profondeur est une moyenne de la profondeur des points autour,
sauf les trop loins et les extrêmes.
| Calcul des coordonnées 3D dans un repère centré sur la caméra,
avec le z = profondeur
La profondeur est une moyenne de la profondeur des points autour,
sauf les trop loins et les extrêmes.
| def get_points_3D(xys, depth, depth_intrinsic, around):
"""Calcul des coordonnées 3D dans un repère centré sur la caméra,
avec le z = profondeur
La profondeur est une moyenne de la profondeur des points autour,
sauf les trop loins et les extrêmes.
"""
points_3D = [None]*17
for key, val in xys.items():
if val:
#
distance_in_square = []
x, y = val[0], val[1]
# nombre de pixel autour du points = 5
x_min = max(x - around, 0)
x_max = min(x + around, depth.width)
y_min = max(y - around, 0)
y_max = min(y + around, depth.height)
for u in range(x_min, x_max):
for v in range(y_min, y_max):
distance_in_square.append(depth.get_distance(u, v))
if distance_in_square:
dists = np.asarray(distance_in_square)
else:
dists = None
if dists.any():
# Suppression du plus petit et du plus grand
dists = np.sort(dists)
dists = dists[1:-1]
# Moyenne
average = np.average(dists)
# Exclusion des trop éloignés
reste = dists[ (dists >= average*0.8) & (dists <= average*1.2) ]
# Eloignement estimé du points
profondeur = np.average(reste)
# Calcul les coordonnées 3D avec x et y coordonnées dans
# l'image et la profondeur du point
point_with_deph = rs.rs2_deproject_pixel_to_point(depth_intrinsic,
[x, y],
profondeur)
if not np.isnan(point_with_deph[0]):
points_3D[key] = point_with_deph
return points_3D | [
"def",
"get_points_3D",
"(",
"xys",
",",
"depth",
",",
"depth_intrinsic",
",",
"around",
")",
":",
"points_3D",
"=",
"[",
"None",
"]",
"*",
"17",
"for",
"key",
",",
"val",
"in",
"xys",
".",
"items",
"(",
")",
":",
"if",
"val",
":",
"#",
"distance_in_square",
"=",
"[",
"]",
"x",
",",
"y",
"=",
"val",
"[",
"0",
"]",
",",
"val",
"[",
"1",
"]",
"# nombre de pixel autour du points = 5",
"x_min",
"=",
"max",
"(",
"x",
"-",
"around",
",",
"0",
")",
"x_max",
"=",
"min",
"(",
"x",
"+",
"around",
",",
"depth",
".",
"width",
")",
"y_min",
"=",
"max",
"(",
"y",
"-",
"around",
",",
"0",
")",
"y_max",
"=",
"min",
"(",
"y",
"+",
"around",
",",
"depth",
".",
"height",
")",
"for",
"u",
"in",
"range",
"(",
"x_min",
",",
"x_max",
")",
":",
"for",
"v",
"in",
"range",
"(",
"y_min",
",",
"y_max",
")",
":",
"distance_in_square",
".",
"append",
"(",
"depth",
".",
"get_distance",
"(",
"u",
",",
"v",
")",
")",
"if",
"distance_in_square",
":",
"dists",
"=",
"np",
".",
"asarray",
"(",
"distance_in_square",
")",
"else",
":",
"dists",
"=",
"None",
"if",
"dists",
".",
"any",
"(",
")",
":",
"# Suppression du plus petit et du plus grand",
"dists",
"=",
"np",
".",
"sort",
"(",
"dists",
")",
"dists",
"=",
"dists",
"[",
"1",
":",
"-",
"1",
"]",
"# Moyenne",
"average",
"=",
"np",
".",
"average",
"(",
"dists",
")",
"# Exclusion des trop éloignés",
"reste",
"=",
"dists",
"[",
"(",
"dists",
">=",
"average",
"*",
"0.8",
")",
"&",
"(",
"dists",
"<=",
"average",
"*",
"1.2",
")",
"]",
"# Eloignement estimé du points",
"profondeur",
"=",
"np",
".",
"average",
"(",
"reste",
")",
"# Calcul les coordonnées 3D avec x et y coordonnées dans",
"# l'image et la profondeur du point",
"point_with_deph",
"=",
"rs",
".",
"rs2_deproject_pixel_to_point",
"(",
"depth_intrinsic",
",",
"[",
"x",
",",
"y",
"]",
",",
"profondeur",
")",
"if",
"not",
"np",
".",
"isnan",
"(",
"point_with_deph",
"[",
"0",
"]",
")",
":",
"points_3D",
"[",
"key",
"]",
"=",
"point_with_deph",
"return",
"points_3D"
] | [
251,
0
] | [
298,
20
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Calculatrice.btnNombrePressed | (self, bouton) | Fonction activée quand l'utilisateur appuie sur un chiffre (0-9) | Fonction activée quand l'utilisateur appuie sur un chiffre (0-9) | def btnNombrePressed(self, bouton):
"""Fonction activée quand l'utilisateur appuie sur un chiffre (0-9)"""
resultat = self.le_resultat.text()
if resultat == '0':
self.le_resultat.setText(bouton)
else:
self.le_resultat.setText(resultat + bouton) | [
"def",
"btnNombrePressed",
"(",
"self",
",",
"bouton",
")",
":",
"resultat",
"=",
"self",
".",
"le_resultat",
".",
"text",
"(",
")",
"if",
"resultat",
"==",
"'0'",
":",
"self",
".",
"le_resultat",
".",
"setText",
"(",
"bouton",
")",
"else",
":",
"self",
".",
"le_resultat",
".",
"setText",
"(",
"resultat",
"+",
"bouton",
")"
] | [
58,
1
] | [
64,
46
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Storage.get_node_by_name | (self, name) | return result | Récupère un noeud par son nom | Récupère un noeud par son nom | def get_node_by_name(self, name):
"""Récupère un noeud par son nom"""
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM nodes WHERE name = ?", (name,))
result = cursor.fetchone()[0]
return result | [
"def",
"get_node_by_name",
"(",
"self",
",",
"name",
")",
":",
"cursor",
"=",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"SELECT * FROM nodes WHERE name = ?\"",
",",
"(",
"name",
",",
")",
")",
"result",
"=",
"cursor",
".",
"fetchone",
"(",
")",
"[",
"0",
"]",
"return",
"result"
] | [
40,
4
] | [
45,
21
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
eval_matrix | (text) | Transformer le texte en une matrice (double liste) | Transformer le texte en une matrice (double liste) | def eval_matrix(text):
"""Transformer le texte en une matrice (double liste)"""
text = text.replace(" ", "").replace("\n", "")
result = is_matrix_correct.match(text)
if result:
return eval(text)
else:
raise RuntimeError("Illegal matrix text provided") | [
"def",
"eval_matrix",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"replace",
"(",
"\" \"",
",",
"\"\"",
")",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
"result",
"=",
"is_matrix_correct",
".",
"match",
"(",
"text",
")",
"if",
"result",
":",
"return",
"eval",
"(",
"text",
")",
"else",
":",
"raise",
"RuntimeError",
"(",
"\"Illegal matrix text provided\"",
")"
] | [
8,
0
] | [
15,
58
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
cercle | (x, y, r, color='black') | tracé d'un cercle de centre (x,y) et de rayon r | tracé d'un cercle de centre (x,y) et de rayon r | def cercle(x, y, r, color='black'):
"""tracé d'un cercle de centre (x,y) et de rayon r"""
MonCanvas.create_oval(x - r, y - r, x + r, y + r, outline=color) | [
"def",
"cercle",
"(",
"x",
",",
"y",
",",
"r",
",",
"color",
"=",
"'black'",
")",
":",
"MonCanvas",
".",
"create_oval",
"(",
"x",
"-",
"r",
",",
"y",
"-",
"r",
",",
"x",
"+",
"r",
",",
"y",
"+",
"r",
",",
"outline",
"=",
"color",
")"
] | [
51,
0
] | [
53,
68
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Screen.run | (self) | Code à exécuter pendant l'exécution du thread. | Code à exécuter pendant l'exécution du thread. | def run(self):
"""Code à exécuter pendant l'exécution du thread."""
i = 0
while True:
animation.loop_chenillard(self.strip, color=Color(95, 90, 255))
time.sleep(0.5)
animation.loop_chenillard_digits(self.strip)
time.sleep(0.5) | [
"def",
"run",
"(",
"self",
")",
":",
"i",
"=",
"0",
"while",
"True",
":",
"animation",
".",
"loop_chenillard",
"(",
"self",
".",
"strip",
",",
"color",
"=",
"Color",
"(",
"95",
",",
"90",
",",
"255",
")",
")",
"time",
".",
"sleep",
"(",
"0.5",
")",
"animation",
".",
"loop_chenillard_digits",
"(",
"self",
".",
"strip",
")",
"time",
".",
"sleep",
"(",
"0.5",
")"
] | [
20,
4
] | [
28,
27
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Admin.owner_reload | (self, ctx: MyContext) | Ajoute le rôle Owner à tout les membres possédant un serveur avec le bot
Il est nécessaire d'avoir au moins 10 membres pour que le rôle soit ajouté | Ajoute le rôle Owner à tout les membres possédant un serveur avec le bot
Il est nécessaire d'avoir au moins 10 membres pour que le rôle soit ajouté | async def owner_reload(self, ctx: MyContext):
"""Ajoute le rôle Owner à tout les membres possédant un serveur avec le bot
Il est nécessaire d'avoir au moins 10 membres pour que le rôle soit ajouté"""
server = self.bot.get_guild(356067272730607628)
if server is None:
await ctx.send("Serveur ZBot introuvable")
return
role = server.get_role(486905171738361876)
if role is None:
await ctx.send("Rôle Owners introuvable")
return
owner_list = list()
for guild in self.bot.guilds:
if len(guild.members)>9:
if guild.owner_id is None:
await ctx.send("Oops, askip le propriétaire de {} n'existe pas ._.".format(guild.id))
continue
owner_list.append(guild.owner_id)
for member in server.members:
if member.id in owner_list and role not in member.roles:
await ctx.send("Rôle ajouté à "+str(member))
await member.add_roles(role,reason="This user support me")
elif (member.id not in owner_list) and role in member.roles:
await ctx.send("Rôle supprimé à "+str(member))
await member.remove_roles(role,reason="This user doesn't support me anymore")
await ctx.bot.get_cog('Utilities').add_check_reaction(ctx.message) | [
"async",
"def",
"owner_reload",
"(",
"self",
",",
"ctx",
":",
"MyContext",
")",
":",
"server",
"=",
"self",
".",
"bot",
".",
"get_guild",
"(",
"356067272730607628",
")",
"if",
"server",
"is",
"None",
":",
"await",
"ctx",
".",
"send",
"(",
"\"Serveur ZBot introuvable\"",
")",
"return",
"role",
"=",
"server",
".",
"get_role",
"(",
"486905171738361876",
")",
"if",
"role",
"is",
"None",
":",
"await",
"ctx",
".",
"send",
"(",
"\"Rôle Owners introuvable\")",
"",
"return",
"owner_list",
"=",
"list",
"(",
")",
"for",
"guild",
"in",
"self",
".",
"bot",
".",
"guilds",
":",
"if",
"len",
"(",
"guild",
".",
"members",
")",
">",
"9",
":",
"if",
"guild",
".",
"owner_id",
"is",
"None",
":",
"await",
"ctx",
".",
"send",
"(",
"\"Oops, askip le propriétaire de {} n'existe pas ._.\".",
"f",
"ormat(",
"g",
"uild.",
"i",
"d)",
")",
"",
"continue",
"owner_list",
".",
"append",
"(",
"guild",
".",
"owner_id",
")",
"for",
"member",
"in",
"server",
".",
"members",
":",
"if",
"member",
".",
"id",
"in",
"owner_list",
"and",
"role",
"not",
"in",
"member",
".",
"roles",
":",
"await",
"ctx",
".",
"send",
"(",
"\"Rôle ajouté à \"+st",
"r",
"(me",
"m",
"ber))",
"",
"",
"await",
"member",
".",
"add_roles",
"(",
"role",
",",
"reason",
"=",
"\"This user support me\"",
")",
"elif",
"(",
"member",
".",
"id",
"not",
"in",
"owner_list",
")",
"and",
"role",
"in",
"member",
".",
"roles",
":",
"await",
"ctx",
".",
"send",
"(",
"\"Rôle supprimé à \"+st",
"r",
"(me",
"m",
"ber))",
"",
"",
"await",
"member",
".",
"remove_roles",
"(",
"role",
",",
"reason",
"=",
"\"This user doesn't support me anymore\"",
")",
"await",
"ctx",
".",
"bot",
".",
"get_cog",
"(",
"'Utilities'",
")",
".",
"add_check_reaction",
"(",
"ctx",
".",
"message",
")"
] | [
641,
4
] | [
666,
74
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
white_noise | () | Remplit le tableau (donc la table t) avec du bruit blanc | Remplit le tableau (donc la table t) avec du bruit blanc | def white_noise():
"Remplit le tableau (donc la table t) avec du bruit blanc"
arr[:] = np.random.normal(0.0, 0.5, size=bs) | [
"def",
"white_noise",
"(",
")",
":",
"arr",
"[",
":",
"]",
"=",
"np",
".",
"random",
".",
"normal",
"(",
"0.0",
",",
"0.5",
",",
"size",
"=",
"bs",
")"
] | [
20,
0
] | [
22,
48
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
diviseur | (n) | return n | premier diviseur premier de n | premier diviseur premier de n | def diviseur(n):
""" premier diviseur premier de n """
i = 2
while i * i <= n:
q, r = divmod(n, i)
if r == 0:
return i
i += 1
return n | [
"def",
"diviseur",
"(",
"n",
")",
":",
"i",
"=",
"2",
"while",
"i",
"*",
"i",
"<=",
"n",
":",
"q",
",",
"r",
"=",
"divmod",
"(",
"n",
",",
"i",
")",
"if",
"r",
"==",
"0",
":",
"return",
"i",
"i",
"+=",
"1",
"return",
"n"
] | [
15,
0
] | [
23,
12
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
resultatStatsEtabAvant | () | Controleur de la route '/resultatStatsEtabAvant' | Controleur de la route '/resultatStatsEtabAvant' | def resultatStatsEtabAvant():
"Controleur de la route '/resultatStatsEtabAvant' "
def requeteNomEtab(conn, cur, idSuperieur):
cur.execute("SELECT nom FROM superieur WHERE idSuperieur = ? ;", (idSuperieur,))
return cur.fetchone()['nom']
def requeteTotalCandidature(conn, cur, idSuperieur):
cur.execute("SELECT COUNT(*) AS total FROM candidature WHERE idSuperieur = ? ;", (idSuperieur,))
return int(cur.fetchone()['total'])
def requeteSeuilAdmis(conn, cur, idSuperieur):
requete = """
SELECT min(m) AS seuil FROM (
SELECT (note1 * coefNote1 + note2 * coefNote2)/(coefNote1 + coefNote2) AS m
FROM (superieur JOIN candidature USING(idSuperieur)) JOIN eleve USING(idEleve)
WHERE idSuperieur = ?
ORDER BY m DESC
LIMIT (SELECT nbAdmis FROM superieur WHERE idSuperieur = ?)
);
"""
cur.execute(requete, (idSuperieur,idSuperieur))
return float(cur.fetchone()['seuil'])
def requeteSeuilAttente(conn, cur, idSuperieur):
requete = """
SELECT min(m) AS seuil FROM (
SELECT (note1 * coefNote1 + note2 * coefNote2)/(coefNote1 + coefNote2) AS m
FROM (superieur JOIN candidature USING(idSuperieur)) JOIN eleve USING(idEleve)
WHERE idSuperieur = ?
ORDER BY m DESC
LIMIT (SELECT nbAppel FROM superieur WHERE idSuperieur = ?)
);
"""
cur.execute(requete, (idSuperieur,idSuperieur))
return float(cur.fetchone()['seuil'])
def requeteListeCandidatureLycee(conn, cur, idSuperieur):
requete = """
SELECT COUNT(*) AS nb, lycee.nom AS nom
FROM (candidature JOIN eleve USING(idEleve)) JOIN lycee USING(idLycee)
WHERE idSuperieur = ?
GROUP BY idLycee
ORDER BY nb DESC ;
"""
cur.execute(requete, (idSuperieur,))
return cur.fetchall()
#analyse du formulaire
if request.method == 'POST':
#ouverture du formulaire
result = request.form
idSuperieur = result['idSuperieur']
#ouverture de la BDD
conn = sqlite3.connect('monavenir.db')
conn.row_factory = sqlite3.Row #pour récupérer les lignes sous forme de dictionnaire
cur = conn.cursor()
#requete sur le nom de l'établissement
nom = requeteNomEtab(conn, cur, idSuperieur)
#initialisation du dictionnaire de statistiques
stats = dict()
stats['nom'] = nom
#on peuple stats avec les résultats des requetes, une par paramètre transmis par le formulaire
if 'total' in result:
stats['total'] = requeteTotalCandidature(conn, cur, idSuperieur)
if 'seuilAdmis' in result:
stats['seuilAdmis'] = requeteSeuilAdmis(conn, cur, idSuperieur)
if 'seuilAttente' in result:
stats['seuilAttente'] = requeteSeuilAttente(conn, cur, idSuperieur)
if 'candidLycee' in result:
stats['candidLycee'] = requeteListeCandidatureLycee(conn, cur, idSuperieur)
#fermeture de la BDD
cur.close()
conn.close()
#renvoi du template
return render_template("resultatStatsEtabAvant.html", stats = stats) | [
"def",
"resultatStatsEtabAvant",
"(",
")",
":",
"def",
"requeteNomEtab",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
":",
"cur",
".",
"execute",
"(",
"\"SELECT nom FROM superieur WHERE idSuperieur = ? ;\"",
",",
"(",
"idSuperieur",
",",
")",
")",
"return",
"cur",
".",
"fetchone",
"(",
")",
"[",
"'nom'",
"]",
"def",
"requeteTotalCandidature",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
":",
"cur",
".",
"execute",
"(",
"\"SELECT COUNT(*) AS total FROM candidature WHERE idSuperieur = ? ;\"",
",",
"(",
"idSuperieur",
",",
")",
")",
"return",
"int",
"(",
"cur",
".",
"fetchone",
"(",
")",
"[",
"'total'",
"]",
")",
"def",
"requeteSeuilAdmis",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
":",
"requete",
"=",
"\"\"\"\r\n SELECT min(m) AS seuil FROM (\r\n\t SELECT (note1 * coefNote1 + note2 * coefNote2)/(coefNote1 + coefNote2) AS m\r\n FROM (superieur JOIN candidature USING(idSuperieur)) JOIN eleve USING(idEleve) \r\n WHERE idSuperieur = ?\r\n ORDER BY m DESC\r\n LIMIT (SELECT nbAdmis FROM superieur WHERE idSuperieur = ?)\r\n );\r\n \"\"\"",
"cur",
".",
"execute",
"(",
"requete",
",",
"(",
"idSuperieur",
",",
"idSuperieur",
")",
")",
"return",
"float",
"(",
"cur",
".",
"fetchone",
"(",
")",
"[",
"'seuil'",
"]",
")",
"def",
"requeteSeuilAttente",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
":",
"requete",
"=",
"\"\"\"\r\n SELECT min(m) AS seuil FROM (\r\n\t SELECT (note1 * coefNote1 + note2 * coefNote2)/(coefNote1 + coefNote2) AS m\r\n FROM (superieur JOIN candidature USING(idSuperieur)) JOIN eleve USING(idEleve) \r\n WHERE idSuperieur = ?\r\n ORDER BY m DESC\r\n LIMIT (SELECT nbAppel FROM superieur WHERE idSuperieur = ?)\r\n );\r\n \"\"\"",
"cur",
".",
"execute",
"(",
"requete",
",",
"(",
"idSuperieur",
",",
"idSuperieur",
")",
")",
"return",
"float",
"(",
"cur",
".",
"fetchone",
"(",
")",
"[",
"'seuil'",
"]",
")",
"def",
"requeteListeCandidatureLycee",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
":",
"requete",
"=",
"\"\"\"\r\n SELECT COUNT(*) AS nb, lycee.nom AS nom\r\n FROM (candidature JOIN eleve USING(idEleve)) JOIN lycee USING(idLycee)\r\n WHERE idSuperieur = ? \r\n GROUP BY idLycee\r\n ORDER BY nb DESC ;\r\n \"\"\"",
"cur",
".",
"execute",
"(",
"requete",
",",
"(",
"idSuperieur",
",",
")",
")",
"return",
"cur",
".",
"fetchall",
"(",
")",
"#analyse du formulaire\r",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"#ouverture du formulaire\r",
"result",
"=",
"request",
".",
"form",
"idSuperieur",
"=",
"result",
"[",
"'idSuperieur'",
"]",
"#ouverture de la BDD\r",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"'monavenir.db'",
")",
"conn",
".",
"row_factory",
"=",
"sqlite3",
".",
"Row",
"#pour récupérer les lignes sous forme de dictionnaire \r",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"#requete sur le nom de l'établissement\r",
"nom",
"=",
"requeteNomEtab",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
"#initialisation du dictionnaire de statistiques\r",
"stats",
"=",
"dict",
"(",
")",
"stats",
"[",
"'nom'",
"]",
"=",
"nom",
"#on peuple stats avec les résultats des requetes, une par paramètre transmis par le formulaire\r",
"if",
"'total'",
"in",
"result",
":",
"stats",
"[",
"'total'",
"]",
"=",
"requeteTotalCandidature",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
"if",
"'seuilAdmis'",
"in",
"result",
":",
"stats",
"[",
"'seuilAdmis'",
"]",
"=",
"requeteSeuilAdmis",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
"if",
"'seuilAttente'",
"in",
"result",
":",
"stats",
"[",
"'seuilAttente'",
"]",
"=",
"requeteSeuilAttente",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
"if",
"'candidLycee'",
"in",
"result",
":",
"stats",
"[",
"'candidLycee'",
"]",
"=",
"requeteListeCandidatureLycee",
"(",
"conn",
",",
"cur",
",",
"idSuperieur",
")",
"#fermeture de la BDD\r",
"cur",
".",
"close",
"(",
")",
"conn",
".",
"close",
"(",
")",
"#renvoi du template\r",
"return",
"render_template",
"(",
"\"resultatStatsEtabAvant.html\"",
",",
"stats",
"=",
"stats",
")"
] | [
105,
0
] | [
180,
76
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Layer.save_vector_layer | (self, *args, **kwargs) | Synchronizer la couche de données vectorielle avec le service OGC via MRA. | Synchronizer la couche de données vectorielle avec le service OGC via MRA. | def save_vector_layer(self, *args, **kwargs):
"""Synchronizer la couche de données vectorielle avec le service OGC via MRA."""
organisation = self.resource.dataset.organisation
ws_name = organisation.slug
ds_name = 'public'
styles_sld = []
if self.pk:
try:
Layer.objects.get(pk=self.pk)
except Layer.DoesNotExist:
pass
else:
# On vérifie si l'organisation du jeu de données a changée,
# auquel cas il est nécessaire de supprimer les objets MRA
# afin de les recréer dans le bon workspace (c-à-d Mapfile).
previous_layer = MRAHandler.get_layer(self.name)
regex = '/workspaces/(?P<ws_name>[a-z0-9_\-]+)/datastores/'
matched = re.search(regex, previous_layer['resource']['href'])
if matched:
previous_ws_name = matched.group('ws_name')
if not ws_name == previous_ws_name:
layer_styles = MRAHandler.get_layer_styles(self.name)
for style in layer_styles:
sld = MRAHandler.get_style(style['name'])
styles_sld.append(sld)
MRAHandler.del_layer(self.name)
MRAHandler.del_featuretype(
previous_ws_name, ds_name, self.name)
MRAHandler.get_or_create_workspace(organisation)
MRAHandler.get_or_create_datastore(ws_name, ds_name)
MRAHandler.get_or_create_featuretype(
ws_name, ds_name, self.name, enabled=True,
title=self.resource.title, abstract=self.resource.description)
for sld in styles_sld:
MRAHandler.create_or_update_style(self.name, data=sld)
MRAHandler.update_layer_defaultstyle(self.name, self.name)
break | [
"def",
"save_vector_layer",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"organisation",
"=",
"self",
".",
"resource",
".",
"dataset",
".",
"organisation",
"ws_name",
"=",
"organisation",
".",
"slug",
"ds_name",
"=",
"'public'",
"styles_sld",
"=",
"[",
"]",
"if",
"self",
".",
"pk",
":",
"try",
":",
"Layer",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"self",
".",
"pk",
")",
"except",
"Layer",
".",
"DoesNotExist",
":",
"pass",
"else",
":",
"# On vérifie si l'organisation du jeu de données a changée,",
"# auquel cas il est nécessaire de supprimer les objets MRA",
"# afin de les recréer dans le bon workspace (c-à-d Mapfile).",
"previous_layer",
"=",
"MRAHandler",
".",
"get_layer",
"(",
"self",
".",
"name",
")",
"regex",
"=",
"'/workspaces/(?P<ws_name>[a-z0-9_\\-]+)/datastores/'",
"matched",
"=",
"re",
".",
"search",
"(",
"regex",
",",
"previous_layer",
"[",
"'resource'",
"]",
"[",
"'href'",
"]",
")",
"if",
"matched",
":",
"previous_ws_name",
"=",
"matched",
".",
"group",
"(",
"'ws_name'",
")",
"if",
"not",
"ws_name",
"==",
"previous_ws_name",
":",
"layer_styles",
"=",
"MRAHandler",
".",
"get_layer_styles",
"(",
"self",
".",
"name",
")",
"for",
"style",
"in",
"layer_styles",
":",
"sld",
"=",
"MRAHandler",
".",
"get_style",
"(",
"style",
"[",
"'name'",
"]",
")",
"styles_sld",
".",
"append",
"(",
"sld",
")",
"MRAHandler",
".",
"del_layer",
"(",
"self",
".",
"name",
")",
"MRAHandler",
".",
"del_featuretype",
"(",
"previous_ws_name",
",",
"ds_name",
",",
"self",
".",
"name",
")",
"MRAHandler",
".",
"get_or_create_workspace",
"(",
"organisation",
")",
"MRAHandler",
".",
"get_or_create_datastore",
"(",
"ws_name",
",",
"ds_name",
")",
"MRAHandler",
".",
"get_or_create_featuretype",
"(",
"ws_name",
",",
"ds_name",
",",
"self",
".",
"name",
",",
"enabled",
"=",
"True",
",",
"title",
"=",
"self",
".",
"resource",
".",
"title",
",",
"abstract",
"=",
"self",
".",
"resource",
".",
"description",
")",
"for",
"sld",
"in",
"styles_sld",
":",
"MRAHandler",
".",
"create_or_update_style",
"(",
"self",
".",
"name",
",",
"data",
"=",
"sld",
")",
"MRAHandler",
".",
"update_layer_defaultstyle",
"(",
"self",
".",
"name",
",",
"self",
".",
"name",
")",
"break"
] | [
352,
4
] | [
394,
17
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
qr_decomposition_bidiag | (A, mode = "", graph_mode = False) | return Q, R | Décomposition QR d'une matrice bidiagonale.
Entrée:
A matrice bidiagonale.
Sortie:
Tuple (Q, R) des matrices de la décomposition.
| Décomposition QR d'une matrice bidiagonale.
Entrée:
A matrice bidiagonale.
Sortie:
Tuple (Q, R) des matrices de la décomposition.
| def qr_decomposition_bidiag(A, mode = "", graph_mode = False):
""" Décomposition QR d'une matrice bidiagonale.
Entrée:
A matrice bidiagonale.
Sortie:
Tuple (Q, R) des matrices de la décomposition.
"""
A = np.matrix(A, dtype='f')
N, M = A.shape
Q = np.eye(N, dtype='f')
R = A
for i in range(min(N, M)-1):
X = R[i:i+2, i]
z = np.zeros([2, 1])
if X[0, 0] > 0:
z[0, 0] = npl.norm(X)
else:
z[0, 0] = -npl.norm(X)
Q[:, i:i+2] = householder_product_right(X, z, Q[:, i:i+2])
R[i:i+2, i:i+2] = householder_product_left(X, z, R[i:i+2, i:i+2])
return Q, R | [
"def",
"qr_decomposition_bidiag",
"(",
"A",
",",
"mode",
"=",
"\"\"",
",",
"graph_mode",
"=",
"False",
")",
":",
"A",
"=",
"np",
".",
"matrix",
"(",
"A",
",",
"dtype",
"=",
"'f'",
")",
"N",
",",
"M",
"=",
"A",
".",
"shape",
"Q",
"=",
"np",
".",
"eye",
"(",
"N",
",",
"dtype",
"=",
"'f'",
")",
"R",
"=",
"A",
"for",
"i",
"in",
"range",
"(",
"min",
"(",
"N",
",",
"M",
")",
"-",
"1",
")",
":",
"X",
"=",
"R",
"[",
"i",
":",
"i",
"+",
"2",
",",
"i",
"]",
"z",
"=",
"np",
".",
"zeros",
"(",
"[",
"2",
",",
"1",
"]",
")",
"if",
"X",
"[",
"0",
",",
"0",
"]",
">",
"0",
":",
"z",
"[",
"0",
",",
"0",
"]",
"=",
"npl",
".",
"norm",
"(",
"X",
")",
"else",
":",
"z",
"[",
"0",
",",
"0",
"]",
"=",
"-",
"npl",
".",
"norm",
"(",
"X",
")",
"Q",
"[",
":",
",",
"i",
":",
"i",
"+",
"2",
"]",
"=",
"householder_product_right",
"(",
"X",
",",
"z",
",",
"Q",
"[",
":",
",",
"i",
":",
"i",
"+",
"2",
"]",
")",
"R",
"[",
"i",
":",
"i",
"+",
"2",
",",
"i",
":",
"i",
"+",
"2",
"]",
"=",
"householder_product_left",
"(",
"X",
",",
"z",
",",
"R",
"[",
"i",
":",
"i",
"+",
"2",
",",
"i",
":",
"i",
"+",
"2",
"]",
")",
"return",
"Q",
",",
"R"
] | [
42,
0
] | [
62,
12
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
gestion_consigne | (texte,url_device,nom_device, idx_cons_domoticz, cons_device,cde_name,cons_device_abais_eco=0,cons_domoticz_confort=0) | Compare les consignes de domoticz ancienne / actuelle / ainsi que celle du device
pour déterminer qui demande un changement de consigne
envoi le changement de consigne au device ou à Domoticz et inscrit un log
| Compare les consignes de domoticz ancienne / actuelle / ainsi que celle du device
pour déterminer qui demande un changement de consigne
envoi le changement de consigne au device ou à Domoticz et inscrit un log
| def gestion_consigne(texte,url_device,nom_device, idx_cons_domoticz, cons_device,cde_name,cons_device_abais_eco=0,cons_domoticz_confort=0):
''' Compare les consignes de domoticz ancienne / actuelle / ainsi que celle du device
pour déterminer qui demande un changement de consigne
envoi le changement de consigne au device ou à Domoticz et inscrit un log
'''
texte= texte.decode("utf-8")
idx_cons_domoticz= idx_cons_domoticz.encode("utf-8")
cons_domoticz_prec = var_restore('save_consigne_'+(nom_device.encode("utf-8"))+idx_cons_domoticz)
#Si Gestion di mode éco radiateur, on soustrait à la consigne confort (cons_device) , la consigne éco (cons_device_eco) :
if cons_device_abais_eco >0 :
cons_device_confort = cons_device # Sauvegarde consigne cozytouch confort
cons_device_eco = cons_device - cons_device_abais_eco # Calcul consigne cozytouch éco
cons_device = cons_device_eco # Application de la consigne éco pour le reste de la fonction
# Calcul de l'écart de consigne
# limitation consigne : la consigne n'accepte que des pas de 0,5°C
# si la partie décimale est égale à 0,5 on accepte, sinon on arrondit
cons_domoticz = domoticz_read_device_analog(idx_cons_domoticz)
e = int(cons_domoticz)
e = cons_domoticz - e
# si la partie décimale est différente de 0,5°C on arrondit
if e != 0.5:
cons_domoticz = round(cons_domoticz)
# comparaison avec la consigne en cours
if cons_device != cons_domoticz and cons_domoticz != cons_domoticz_prec and cons_domoticz_prec > 0:
# si un écart est détecté
# et si le changement de consigne vient de domoticz, on envoie le changement au device
# et si la consigne précédente est différente de 0 (cas au démarrage)
# Si Gestion du mode éco radiateur :
if cons_device_abais_eco > 0 :
# On fait consigne confort Domoticz - consigne éco demandée par Domoticz (Cozytouch demande l'écart entre les deux)
# On prend la consigne confort Domoticz pour le cas où l'on change les 2 consignes en meme temps
cons_domoticz_abais_eco = cons_domoticz_confort - cons_domoticz
# Valeur mini de l'écart de consigne = 2°C
if cons_domoticz_abais_eco < 2 :
cons_domoticz_abais_eco = 2 # Minimum 2°C
cons_domoticz = cons_domoticz - cons_domoticz_abais_eco # Ecriture de la consigne Domoticz
domoticz_write_device_analog(cons_domoticz,idx_cons_domoticz) # Mise à jour de la consigne Domoticz
domoticz_write_log(u'Cozytouch - '+nom_device+u' : consigne '+texte+u' : consigne doit etre 2°C en dessous de la consigne confort ! ')
print "consigne abaissement éco Domoticz " + str(cons_domoticz_abais_eco)
cozytouch_POST(url_device,cde_name,cons_domoticz_abais_eco) # Envoi de la consigne limitée à Cozytouch
var_save(cons_domoticz, ('save_consigne_'+(nom_device.encode("utf-8"))+idx_cons_domoticz)) # Sauvegarde consigne domoticz
else :
cozytouch_POST(url_device,cde_name,cons_domoticz)
var_save(cons_domoticz, ('save_consigne_'+(nom_device.encode("utf-8"))+idx_cons_domoticz))
domoticz_write_log(u'Cozytouch - '+nom_device+u' : nouvelle consigne '+texte+u' transmise: '+str(cons_domoticz)+u'°C')
if debug:
print('Fonction gestion_consigne : Chgt consigne Domoticz, envoie vers Cozytouch : '+(nom_device.encode("utf-8"))+'/'+(texte.encode("utf-8"))+'/'+str(cons_domoticz)+'°C')
elif cons_device != cons_domoticz and cons_domoticz == cons_domoticz_prec and cons_domoticz_prec > 0:
# sinon, le changement vient du device Cozytouch
# mise à jour de domoticz
if debug:
print('Fonction gestion_consigne : Chgt consigne Cozytouch, envoie vers Domoticz : '+(nom_device.encode("utf-8"))+'/'+(texte.encode("utf-8"))+'/'+str(cons_device)+'°C')
# Si Gestion du mode éco radiateur :
domoticz_write_log(u'Cozytouch - '+nom_device+u' : detection changement consigne ' +texte+' : '+str(cons_device)+u'°C')
domoticz_write_device_analog(cons_device,idx_cons_domoticz)
var_save(cons_device, ('save_consigne_'+(nom_device.encode("utf-8"))+idx_cons_domoticz))
else :
# ou simple rafraichissement domoticz si aucun changement
if debug:
print('Fonction gestion_consigne : Rafraichissement consigne : '+(nom_device.encode("utf-8"))+'/'+(texte.encode("utf-8"))+'/'+str(cons_device)+'°C')
domoticz_write_device_analog(cons_device,idx_cons_domoticz)
var_save(cons_device, ('save_consigne_'+(nom_device.encode("utf-8"))+idx_cons_domoticz)) | [
"def",
"gestion_consigne",
"(",
"texte",
",",
"url_device",
",",
"nom_device",
",",
"idx_cons_domoticz",
",",
"cons_device",
",",
"cde_name",
",",
"cons_device_abais_eco",
"=",
"0",
",",
"cons_domoticz_confort",
"=",
"0",
")",
":",
"texte",
"=",
"texte",
".",
"decode",
"(",
"\"utf-8\"",
")",
"idx_cons_domoticz",
"=",
"idx_cons_domoticz",
".",
"encode",
"(",
"\"utf-8\"",
")",
"cons_domoticz_prec",
"=",
"var_restore",
"(",
"'save_consigne_'",
"+",
"(",
"nom_device",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"idx_cons_domoticz",
")",
"#Si Gestion di mode éco radiateur, on soustrait à la consigne confort (cons_device) , la consigne éco (cons_device_eco) :",
"if",
"cons_device_abais_eco",
">",
"0",
":",
"cons_device_confort",
"=",
"cons_device",
"# Sauvegarde consigne cozytouch confort",
"cons_device_eco",
"=",
"cons_device",
"-",
"cons_device_abais_eco",
"# Calcul consigne cozytouch éco",
"cons_device",
"=",
"cons_device_eco",
"# Application de la consigne éco pour le reste de la fonction",
"# Calcul de l'écart de consigne",
"# limitation consigne : la consigne n'accepte que des pas de 0,5°C",
"# si la partie décimale est égale à 0,5 on accepte, sinon on arrondit",
"cons_domoticz",
"=",
"domoticz_read_device_analog",
"(",
"idx_cons_domoticz",
")",
"e",
"=",
"int",
"(",
"cons_domoticz",
")",
"e",
"=",
"cons_domoticz",
"-",
"e",
"# si la partie décimale est différente de 0,5°C on arrondit",
"if",
"e",
"!=",
"0.5",
":",
"cons_domoticz",
"=",
"round",
"(",
"cons_domoticz",
")",
"# comparaison avec la consigne en cours",
"if",
"cons_device",
"!=",
"cons_domoticz",
"and",
"cons_domoticz",
"!=",
"cons_domoticz_prec",
"and",
"cons_domoticz_prec",
">",
"0",
":",
"# si un écart est détecté",
"# et si le changement de consigne vient de domoticz, on envoie le changement au device",
"# et si la consigne précédente est différente de 0 (cas au démarrage)",
"# Si Gestion du mode éco radiateur :",
"if",
"cons_device_abais_eco",
">",
"0",
":",
"# On fait consigne confort Domoticz - consigne éco demandée par Domoticz (Cozytouch demande l'écart entre les deux)",
"# On prend la consigne confort Domoticz pour le cas où l'on change les 2 consignes en meme temps",
"cons_domoticz_abais_eco",
"=",
"cons_domoticz_confort",
"-",
"cons_domoticz",
"# Valeur mini de l'écart de consigne = 2°C",
"if",
"cons_domoticz_abais_eco",
"<",
"2",
":",
"cons_domoticz_abais_eco",
"=",
"2",
"# Minimum 2°C",
"cons_domoticz",
"=",
"cons_domoticz",
"-",
"cons_domoticz_abais_eco",
"# Ecriture de la consigne Domoticz",
"domoticz_write_device_analog",
"(",
"cons_domoticz",
",",
"idx_cons_domoticz",
")",
"# Mise à jour de la consigne Domoticz",
"domoticz_write_log",
"(",
"u'Cozytouch - '",
"+",
"nom_device",
"+",
"u' : consigne '",
"+",
"texte",
"+",
"u' : consigne doit etre 2°C en dessous de la consigne confort ! ')",
"",
"print",
"\"consigne abaissement éco Domoticz \" ",
" ",
"tr(",
"c",
"ons_domoticz_abais_eco)",
"",
"cozytouch_POST",
"(",
"url_device",
",",
"cde_name",
",",
"cons_domoticz_abais_eco",
")",
"# Envoi de la consigne limitée à Cozytouch",
"var_save",
"(",
"cons_domoticz",
",",
"(",
"'save_consigne_'",
"+",
"(",
"nom_device",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"idx_cons_domoticz",
")",
")",
"# Sauvegarde consigne domoticz",
"else",
":",
"cozytouch_POST",
"(",
"url_device",
",",
"cde_name",
",",
"cons_domoticz",
")",
"var_save",
"(",
"cons_domoticz",
",",
"(",
"'save_consigne_'",
"+",
"(",
"nom_device",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"idx_cons_domoticz",
")",
")",
"domoticz_write_log",
"(",
"u'Cozytouch - '",
"+",
"nom_device",
"+",
"u' : nouvelle consigne '",
"+",
"texte",
"+",
"u' transmise: '",
"+",
"str",
"(",
"cons_domoticz",
")",
"+",
"u'°C')",
"",
"if",
"debug",
":",
"print",
"(",
"'Fonction gestion_consigne : Chgt consigne Domoticz, envoie vers Cozytouch : '",
"+",
"(",
"nom_device",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"'/'",
"+",
"(",
"texte",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"'/'",
"+",
"str",
"(",
"cons_domoticz",
")",
"+",
"'°C')",
"",
"elif",
"cons_device",
"!=",
"cons_domoticz",
"and",
"cons_domoticz",
"==",
"cons_domoticz_prec",
"and",
"cons_domoticz_prec",
">",
"0",
":",
"# sinon, le changement vient du device Cozytouch",
"# mise à jour de domoticz",
"if",
"debug",
":",
"print",
"(",
"'Fonction gestion_consigne : Chgt consigne Cozytouch, envoie vers Domoticz : '",
"+",
"(",
"nom_device",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"'/'",
"+",
"(",
"texte",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"'/'",
"+",
"str",
"(",
"cons_device",
")",
"+",
"'°C')",
"",
"# Si Gestion du mode éco radiateur :",
"domoticz_write_log",
"(",
"u'Cozytouch - '",
"+",
"nom_device",
"+",
"u' : detection changement consigne '",
"+",
"texte",
"+",
"' : '",
"+",
"str",
"(",
"cons_device",
")",
"+",
"u'°C')",
"",
"domoticz_write_device_analog",
"(",
"cons_device",
",",
"idx_cons_domoticz",
")",
"var_save",
"(",
"cons_device",
",",
"(",
"'save_consigne_'",
"+",
"(",
"nom_device",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"idx_cons_domoticz",
")",
")",
"else",
":",
"# ou simple rafraichissement domoticz si aucun changement",
"if",
"debug",
":",
"print",
"(",
"'Fonction gestion_consigne : Rafraichissement consigne : '",
"+",
"(",
"nom_device",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"'/'",
"+",
"(",
"texte",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"'/'",
"+",
"str",
"(",
"cons_device",
")",
"+",
"'°C')",
"",
"domoticz_write_device_analog",
"(",
"cons_device",
",",
"idx_cons_domoticz",
")",
"var_save",
"(",
"cons_device",
",",
"(",
"'save_consigne_'",
"+",
"(",
"nom_device",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"+",
"idx_cons_domoticz",
")",
")"
] | [
1067,
0
] | [
1138,
96
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Crud.get_table_views | (self) | return self.application["tables"][self.ctx["table_id"]]["views"] | Obtenir la liste des vues de la table courante | Obtenir la liste des vues de la table courante | def get_table_views(self):
""" Obtenir la liste des vues de la table courante """
return self.application["tables"][self.ctx["table_id"]]["views"] | [
"def",
"get_table_views",
"(",
"self",
")",
":",
"return",
"self",
".",
"application",
"[",
"\"tables\"",
"]",
"[",
"self",
".",
"ctx",
"[",
"\"table_id\"",
"]",
"]",
"[",
"\"views\"",
"]"
] | [
466,
4
] | [
468,
72
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
OrganisationShow.put | (self, request, organisation_name) | return HttpResponse(status=204) | Mettre à jour l'organisation. | Mettre à jour l'organisation. | def put(self, request, organisation_name):
"""Mettre à jour l'organisation."""
request.PUT, request._files = parse_request(request)
request.PUT._mutable = True
if not request.user.profile.is_admin:
raise Http404()
try:
handle_pust_request(request, organisation_name=organisation_name)
except Http404:
raise Http404()
except GenericException as e:
return JsonResponse({'error': e.details}, status=400)
return HttpResponse(status=204) | [
"def",
"put",
"(",
"self",
",",
"request",
",",
"organisation_name",
")",
":",
"request",
".",
"PUT",
",",
"request",
".",
"_files",
"=",
"parse_request",
"(",
"request",
")",
"request",
".",
"PUT",
".",
"_mutable",
"=",
"True",
"if",
"not",
"request",
".",
"user",
".",
"profile",
".",
"is_admin",
":",
"raise",
"Http404",
"(",
")",
"try",
":",
"handle_pust_request",
"(",
"request",
",",
"organisation_name",
"=",
"organisation_name",
")",
"except",
"Http404",
":",
"raise",
"Http404",
"(",
")",
"except",
"GenericException",
"as",
"e",
":",
"return",
"JsonResponse",
"(",
"{",
"'error'",
":",
"e",
".",
"details",
"}",
",",
"status",
"=",
"400",
")",
"return",
"HttpResponse",
"(",
"status",
"=",
"204",
")"
] | [
158,
4
] | [
171,
39
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
nCk | (n, k) | return math.factorial(n) // math.factorial(k) // math.factorial(n - k) | coefficient binomial (ou nombre de combinaisons) | coefficient binomial (ou nombre de combinaisons) | def nCk(n, k):
""" coefficient binomial (ou nombre de combinaisons) """
if n < k:
return 0
return math.factorial(n) // math.factorial(k) // math.factorial(n - k) | [
"def",
"nCk",
"(",
"n",
",",
"k",
")",
":",
"if",
"n",
"<",
"k",
":",
"return",
"0",
"return",
"math",
".",
"factorial",
"(",
"n",
")",
"//",
"math",
".",
"factorial",
"(",
"k",
")",
"//",
"math",
".",
"factorial",
"(",
"n",
"-",
"k",
")"
] | [
22,
0
] | [
26,
74
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
nrows_ncols | (N) | return nrows, ncols | (nrows, ncols) pour créer un subplots de N figures avec les bonnes dimensions. | (nrows, ncols) pour créer un subplots de N figures avec les bonnes dimensions. | def nrows_ncols(N):
"""(nrows, ncols) pour créer un subplots de N figures avec les bonnes dimensions."""
nrows = int(np.ceil(np.sqrt(N)))
ncols = N // nrows
while N > nrows * ncols:
ncols += 1
nrows, ncols = max(nrows, ncols), min(nrows, ncols)
return nrows, ncols | [
"def",
"nrows_ncols",
"(",
"N",
")",
":",
"nrows",
"=",
"int",
"(",
"np",
".",
"ceil",
"(",
"np",
".",
"sqrt",
"(",
"N",
")",
")",
")",
"ncols",
"=",
"N",
"//",
"nrows",
"while",
"N",
">",
"nrows",
"*",
"ncols",
":",
"ncols",
"+=",
"1",
"nrows",
",",
"ncols",
"=",
"max",
"(",
"nrows",
",",
"ncols",
")",
",",
"min",
"(",
"nrows",
",",
"ncols",
")",
"return",
"nrows",
",",
"ncols"
] | [
188,
0
] | [
195,
23
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
calculrayoncourbure | (cible) | return(R) | calcule le rayon de courbure necessaire à rejoidre cible depuis zero en ne prenant comme direction de v la direction dans laquelle pointe le véhicule | calcule le rayon de courbure necessaire à rejoidre cible depuis zero en ne prenant comme direction de v la direction dans laquelle pointe le véhicule | def calculrayoncourbure(cible):
"calcule le rayon de courbure necessaire à rejoidre cible depuis zero en ne prenant comme direction de v la direction dans laquelle pointe le véhicule"
xp=cible[0]
yp=cible[1]
if yp!=0:
K=-xp/yp #la pente de la droite ortho à O cible"
C=yp/2-K*xp/2
yo=K*0+C #intersection entre la droite portée par le rayon issu de O et la mediatrice de OCible se coupent en O et la droite portée par le rayon issu de O est d'équation x=0"
if yp==0:
yo=10000
R=yo
return(R) | [
"def",
"calculrayoncourbure",
"(",
"cible",
")",
":",
"xp",
"=",
"cible",
"[",
"0",
"]",
"yp",
"=",
"cible",
"[",
"1",
"]",
"if",
"yp",
"!=",
"0",
":",
"K",
"=",
"-",
"xp",
"/",
"yp",
"#la pente de la droite ortho à O cible\"\r",
"C",
"=",
"yp",
"/",
"2",
"-",
"K",
"*",
"xp",
"/",
"2",
"yo",
"=",
"K",
"*",
"0",
"+",
"C",
"#intersection entre la droite portée par le rayon issu de O et la mediatrice de OCible se coupent en O et la droite portée par le rayon issu de O est d'équation x=0\"\r",
"if",
"yp",
"==",
"0",
":",
"yo",
"=",
"10000",
"R",
"=",
"yo",
"return",
"(",
"R",
")"
] | [
2,
0
] | [
15,
13
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
delete_rows_wednesday | (df) | return df[df["jour"] != "Mercredi"] | Cette fonction renvoie une dataframe débarassée des observations des mercredis. | Cette fonction renvoie une dataframe débarassée des observations des mercredis. | def delete_rows_wednesday(df):
"""Cette fonction renvoie une dataframe débarassée des observations des mercredis."""
return df[df["jour"] != "Mercredi"] | [
"def",
"delete_rows_wednesday",
"(",
"df",
")",
":",
"return",
"df",
"[",
"df",
"[",
"\"jour\"",
"]",
"!=",
"\"Mercredi\"",
"]"
] | [
58,
0
] | [
60,
39
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
successeurs | (m, s) | return succ | Renvoie les successeurs du sommet s de la matrice d'adjacence m.
Les successeurs se lisent sur la ligne s de m.
| Renvoie les successeurs du sommet s de la matrice d'adjacence m.
Les successeurs se lisent sur la ligne s de m.
| def successeurs(m, s):
"""Renvoie les successeurs du sommet s de la matrice d'adjacence m.
Les successeurs se lisent sur la ligne s de m.
"""
succ = []
for j in range(len(m[s])):
if m[s][j] == 1:
succ.append(j)
return succ | [
"def",
"successeurs",
"(",
"m",
",",
"s",
")",
":",
"succ",
"=",
"[",
"]",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"m",
"[",
"s",
"]",
")",
")",
":",
"if",
"m",
"[",
"s",
"]",
"[",
"j",
"]",
"==",
"1",
":",
"succ",
".",
"append",
"(",
"j",
")",
"return",
"succ"
] | [
19,
0
] | [
29,
15
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Vecteur.__add__ | (self, p) | return Vecteur(self.x + p.x, self.y + p.y, self.z + p.z) | addition de deux points | addition de deux points | def __add__(self, p):
"""addition de deux points"""
return Vecteur(self.x + p.x, self.y + p.y, self.z + p.z) | [
"def",
"__add__",
"(",
"self",
",",
"p",
")",
":",
"return",
"Vecteur",
"(",
"self",
".",
"x",
"+",
"p",
".",
"x",
",",
"self",
".",
"y",
"+",
"p",
".",
"y",
",",
"self",
".",
"z",
"+",
"p",
".",
"z",
")"
] | [
21,
4
] | [
23,
64
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
peupler_eleves | (cur, idEleve, fichierEleve) | return idEleve | On peuple la base eleve à partir du fichier csv fichierEleve
idEleve est l'identifiant du premier élève | On peuple la base eleve à partir du fichier csv fichierEleve
idEleve est l'identifiant du premier élève | def peupler_eleves(cur, idEleve, fichierEleve):
"""On peuple la base eleve à partir du fichier csv fichierEleve
idEleve est l'identifiant du premier élève"""
f = open(fichierEleve,'r')
csvEleve = csv.DictReader(f, delimiter=';')
for eleve in csvEleve :
cur.execute("INSERT INTO eleve(idEleve, idLycee, login, password, nom, prenom, anneeNaissance, note1, note2) VALUES (?,?,?,?,?,?,?,?,?)",
(idEleve, eleve['idLycee'], eleve['login'], eleve['password'], eleve['nom'], eleve['prenom'],
eleve['naissance'], eleve['note1'], eleve['note2'] ) )
idEleve += 1
f.close()
return idEleve | [
"def",
"peupler_eleves",
"(",
"cur",
",",
"idEleve",
",",
"fichierEleve",
")",
":",
"f",
"=",
"open",
"(",
"fichierEleve",
",",
"'r'",
")",
"csvEleve",
"=",
"csv",
".",
"DictReader",
"(",
"f",
",",
"delimiter",
"=",
"';'",
")",
"for",
"eleve",
"in",
"csvEleve",
":",
"cur",
".",
"execute",
"(",
"\"INSERT INTO eleve(idEleve, idLycee, login, password, nom, prenom, anneeNaissance, note1, note2) VALUES (?,?,?,?,?,?,?,?,?)\"",
",",
"(",
"idEleve",
",",
"eleve",
"[",
"'idLycee'",
"]",
",",
"eleve",
"[",
"'login'",
"]",
",",
"eleve",
"[",
"'password'",
"]",
",",
"eleve",
"[",
"'nom'",
"]",
",",
"eleve",
"[",
"'prenom'",
"]",
",",
"eleve",
"[",
"'naissance'",
"]",
",",
"eleve",
"[",
"'note1'",
"]",
",",
"eleve",
"[",
"'note2'",
"]",
")",
")",
"idEleve",
"+=",
"1",
"f",
".",
"close",
"(",
")",
"return",
"idEleve"
] | [
27,
0
] | [
38,
18
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Admin.send_faq | (self, ctx: MyContext) | Envoie les messages du salon <#541228784456695818> vers le salon <#508028818154323980> | Envoie les messages du salon <#541228784456695818> vers le salon <#508028818154323980> | async def send_faq(self, ctx: MyContext):
"""Envoie les messages du salon <#541228784456695818> vers le salon <#508028818154323980>"""
msg = await ctx.send("Suppression des salons...")
destination_fr = ctx.guild.get_channel(508028818154323980)
destination_en = ctx.guild.get_channel(541599345972346881)
chan_fr = ctx.guild.get_channel(541228784456695818)
chan_en = ctx.guild.get_channel(541599226623426590)
role_fr = ctx.guild.get_role(541224634087899146)
role_en = ctx.guild.get_role(537597687801839617)
await destination_fr.set_permissions(role_fr, read_messages=False)
await destination_en.set_permissions(role_en, read_messages=False)
await destination_fr.purge()
await destination_en.purge()
await msg.edit(content="Envoi des messages...")
async for message in chan_fr.history(limit=200,oldest_first=True):
await destination_fr.send(message.content)
async for message in chan_en.history(limit=200,oldest_first=True):
await destination_en.send(message.content)
await destination_fr.set_permissions(role_fr, read_messages=True)
await destination_en.set_permissions(role_en, read_messages=True)
await msg.edit(content="Terminé !")
await ctx.bot.get_cog('Utilities').add_check_reaction(ctx.message) | [
"async",
"def",
"send_faq",
"(",
"self",
",",
"ctx",
":",
"MyContext",
")",
":",
"msg",
"=",
"await",
"ctx",
".",
"send",
"(",
"\"Suppression des salons...\"",
")",
"destination_fr",
"=",
"ctx",
".",
"guild",
".",
"get_channel",
"(",
"508028818154323980",
")",
"destination_en",
"=",
"ctx",
".",
"guild",
".",
"get_channel",
"(",
"541599345972346881",
")",
"chan_fr",
"=",
"ctx",
".",
"guild",
".",
"get_channel",
"(",
"541228784456695818",
")",
"chan_en",
"=",
"ctx",
".",
"guild",
".",
"get_channel",
"(",
"541599226623426590",
")",
"role_fr",
"=",
"ctx",
".",
"guild",
".",
"get_role",
"(",
"541224634087899146",
")",
"role_en",
"=",
"ctx",
".",
"guild",
".",
"get_role",
"(",
"537597687801839617",
")",
"await",
"destination_fr",
".",
"set_permissions",
"(",
"role_fr",
",",
"read_messages",
"=",
"False",
")",
"await",
"destination_en",
".",
"set_permissions",
"(",
"role_en",
",",
"read_messages",
"=",
"False",
")",
"await",
"destination_fr",
".",
"purge",
"(",
")",
"await",
"destination_en",
".",
"purge",
"(",
")",
"await",
"msg",
".",
"edit",
"(",
"content",
"=",
"\"Envoi des messages...\"",
")",
"async",
"for",
"message",
"in",
"chan_fr",
".",
"history",
"(",
"limit",
"=",
"200",
",",
"oldest_first",
"=",
"True",
")",
":",
"await",
"destination_fr",
".",
"send",
"(",
"message",
".",
"content",
")",
"async",
"for",
"message",
"in",
"chan_en",
".",
"history",
"(",
"limit",
"=",
"200",
",",
"oldest_first",
"=",
"True",
")",
":",
"await",
"destination_en",
".",
"send",
"(",
"message",
".",
"content",
")",
"await",
"destination_fr",
".",
"set_permissions",
"(",
"role_fr",
",",
"read_messages",
"=",
"True",
")",
"await",
"destination_en",
".",
"set_permissions",
"(",
"role_en",
",",
"read_messages",
"=",
"True",
")",
"await",
"msg",
".",
"edit",
"(",
"content",
"=",
"\"Terminé !\")",
"",
"await",
"ctx",
".",
"bot",
".",
"get_cog",
"(",
"'Utilities'",
")",
".",
"add_check_reaction",
"(",
"ctx",
".",
"message",
")"
] | [
121,
4
] | [
142,
74
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
PrivateUSERApiTest.test_update_user_profile | (self) | verifie que l'utilisateur meut mettre a jour son compte | verifie que l'utilisateur meut mettre a jour son compte | def test_update_user_profile(self):
"""verifie que l'utilisateur meut mettre a jour son compte"""
payload = {'name': 'new name', 'password': '12334554463'}
res = self.client.patch(ME_URL, payload)
self.user.refresh_from_db()
self.assertEqual(self.user.name, payload['name'])
self.assertTrue(self.user.check_password(payload['password']))
self.assertEqual(res.status_code, status.HTTP_200_OK) | [
"def",
"test_update_user_profile",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'name'",
":",
"'new name'",
",",
"'password'",
":",
"'12334554463'",
"}",
"res",
"=",
"self",
".",
"client",
".",
"patch",
"(",
"ME_URL",
",",
"payload",
")",
"self",
".",
"user",
".",
"refresh_from_db",
"(",
")",
"self",
".",
"assertEqual",
"(",
"self",
".",
"user",
".",
"name",
",",
"payload",
"[",
"'name'",
"]",
")",
"self",
".",
"assertTrue",
"(",
"self",
".",
"user",
".",
"check_password",
"(",
"payload",
"[",
"'password'",
"]",
")",
")",
"self",
".",
"assertEqual",
"(",
"res",
".",
"status_code",
",",
"status",
".",
"HTTP_200_OK",
")"
] | [
120,
4
] | [
128,
61
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
maj_device | (data,name,p,x) | Fonction de mise à jour du device dans Domoticz
| Fonction de mise à jour du device dans Domoticz
| def maj_device(data,name,p,x):
''' Fonction de mise à jour du device dans Domoticz
'''
print("Mise a jour device "+str(p)+" : "+name)
a = var_restore('save_devices')
classe = a[p]
''' Mise à jour : Données radiateur
'''
if name == dict_cozytouch_devtypes.get(u'module fil pilote') or name == dict_cozytouch_devtypes.get(u'radiateur') :
# Switch selecteur mode OFF / Manuel / Auto
gestion_switch_selector_domoticz ((value_by_name(data,x,u'io:TargetHeatingLevelState')),classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_switch_level'),
state_cozytouch_on_off=((value_by_name(data,x,u'core:OperatingModeState'))), command_off_activate = True,
level_0=u'off',level_10=u'frostprotection',level_20=u'eco',level_30=u'comfort-2',level_40=u'comfort-1',level_50=u'comfort',setting_command_mode=u'setHeatingLevel')
if name == dict_cozytouch_devtypes.get(u'radiateur') :
# Switch selecteur mode ordre radiateur OFF / Hors gel / Eco / Confort -2 / Confort -2 / Confort
# pas d'écriture possible depuis domoticz pour un radiateur connecté, l'ordre est imposé par le fil pilote ou le mode de programmation interne de l'appareil
# Lecture de l'ordre en cours sur le raditateur :
ordre_radiateur = (value_by_name(data,x,u'io:TargetHeatingLevelState'))
print ordre_radiateur
#Lecture de l'état de fonctionnement du radiateur :
mode_radiateur=(value_by_name(data,x,u'core:OperatingModeState'))
print mode_radiateur
# Switch selecteur mode OFF / Manuel / Auto
gestion_switch_selector_domoticz (value_by_name(data,x,u'core:OperatingModeState'),classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_switch_mode'),
level_0=u'standby',level_10=u'basic',level_20=u'internal',level_30=u'Derogation',setting_command_mode=u'setOperatingMode')
# Mesure température : Device : TemperatureSensor, Parametre 1 : core:TemperatureState
domoticz_write_device_analog((value_by_name(data,(x+1),u'core:TemperatureState')),(classe.get(u'idx_mesure_temp')))
# Consigne de température confort : Device : AtlanticElectricalHeaterWithAdjustableTemperatureSetpointIOComponent, Parametre 9 : core:ComfortRoomTemperatureState
gestion_consigne(u'confort',classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_cons_temp_confort'),value_by_name(data,x,u'core:ComfortRoomTemperatureState'),(u'setComfortTemperature'))
# Consigne de témpérature éco : Device : AtlanticElectricalHeaterWithAdjustableTemperatureSetpointIOComponent, Parametre 10: core:EcoRoomTemperatureState
gestion_consigne(u'eco',classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_cons_temp_eco'),value_by_name(data,x,'core:ComfortRoomTemperatureState') ,u'setSetpointLoweringTemperatureInProgMode',
cons_device_abais_eco = value_by_name(data,x,u'io:SetpointLoweringTemperatureInProgModeState'), # lecture de la consigne éco appliquée par Cozytouch
cons_domoticz_confort = domoticz_read_device_analog(classe.get(u'idx_cons_temp_confort'))) # lecture de la consigne confort appliquée dans Domoticz
# Compteur d'énergie: Device : CumulativeElectricPowerConsumptionSensor, Parametre 1 : core:ElectricEnergyConsumptionState
domoticz_write_device_analog((value_by_name(data,x+4,u'core:ElectricEnergyConsumptionState')),(classe.get(u'idx_compteur')))
''' Mise à jour : Données chauffe eau
'''
if name == dict_cozytouch_devtypes.get('chauffe eau'):
# Switch on/off
on_off = (value_by_name(data,x,"io:OperatingModeCapabilitiesState")[u'energyDemandStatus'])
if on_off == 1 :
on_off = 'On'
else:
on_off = 'Off'
# Comparaison avec l'état précédent pour mettre à jour uniquement sur changement (évite de remplir les logs inutilement)
onoff_prec = var_restore('save_onoff_'+str(classe.get('idx_on_off')))
if onoff_prec != on_off :
domoticz_write_device_switch_onoff(on_off,(classe.get('idx_on_off')))
var_save(on_off, ('save_onoff_'+str(classe.get('idx_on_off'))))
# Switch selecteur auto/manu/manu+eco : définition des levels du switch
auto_manu = value_by_name(data,x,"io:DHWModeState")
if auto_manu == 'autoMode':
switch = 0
if auto_manu == 'manualEcoInactive':
switch = 10
if auto_manu == 'manualEcoActive':
switch = 20
# Switch selecteur :
# Comparaison avec l'état précédent pour mettre à jour uniquement sur changement (évite de remplir les logs inutilement)
switch_prec = var_restore('save_switch_'+str(classe.get('idx_switch_auto_manu')))
if switch_prec != switch :
domoticz_write_device_switch_selector(switch, classe.get('idx_switch_auto_manu'))
var_save(switch, ('save_switch_'+str(classe.get('idx_switch_auto_manu'))))
# Mesure température :
domoticz_write_device_analog((value_by_name(data,x,"core:TemperatureState")),(classe.get('idx_mesure_temp')))
# Compteur d'eau chaude restante :
domoticz_write_device_analog(value_by_name(data,x,"core:WaterConsumptionState"),(classe.get('idx_conso_eau')))
# Calcul puissance moyenne :
wh_prec = var_restore('wh_prec_'+str(classe.get('idx_compteur')))
wh_actuel = value_by_name(data,x+1,'core:ElectricEnergyConsumptionState')
wh_1min = wh_actuel - wh_prec
Pmoy_1min = wh_1min * 60
var_save(wh_actuel, ('wh_prec_'+str(classe.get('idx_compteur'))))
# Compteur d'énergie:
domoticz_write_device_analog(str(Pmoy_1min)+';'+str(wh_actuel),(classe.get('idx_compteur')))
# Compteur temps de fonctionnement pompe à chaleur :
domoticz_write_device_analog((value_by_name(data,x,"io:HeatPumpOperatingTimeState")),(classe.get('idx_compteur_pompe')))
''' Mise à jour : Données PAC
'''
if name == dict_cozytouch_devtypes.get(u'PAC main control') :
# MAJ données générales PAC
# Lecture du mode stop/heating/cooling/drying :
global mode_PAC
mode_PAC = (value_by_name(data,x,u'io:PassAPCOperatingModeState'))
# Lecture du mode auto : Remplacement variable mode par 'auto'
if value_by_name(data,x,u'core:HeatingCoolingAutoSwitchState')== u'on':
mode_PAC = u'auto'
# Gestion du sélecteur :
# Voir comment gérer la demande de passage en mode auto, il faut adresser une commande "setHeatingCoolingAutoSwitch" au changement du label u'auto'
# BLOC MODIFIE POUR ENVOI D ELA COMMANDE SETHEATINGCOLLINGAUTOSWITCH MAIS IL FAUT ENVOYER UN 'ON' OU UN 'OFF' PAS LE LABEL 40 'AUTO'
gestion_switch_selector_domoticz (mode_PAC,classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_switch_mode'),
level_0='stop',level_10='heating',level_20='cooling',level_30='drying',level_40='auto',setting_command_mode='setPassAPCOperatingMode',
special_level = 'auto',special_setting='setHeatingCoolingAutoSwitch',special_setting_parameter_on='on',special_setting_parameter_off='off')
if name == dict_cozytouch_devtypes.get('PAC zone control') :
# MAJ données zone PAC
# Mesure température :
domoticz_write_device_analog(value_by_name(data,(x+1),u'core:TemperatureState'),classe.get(u'idx_mesure_temp'))
# Consigne température Confort en mode chauffage en mode programmation : (core:ComfortHeatingTargetTemperatureState)
gestion_consigne(u'Confort chauff.',classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_cons_temp_confort_chauffage'),value_by_name(data,x,u'core:ComfortHeatingTargetTemperatureState'),(u'setComfortHeatingTargetTemperature'))
# Consigne température Confort mode climatisation en mode programmation : (core:ComfortCoolingTargetTemperatureState)
gestion_consigne(u'Confort rafraich.',classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_cons_temp_confort_clim'),value_by_name(data,x,u'core:ComfortCoolingTargetTemperatureState'),(u'setComfortCoolingTargetTemperature'))
# Consigne température Eco mode chauffage en mode programmation : (core:EcoHeatingTargetTemperatureState)
gestion_consigne(u'Eco chauff.',classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_cons_temp_eco_chauffage'),value_by_name(data,x,u'core:EcoHeatingTargetTemperatureState'),(u'setEcoHeatingTargetTemperature'))
# Consigne température Confort mode climatisation en mode programmation : (core:EcoCoolingTargetTemperatureState)
gestion_consigne(u'Eco rafraich.',classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_cons_temp_eco_clim'),value_by_name(data,x,u'core:EcoCoolingTargetTemperatureState'),(u'setEcoCoolingTargetTemperature'))
# Switch selecteur mode OFF / Manuel / Auto
# dépendant du mode en cours de la Zone Control pour le mode Manuel
# Si zone Control en mode 'Heating' :
if mode_PAC == u'heating' :
# Gestion consigne en mode manuel : Seeting consigne en mode 'heating'
setting_consigne_zone = u'setHeatingTargetTemperature'
# Gestion switch sélecteur : Prise en compte du mode de fonctionnement de la zone control suivant le paramètre de fonctionnement en mode 'heating'
state_mode_zone = value_by_name(data,x,u'io:PassAPCHeatingModeState')
# Gestion switch sélecteur : Setting mode en mode 'heating'
setting_command_mode_zone = u'setPassAPCHeatingMode'
# Gestion switch sélecteur : Setting mode 'off' en mode 'heating'
setting_command_on_off_mode_zone = u'setHeatingOnOffState'
# Gestion switch sélecteur : Prise en compte de l'état de la zone (manu, comfort, eco...)
state_zone = value_by_name(data,x,u'io:PassAPCHeatingProfileState')
# Gestion switch sélecteur : Prise en compte de l'état on/off de la zone
state_on_off_zone = value_by_name(data,x,u'core:HeatingOnOffState')
# Gestion de la consigne manuel suivant l'état de fonctionnement de la PAC (heating ou cooling)
# Consigne température en mode manu : (setCoolingTargetTemperature en mode manuel refroidissement / setHeatingTargetTemperature en mode manuel chauffage)
gestion_consigne(u'Manuel',classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_cons_temp_manu'),value_by_name(data,x,u'core:TargetTemperatureState'),setting_consigne_zone)
# Gestion switch sélecteur :
return_switch = gestion_switch_selector_domoticz (state_mode_zone ,classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_switch_mode'),
state_cozytouch_on_off = state_on_off_zone,
command_off_activate= True, setting_command_on_off=setting_command_on_off_mode_zone, setting_parameter_off=u'off',
command_on_activate=True, setting_parameter_on=u'on',
level_0=u'stop',level_10=u'manu',level_20=u'internalScheduling',setting_command_mode=setting_command_mode_zone)
# Evaluation du retour de la fonction, si cas n°2, on a envoyé un changement vers Cozytouch
# On renvoi dans tous les cas de changement de mode vers Cozytouch la consigne manuel
if return_switch == 1 :
# Renvoi de la consigne de T°C manuel lors d'une changement de mode vers manuel (sinon sans cela, la consigne passe à 8°C, mystère Cozytouch)
cozytouch_POST(classe.get(u'url'),setting_consigne_zone,+domoticz_read_device_analog(classe.get(u'idx_cons_temp_manu')))
# Si zone Control en mode 'Cooling' :
elif mode_PAC == u'cooling':
# Gestion consigne en mode manuel : Setting consigne en mode 'heating'
setting_consigne_zone = u'setCoolingTargetTemperature'
# Gestion switch sélecteur : Prise en compte du mode de fonctionnement de la zone control suivant le paramètre de fonctionnement en mode 'cooling'
state_mode_zone = value_by_name(data,x,u'io:PassAPCCoolingModeState')
# Gestion switch sélecteur : Setting mode en mode 'cooling'
setting_command_mode_zone = u'setPassAPCCoolingMode'
# Gestion switch sélecteur : Setting mode 'off' en mode 'cooling'
setting_command_on_off_mode_zone = u'setCoolingOnOffState'
# Gestion switch sélecteur : Prise en compte de l'état de la zone (manu, comfort, eco...)
state_zone = value_by_name(data,x,u'io:PassAPCCoolingProfileState')
# Gestion switch sélecteur : Prise en compte de l'état on/off de la zone
state_on_off_zone = value_by_name(data,x,u'core:CoolingOnOffState')
# Gestion de la consigne manuel suivant l'état de fonctionnement de la PAC (heating ou cooling)
# Consigne température en mode manu : (setCoolingTargetTemperature en mode manuel refroidissement / setHeatingTargetTemperature en mode manuel chauffage)
gestion_consigne(u'Manuel',classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_cons_temp_manu'),value_by_name(data,x,u'core:TargetTemperatureState'),setting_consigne_zone)
# Gestion switch sélecteur :
return_switch = gestion_switch_selector_domoticz (state_mode_zone ,classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_switch_mode'),
state_cozytouch_on_off = state_on_off_zone,
command_off_activate= True, setting_command_on_off=setting_command_on_off_mode_zone, setting_parameter_off=u'off',
command_on_activate=True, setting_parameter_on=u'on',
level_0=u'stop',level_10=u'manu',level_20=u'internalScheduling',setting_command_mode=setting_command_mode_zone)
# Evaluation du retour de la fonction, si cas n°2, on a envoyé un changement vers Cozytouch
# On renvoi dans tous les cas de changement de mode vers Cozytouch la consigne manuel
if return_switch == 1 :
# Renvoi de la consigne de T°C manuel lors d'une changement de mode vers manuel (sinon sans cela, la consigne passe à 8°C)
cozytouch_POST(classe.get(u'url'),setting_consigne_zone, domoticz_read_device_analog(classe.get(u'idx_cons_temp_manu')))
# Si zone control en 'stop' : on force l'affichage des zones en 'off''
elif mode_PAC == u'stop' :
# Gestion switch sélecteur :
gestion_switch_selector_domoticz (state_mode_zone ,classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_switch_mode'),
state_cozytouch_on_off = u'stop', # force une lecture d'un état OFF
level_0=u'stop',level_10=u'manu',level_20=u'internalScheduling')
####
# Update function : SubClass DHWP_THERM_V3_IO, DHWP_THERM_IO, DHWP_THERM_V2_MURAL_IO
if name == dict_cozytouch_devtypes.get(u'DHWP_THERM_V3_IO') or name == dict_cozytouch_devtypes.get(u'DHWP_THERM_IO') or name == dict_cozytouch_devtypes.get(u'DHWP_THERM_V2_MURAL_IO') :
# Etat chauffe on/off
a = (value_by_name(data,x,u"io:OperatingModeCapabilitiesState"))[u'energyDemandStatus']
if a == 1 :
on_off = u'On'
else:
on_off = u'Off'
# Comparaison avec l'état précédent pour mettre à jour uniquement sur changement (évite de remplir les logs inutilement)
onoff_prec = var_restore('save_onoff_'+str(classe.get('idx_on_off')))
if onoff_prec != on_off :
domoticz_write_device_switch_onoff(on_off,classe.get(u'idx_on_off'))
var_save(on_off, ('save_onoff_'+str(classe.get('idx_on_off'))))
# Compteur temps de fonctionnement pompe à chaleur (io:HeatPumpOperatingTimeState)
domoticz_write_device_analog(value_by_name(data,x,u'io:HeatPumpOperatingTimeState'),classe.get(u'idx_compteur_pompe'))
# Energy counter (core:ElectricEnergyConsumptionState)
domoticz_write_device_analog(value_by_name(data,x+1,u'core:ElectricEnergyConsumptionState'),classe.get(u'idx_compteur_energie'))
# Consigne température (SetTargetTemperature) ou #'core:TemperatureState' si pb
gestion_consigne (u'consigne',classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_cons_temp'),value_by_name(data,x,u'core:TargetTemperatureState'),u'setTargetTemperature')
# Remplacement état du chauffe eau par 'boost' si activé
if (value_by_name(data,x,u"core:OperatingModeState"))[u'relaunch'] == u'on':
state_chauffe_eau = u'boost'
elif (value_by_name(data,x,u'core:OperatingModeState'))[u'absence'] == u'on':
state_chauffe_eau = u'off'
# Par défaut, état du chauffe eau repris sur le DHWmodeState (manual, manual+eco ou auto)
else :
state_chauffe_eau = (value_by_name(data,x,u'io:DHWModeState'))
# Switch selecteur mode Manuel+ecoInactive/Manuel+ecoActive/Auto
return_fonction = gestion_switch_selector_domoticz (state_chauffe_eau,classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_switch_mode'),
state_cozytouch_on_off = (value_by_name(data,x,u'core:OperatingModeState'))[u'absence'],
level_0=u'off',level_10=u'manualEcoInactive',level_20=u'manualEcoActive',level_30=u'autoMode',level_40=u'boost',setting_command_mode=u'setDHWMode',
command_activate=False)
# Mode changement de domoticz vers Cozytouch avec nom du level envoyé
if return_fonction[0] == 1 :
if return_fonction[1]== u'off' :
cozytouch_POST(classe.get(u'url'),u'setCurrentOperatingMode',u'{"absence":"on", "relaunch":"off"}')
elif return_fonction[1] != u'off' and return_fonction[1] == u'boost' :
cozytouch_POST(classe.get(u'url'),u'setCurrentOperatingMode',u'{"absence":"off", "relaunch":"on"}')
elif return_fonction[1] != u'off' and return_fonction[1] != u'boost' :
cozytouch_POST(classe.get(u'url'),u'setCurrentOperatingMode',u'{"absence":"off", "relaunch":"off"}')
if return_fonction[1] == u'manualEcoInactive' or return_fonction[1] == u'manualEcoActive' or return_fonction[1] == u'autoMode' :
cozytouch_POST(classe.get(u'url'),u'setDHWMode',return_fonction[1])
# Switch selecteur durée 'boost'
gestion_switch_selector_domoticz (value_by_name(data,x,u'core:BoostModeDurationState'),classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_boost_duration'),
level_0=0, level_10=1, level_20=2, level_30=3, level_40=4, level_50=5, level_60=6,level_70=7,setting_command_mode=u'setBoostModeDuration')
# Switch selecteur durée 'absence'
gestion_switch_selector_domoticz (int(value_by_name(data,x,u'io:AwayModeDurationState')),classe.get(u'url'),classe.get(u'nom'),classe.get(u'idx_away_duration'),
level_0=0, level_10=1, level_20=2, level_30=3, level_40=4, level_50=5, level_60=6,level_70=7,setting_command_mode=u'setAwayModeDuration')
######
# Update only for SubClass "DHWP_THERM_V2_MURAL_IO"
if name == dict_cozytouch_devtypes.get(u'DHWP_THERM_V2_MURAL_IO') :
# Temperature measurement (io:MiddleWaterTemperatureState)
domoticz_write_device_analog((value_by_name(data,x,u'io:MiddleWaterTemperatureState')),(classe.get(u'idx_temp_measurement')))
# Heat Pump Energy Counter (io:PowerHeatPumpState)
domoticz_write_device_analog((value_by_name(data,x,u'io:PowerHeatPumpState')),(classe.get(u'idx_energy_counter_heatpump')))
# Heat Electrical Energy Counter (io:PowerHeatElectricalState)
domoticz_write_device_analog((value_by_name(data,x,u'io:PowerHeatElectricalState')),(classe.get(u'idx_energy_counter_heatelec')))
# Water volume estimation (core:V40WaterVolumeEstimationState)
domoticz_write_device_analog((value_by_name(data,x,u'core:V40WaterVolumeEstimationState')),(classe.get(u'idx_water_estimation'))) | [
"def",
"maj_device",
"(",
"data",
",",
"name",
",",
"p",
",",
"x",
")",
":",
"print",
"(",
"\"Mise a jour device \"",
"+",
"str",
"(",
"p",
")",
"+",
"\" : \"",
"+",
"name",
")",
"a",
"=",
"var_restore",
"(",
"'save_devices'",
")",
"classe",
"=",
"a",
"[",
"p",
"]",
"''' Mise à jour : Données radiateur\n '''",
"if",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"u'module fil pilote'",
")",
"or",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"u'radiateur'",
")",
":",
"# Switch selecteur mode OFF / Manuel / Auto",
"gestion_switch_selector_domoticz",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:TargetHeatingLevelState'",
")",
")",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_switch_level'",
")",
",",
"state_cozytouch_on_off",
"=",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:OperatingModeState'",
")",
")",
")",
",",
"command_off_activate",
"=",
"True",
",",
"level_0",
"=",
"u'off'",
",",
"level_10",
"=",
"u'frostprotection'",
",",
"level_20",
"=",
"u'eco'",
",",
"level_30",
"=",
"u'comfort-2'",
",",
"level_40",
"=",
"u'comfort-1'",
",",
"level_50",
"=",
"u'comfort'",
",",
"setting_command_mode",
"=",
"u'setHeatingLevel'",
")",
"if",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"u'radiateur'",
")",
":",
"# Switch selecteur mode ordre radiateur OFF / Hors gel / Eco / Confort -2 / Confort -2 / Confort",
"# pas d'écriture possible depuis domoticz pour un radiateur connecté, l'ordre est imposé par le fil pilote ou le mode de programmation interne de l'appareil",
"# Lecture de l'ordre en cours sur le raditateur :",
"ordre_radiateur",
"=",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:TargetHeatingLevelState'",
")",
")",
"print",
"ordre_radiateur",
"#Lecture de l'état de fonctionnement du radiateur :",
"mode_radiateur",
"=",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:OperatingModeState'",
")",
")",
"print",
"mode_radiateur",
"# Switch selecteur mode OFF / Manuel / Auto",
"gestion_switch_selector_domoticz",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:OperatingModeState'",
")",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_switch_mode'",
")",
",",
"level_0",
"=",
"u'standby'",
",",
"level_10",
"=",
"u'basic'",
",",
"level_20",
"=",
"u'internal'",
",",
"level_30",
"=",
"u'Derogation'",
",",
"setting_command_mode",
"=",
"u'setOperatingMode'",
")",
"# Mesure température : Device : TemperatureSensor, Parametre 1 : core:TemperatureState",
"domoticz_write_device_analog",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"(",
"x",
"+",
"1",
")",
",",
"u'core:TemperatureState'",
")",
")",
",",
"(",
"classe",
".",
"get",
"(",
"u'idx_mesure_temp'",
")",
")",
")",
"# Consigne de température confort : Device : AtlanticElectricalHeaterWithAdjustableTemperatureSetpointIOComponent, Parametre 9 : core:ComfortRoomTemperatureState",
"gestion_consigne",
"(",
"u'confort'",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_confort'",
")",
",",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:ComfortRoomTemperatureState'",
")",
",",
"(",
"u'setComfortTemperature'",
")",
")",
"# Consigne de témpérature éco : Device : AtlanticElectricalHeaterWithAdjustableTemperatureSetpointIOComponent, Parametre 10: core:EcoRoomTemperatureState",
"gestion_consigne",
"(",
"u'eco'",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_eco'",
")",
",",
"value_by_name",
"(",
"data",
",",
"x",
",",
"'core:ComfortRoomTemperatureState'",
")",
",",
"u'setSetpointLoweringTemperatureInProgMode'",
",",
"cons_device_abais_eco",
"=",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:SetpointLoweringTemperatureInProgModeState'",
")",
",",
"# lecture de la consigne éco appliquée par Cozytouch",
"cons_domoticz_confort",
"=",
"domoticz_read_device_analog",
"(",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_confort'",
")",
")",
")",
"# lecture de la consigne confort appliquée dans Domoticz",
"# Compteur d'énergie: Device : CumulativeElectricPowerConsumptionSensor, Parametre 1 : core:ElectricEnergyConsumptionState",
"domoticz_write_device_analog",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"x",
"+",
"4",
",",
"u'core:ElectricEnergyConsumptionState'",
")",
")",
",",
"(",
"classe",
".",
"get",
"(",
"u'idx_compteur'",
")",
")",
")",
"''' Mise à jour : Données chauffe eau\n '''",
"if",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"'chauffe eau'",
")",
":",
"# Switch on/off",
"on_off",
"=",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"\"io:OperatingModeCapabilitiesState\"",
")",
"[",
"u'energyDemandStatus'",
"]",
")",
"if",
"on_off",
"==",
"1",
":",
"on_off",
"=",
"'On'",
"else",
":",
"on_off",
"=",
"'Off'",
"# Comparaison avec l'état précédent pour mettre à jour uniquement sur changement (évite de remplir les logs inutilement)",
"onoff_prec",
"=",
"var_restore",
"(",
"'save_onoff_'",
"+",
"str",
"(",
"classe",
".",
"get",
"(",
"'idx_on_off'",
")",
")",
")",
"if",
"onoff_prec",
"!=",
"on_off",
":",
"domoticz_write_device_switch_onoff",
"(",
"on_off",
",",
"(",
"classe",
".",
"get",
"(",
"'idx_on_off'",
")",
")",
")",
"var_save",
"(",
"on_off",
",",
"(",
"'save_onoff_'",
"+",
"str",
"(",
"classe",
".",
"get",
"(",
"'idx_on_off'",
")",
")",
")",
")",
"# Switch selecteur auto/manu/manu+eco : définition des levels du switch",
"auto_manu",
"=",
"value_by_name",
"(",
"data",
",",
"x",
",",
"\"io:DHWModeState\"",
")",
"if",
"auto_manu",
"==",
"'autoMode'",
":",
"switch",
"=",
"0",
"if",
"auto_manu",
"==",
"'manualEcoInactive'",
":",
"switch",
"=",
"10",
"if",
"auto_manu",
"==",
"'manualEcoActive'",
":",
"switch",
"=",
"20",
"# Switch selecteur :",
"# Comparaison avec l'état précédent pour mettre à jour uniquement sur changement (évite de remplir les logs inutilement)",
"switch_prec",
"=",
"var_restore",
"(",
"'save_switch_'",
"+",
"str",
"(",
"classe",
".",
"get",
"(",
"'idx_switch_auto_manu'",
")",
")",
")",
"if",
"switch_prec",
"!=",
"switch",
":",
"domoticz_write_device_switch_selector",
"(",
"switch",
",",
"classe",
".",
"get",
"(",
"'idx_switch_auto_manu'",
")",
")",
"var_save",
"(",
"switch",
",",
"(",
"'save_switch_'",
"+",
"str",
"(",
"classe",
".",
"get",
"(",
"'idx_switch_auto_manu'",
")",
")",
")",
")",
"# Mesure température :",
"domoticz_write_device_analog",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"\"core:TemperatureState\"",
")",
")",
",",
"(",
"classe",
".",
"get",
"(",
"'idx_mesure_temp'",
")",
")",
")",
"# Compteur d'eau chaude restante :",
"domoticz_write_device_analog",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"\"core:WaterConsumptionState\"",
")",
",",
"(",
"classe",
".",
"get",
"(",
"'idx_conso_eau'",
")",
")",
")",
"# Calcul puissance moyenne :",
"wh_prec",
"=",
"var_restore",
"(",
"'wh_prec_'",
"+",
"str",
"(",
"classe",
".",
"get",
"(",
"'idx_compteur'",
")",
")",
")",
"wh_actuel",
"=",
"value_by_name",
"(",
"data",
",",
"x",
"+",
"1",
",",
"'core:ElectricEnergyConsumptionState'",
")",
"wh_1min",
"=",
"wh_actuel",
"-",
"wh_prec",
"Pmoy_1min",
"=",
"wh_1min",
"*",
"60",
"var_save",
"(",
"wh_actuel",
",",
"(",
"'wh_prec_'",
"+",
"str",
"(",
"classe",
".",
"get",
"(",
"'idx_compteur'",
")",
")",
")",
")",
"# Compteur d'énergie:",
"domoticz_write_device_analog",
"(",
"str",
"(",
"Pmoy_1min",
")",
"+",
"';'",
"+",
"str",
"(",
"wh_actuel",
")",
",",
"(",
"classe",
".",
"get",
"(",
"'idx_compteur'",
")",
")",
")",
"# Compteur temps de fonctionnement pompe à chaleur :",
"domoticz_write_device_analog",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"\"io:HeatPumpOperatingTimeState\"",
")",
")",
",",
"(",
"classe",
".",
"get",
"(",
"'idx_compteur_pompe'",
")",
")",
")",
"''' Mise à jour : Données PAC\n '''",
"if",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"u'PAC main control'",
")",
":",
"# MAJ données générales PAC",
"# Lecture du mode stop/heating/cooling/drying :",
"global",
"mode_PAC",
"mode_PAC",
"=",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:PassAPCOperatingModeState'",
")",
")",
"# Lecture du mode auto : Remplacement variable mode par 'auto'",
"if",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:HeatingCoolingAutoSwitchState'",
")",
"==",
"u'on'",
":",
"mode_PAC",
"=",
"u'auto'",
"# Gestion du sélecteur :",
"# Voir comment gérer la demande de passage en mode auto, il faut adresser une commande \"setHeatingCoolingAutoSwitch\" au changement du label u'auto'",
"# BLOC MODIFIE POUR ENVOI D ELA COMMANDE SETHEATINGCOLLINGAUTOSWITCH MAIS IL FAUT ENVOYER UN 'ON' OU UN 'OFF' PAS LE LABEL 40 'AUTO'",
"gestion_switch_selector_domoticz",
"(",
"mode_PAC",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_switch_mode'",
")",
",",
"level_0",
"=",
"'stop'",
",",
"level_10",
"=",
"'heating'",
",",
"level_20",
"=",
"'cooling'",
",",
"level_30",
"=",
"'drying'",
",",
"level_40",
"=",
"'auto'",
",",
"setting_command_mode",
"=",
"'setPassAPCOperatingMode'",
",",
"special_level",
"=",
"'auto'",
",",
"special_setting",
"=",
"'setHeatingCoolingAutoSwitch'",
",",
"special_setting_parameter_on",
"=",
"'on'",
",",
"special_setting_parameter_off",
"=",
"'off'",
")",
"if",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"'PAC zone control'",
")",
":",
"# MAJ données zone PAC",
"# Mesure température :",
"domoticz_write_device_analog",
"(",
"value_by_name",
"(",
"data",
",",
"(",
"x",
"+",
"1",
")",
",",
"u'core:TemperatureState'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_mesure_temp'",
")",
")",
"# Consigne température Confort en mode chauffage en mode programmation : (core:ComfortHeatingTargetTemperatureState)",
"gestion_consigne",
"(",
"u'Confort chauff.'",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_confort_chauffage'",
")",
",",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:ComfortHeatingTargetTemperatureState'",
")",
",",
"(",
"u'setComfortHeatingTargetTemperature'",
")",
")",
"# Consigne température Confort mode climatisation en mode programmation : (core:ComfortCoolingTargetTemperatureState)",
"gestion_consigne",
"(",
"u'Confort rafraich.'",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_confort_clim'",
")",
",",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:ComfortCoolingTargetTemperatureState'",
")",
",",
"(",
"u'setComfortCoolingTargetTemperature'",
")",
")",
"# Consigne température Eco mode chauffage en mode programmation : (core:EcoHeatingTargetTemperatureState)",
"gestion_consigne",
"(",
"u'Eco chauff.'",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_eco_chauffage'",
")",
",",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:EcoHeatingTargetTemperatureState'",
")",
",",
"(",
"u'setEcoHeatingTargetTemperature'",
")",
")",
"# Consigne température Confort mode climatisation en mode programmation : (core:EcoCoolingTargetTemperatureState)",
"gestion_consigne",
"(",
"u'Eco rafraich.'",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_eco_clim'",
")",
",",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:EcoCoolingTargetTemperatureState'",
")",
",",
"(",
"u'setEcoCoolingTargetTemperature'",
")",
")",
"# Switch selecteur mode OFF / Manuel / Auto",
"# dépendant du mode en cours de la Zone Control pour le mode Manuel",
"# Si zone Control en mode 'Heating' :",
"if",
"mode_PAC",
"==",
"u'heating'",
":",
"# Gestion consigne en mode manuel : Seeting consigne en mode 'heating'",
"setting_consigne_zone",
"=",
"u'setHeatingTargetTemperature'",
"# Gestion switch sélecteur : Prise en compte du mode de fonctionnement de la zone control suivant le paramètre de fonctionnement en mode 'heating'",
"state_mode_zone",
"=",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:PassAPCHeatingModeState'",
")",
"# Gestion switch sélecteur : Setting mode en mode 'heating'",
"setting_command_mode_zone",
"=",
"u'setPassAPCHeatingMode'",
"# Gestion switch sélecteur : Setting mode 'off' en mode 'heating'",
"setting_command_on_off_mode_zone",
"=",
"u'setHeatingOnOffState'",
"# Gestion switch sélecteur : Prise en compte de l'état de la zone (manu, comfort, eco...)",
"state_zone",
"=",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:PassAPCHeatingProfileState'",
")",
"# Gestion switch sélecteur : Prise en compte de l'état on/off de la zone",
"state_on_off_zone",
"=",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:HeatingOnOffState'",
")",
"# Gestion de la consigne manuel suivant l'état de fonctionnement de la PAC (heating ou cooling)",
"# Consigne température en mode manu : (setCoolingTargetTemperature en mode manuel refroidissement / setHeatingTargetTemperature en mode manuel chauffage)",
"gestion_consigne",
"(",
"u'Manuel'",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_manu'",
")",
",",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:TargetTemperatureState'",
")",
",",
"setting_consigne_zone",
")",
"# Gestion switch sélecteur :",
"return_switch",
"=",
"gestion_switch_selector_domoticz",
"(",
"state_mode_zone",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_switch_mode'",
")",
",",
"state_cozytouch_on_off",
"=",
"state_on_off_zone",
",",
"command_off_activate",
"=",
"True",
",",
"setting_command_on_off",
"=",
"setting_command_on_off_mode_zone",
",",
"setting_parameter_off",
"=",
"u'off'",
",",
"command_on_activate",
"=",
"True",
",",
"setting_parameter_on",
"=",
"u'on'",
",",
"level_0",
"=",
"u'stop'",
",",
"level_10",
"=",
"u'manu'",
",",
"level_20",
"=",
"u'internalScheduling'",
",",
"setting_command_mode",
"=",
"setting_command_mode_zone",
")",
"# Evaluation du retour de la fonction, si cas n°2, on a envoyé un changement vers Cozytouch",
"# On renvoi dans tous les cas de changement de mode vers Cozytouch la consigne manuel",
"if",
"return_switch",
"==",
"1",
":",
"# Renvoi de la consigne de T°C manuel lors d'une changement de mode vers manuel (sinon sans cela, la consigne passe à 8°C, mystère Cozytouch)",
"cozytouch_POST",
"(",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"setting_consigne_zone",
",",
"+",
"domoticz_read_device_analog",
"(",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_manu'",
")",
")",
")",
"# Si zone Control en mode 'Cooling' :",
"elif",
"mode_PAC",
"==",
"u'cooling'",
":",
"# Gestion consigne en mode manuel : Setting consigne en mode 'heating'",
"setting_consigne_zone",
"=",
"u'setCoolingTargetTemperature'",
"# Gestion switch sélecteur : Prise en compte du mode de fonctionnement de la zone control suivant le paramètre de fonctionnement en mode 'cooling'",
"state_mode_zone",
"=",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:PassAPCCoolingModeState'",
")",
"# Gestion switch sélecteur : Setting mode en mode 'cooling'",
"setting_command_mode_zone",
"=",
"u'setPassAPCCoolingMode'",
"# Gestion switch sélecteur : Setting mode 'off' en mode 'cooling'",
"setting_command_on_off_mode_zone",
"=",
"u'setCoolingOnOffState'",
"# Gestion switch sélecteur : Prise en compte de l'état de la zone (manu, comfort, eco...)",
"state_zone",
"=",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:PassAPCCoolingProfileState'",
")",
"# Gestion switch sélecteur : Prise en compte de l'état on/off de la zone",
"state_on_off_zone",
"=",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:CoolingOnOffState'",
")",
"# Gestion de la consigne manuel suivant l'état de fonctionnement de la PAC (heating ou cooling)",
"# Consigne température en mode manu : (setCoolingTargetTemperature en mode manuel refroidissement / setHeatingTargetTemperature en mode manuel chauffage)",
"gestion_consigne",
"(",
"u'Manuel'",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_manu'",
")",
",",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:TargetTemperatureState'",
")",
",",
"setting_consigne_zone",
")",
"# Gestion switch sélecteur :",
"return_switch",
"=",
"gestion_switch_selector_domoticz",
"(",
"state_mode_zone",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_switch_mode'",
")",
",",
"state_cozytouch_on_off",
"=",
"state_on_off_zone",
",",
"command_off_activate",
"=",
"True",
",",
"setting_command_on_off",
"=",
"setting_command_on_off_mode_zone",
",",
"setting_parameter_off",
"=",
"u'off'",
",",
"command_on_activate",
"=",
"True",
",",
"setting_parameter_on",
"=",
"u'on'",
",",
"level_0",
"=",
"u'stop'",
",",
"level_10",
"=",
"u'manu'",
",",
"level_20",
"=",
"u'internalScheduling'",
",",
"setting_command_mode",
"=",
"setting_command_mode_zone",
")",
"# Evaluation du retour de la fonction, si cas n°2, on a envoyé un changement vers Cozytouch",
"# On renvoi dans tous les cas de changement de mode vers Cozytouch la consigne manuel",
"if",
"return_switch",
"==",
"1",
":",
"# Renvoi de la consigne de T°C manuel lors d'une changement de mode vers manuel (sinon sans cela, la consigne passe à 8°C)",
"cozytouch_POST",
"(",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"setting_consigne_zone",
",",
"domoticz_read_device_analog",
"(",
"classe",
".",
"get",
"(",
"u'idx_cons_temp_manu'",
")",
")",
")",
"# Si zone control en 'stop' : on force l'affichage des zones en 'off''",
"elif",
"mode_PAC",
"==",
"u'stop'",
":",
"# Gestion switch sélecteur :",
"gestion_switch_selector_domoticz",
"(",
"state_mode_zone",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_switch_mode'",
")",
",",
"state_cozytouch_on_off",
"=",
"u'stop'",
",",
"# force une lecture d'un état OFF",
"level_0",
"=",
"u'stop'",
",",
"level_10",
"=",
"u'manu'",
",",
"level_20",
"=",
"u'internalScheduling'",
")",
"####",
"# Update function : SubClass DHWP_THERM_V3_IO, DHWP_THERM_IO, DHWP_THERM_V2_MURAL_IO",
"if",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"u'DHWP_THERM_V3_IO'",
")",
"or",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"u'DHWP_THERM_IO'",
")",
"or",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"u'DHWP_THERM_V2_MURAL_IO'",
")",
":",
"# Etat chauffe on/off",
"a",
"=",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u\"io:OperatingModeCapabilitiesState\"",
")",
")",
"[",
"u'energyDemandStatus'",
"]",
"if",
"a",
"==",
"1",
":",
"on_off",
"=",
"u'On'",
"else",
":",
"on_off",
"=",
"u'Off'",
"# Comparaison avec l'état précédent pour mettre à jour uniquement sur changement (évite de remplir les logs inutilement)",
"onoff_prec",
"=",
"var_restore",
"(",
"'save_onoff_'",
"+",
"str",
"(",
"classe",
".",
"get",
"(",
"'idx_on_off'",
")",
")",
")",
"if",
"onoff_prec",
"!=",
"on_off",
":",
"domoticz_write_device_switch_onoff",
"(",
"on_off",
",",
"classe",
".",
"get",
"(",
"u'idx_on_off'",
")",
")",
"var_save",
"(",
"on_off",
",",
"(",
"'save_onoff_'",
"+",
"str",
"(",
"classe",
".",
"get",
"(",
"'idx_on_off'",
")",
")",
")",
")",
"# Compteur temps de fonctionnement pompe à chaleur (io:HeatPumpOperatingTimeState)",
"domoticz_write_device_analog",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:HeatPumpOperatingTimeState'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_compteur_pompe'",
")",
")",
"# Energy counter (core:ElectricEnergyConsumptionState)",
"domoticz_write_device_analog",
"(",
"value_by_name",
"(",
"data",
",",
"x",
"+",
"1",
",",
"u'core:ElectricEnergyConsumptionState'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_compteur_energie'",
")",
")",
"# Consigne température (SetTargetTemperature) ou #'core:TemperatureState' si pb",
"gestion_consigne",
"(",
"u'consigne'",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_cons_temp'",
")",
",",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:TargetTemperatureState'",
")",
",",
"u'setTargetTemperature'",
")",
"# Remplacement état du chauffe eau par 'boost' si activé",
"if",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u\"core:OperatingModeState\"",
")",
")",
"[",
"u'relaunch'",
"]",
"==",
"u'on'",
":",
"state_chauffe_eau",
"=",
"u'boost'",
"elif",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:OperatingModeState'",
")",
")",
"[",
"u'absence'",
"]",
"==",
"u'on'",
":",
"state_chauffe_eau",
"=",
"u'off'",
"# Par défaut, état du chauffe eau repris sur le DHWmodeState (manual, manual+eco ou auto)",
"else",
":",
"state_chauffe_eau",
"=",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:DHWModeState'",
")",
")",
"# Switch selecteur mode Manuel+ecoInactive/Manuel+ecoActive/Auto",
"return_fonction",
"=",
"gestion_switch_selector_domoticz",
"(",
"state_chauffe_eau",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_switch_mode'",
")",
",",
"state_cozytouch_on_off",
"=",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:OperatingModeState'",
")",
")",
"[",
"u'absence'",
"]",
",",
"level_0",
"=",
"u'off'",
",",
"level_10",
"=",
"u'manualEcoInactive'",
",",
"level_20",
"=",
"u'manualEcoActive'",
",",
"level_30",
"=",
"u'autoMode'",
",",
"level_40",
"=",
"u'boost'",
",",
"setting_command_mode",
"=",
"u'setDHWMode'",
",",
"command_activate",
"=",
"False",
")",
"# Mode changement de domoticz vers Cozytouch avec nom du level envoyé",
"if",
"return_fonction",
"[",
"0",
"]",
"==",
"1",
":",
"if",
"return_fonction",
"[",
"1",
"]",
"==",
"u'off'",
":",
"cozytouch_POST",
"(",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"u'setCurrentOperatingMode'",
",",
"u'{\"absence\":\"on\", \"relaunch\":\"off\"}'",
")",
"elif",
"return_fonction",
"[",
"1",
"]",
"!=",
"u'off'",
"and",
"return_fonction",
"[",
"1",
"]",
"==",
"u'boost'",
":",
"cozytouch_POST",
"(",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"u'setCurrentOperatingMode'",
",",
"u'{\"absence\":\"off\", \"relaunch\":\"on\"}'",
")",
"elif",
"return_fonction",
"[",
"1",
"]",
"!=",
"u'off'",
"and",
"return_fonction",
"[",
"1",
"]",
"!=",
"u'boost'",
":",
"cozytouch_POST",
"(",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"u'setCurrentOperatingMode'",
",",
"u'{\"absence\":\"off\", \"relaunch\":\"off\"}'",
")",
"if",
"return_fonction",
"[",
"1",
"]",
"==",
"u'manualEcoInactive'",
"or",
"return_fonction",
"[",
"1",
"]",
"==",
"u'manualEcoActive'",
"or",
"return_fonction",
"[",
"1",
"]",
"==",
"u'autoMode'",
":",
"cozytouch_POST",
"(",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"u'setDHWMode'",
",",
"return_fonction",
"[",
"1",
"]",
")",
"# Switch selecteur durée 'boost'",
"gestion_switch_selector_domoticz",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:BoostModeDurationState'",
")",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_boost_duration'",
")",
",",
"level_0",
"=",
"0",
",",
"level_10",
"=",
"1",
",",
"level_20",
"=",
"2",
",",
"level_30",
"=",
"3",
",",
"level_40",
"=",
"4",
",",
"level_50",
"=",
"5",
",",
"level_60",
"=",
"6",
",",
"level_70",
"=",
"7",
",",
"setting_command_mode",
"=",
"u'setBoostModeDuration'",
")",
"# Switch selecteur durée 'absence'",
"gestion_switch_selector_domoticz",
"(",
"int",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:AwayModeDurationState'",
")",
")",
",",
"classe",
".",
"get",
"(",
"u'url'",
")",
",",
"classe",
".",
"get",
"(",
"u'nom'",
")",
",",
"classe",
".",
"get",
"(",
"u'idx_away_duration'",
")",
",",
"level_0",
"=",
"0",
",",
"level_10",
"=",
"1",
",",
"level_20",
"=",
"2",
",",
"level_30",
"=",
"3",
",",
"level_40",
"=",
"4",
",",
"level_50",
"=",
"5",
",",
"level_60",
"=",
"6",
",",
"level_70",
"=",
"7",
",",
"setting_command_mode",
"=",
"u'setAwayModeDuration'",
")",
"######",
"# Update only for SubClass \"DHWP_THERM_V2_MURAL_IO\"",
"if",
"name",
"==",
"dict_cozytouch_devtypes",
".",
"get",
"(",
"u'DHWP_THERM_V2_MURAL_IO'",
")",
":",
"# Temperature measurement (io:MiddleWaterTemperatureState)",
"domoticz_write_device_analog",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:MiddleWaterTemperatureState'",
")",
")",
",",
"(",
"classe",
".",
"get",
"(",
"u'idx_temp_measurement'",
")",
")",
")",
"# Heat Pump Energy Counter (io:PowerHeatPumpState)",
"domoticz_write_device_analog",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:PowerHeatPumpState'",
")",
")",
",",
"(",
"classe",
".",
"get",
"(",
"u'idx_energy_counter_heatpump'",
")",
")",
")",
"# Heat Electrical Energy Counter (io:PowerHeatElectricalState)",
"domoticz_write_device_analog",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'io:PowerHeatElectricalState'",
")",
")",
",",
"(",
"classe",
".",
"get",
"(",
"u'idx_energy_counter_heatelec'",
")",
")",
")",
"# Water volume estimation (core:V40WaterVolumeEstimationState)",
"domoticz_write_device_analog",
"(",
"(",
"value_by_name",
"(",
"data",
",",
"x",
",",
"u'core:V40WaterVolumeEstimationState'",
")",
")",
",",
"(",
"classe",
".",
"get",
"(",
"u'idx_water_estimation'",
")",
")",
")"
] | [
1265,
0
] | [
1556,
141
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Facette.intersection | (self, r) | retourne le point d'intersection avec le rayon r,
retourne None s'il n'y pas d'intersection | retourne le point d'intersection avec le rayon r,
retourne None s'il n'y pas d'intersection | def intersection(self, r):
"""retourne le point d'intersection avec le rayon r,
retourne None s'il n'y pas d'intersection"""
p = self.intersection_plan(r)
if p is None:
return None
if self.point_interieur(p):
return p
else:
return None | [
"def",
"intersection",
"(",
"self",
",",
"r",
")",
":",
"p",
"=",
"self",
".",
"intersection_plan",
"(",
"r",
")",
"if",
"p",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"point_interieur",
"(",
"p",
")",
":",
"return",
"p",
"else",
":",
"return",
"None"
] | [
41,
4
] | [
50,
23
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
point.__str__ | (self) | return "(x,y) = (%4.1f,%4.1f) masse %f" % (self.x,self.y,self.m) | afficher le point | afficher le point | def __str__ (self) :
"""afficher le point"""
return "(x,y) = (%4.1f,%4.1f) masse %f" % (self.x,self.y,self.m) | [
"def",
"__str__",
"(",
"self",
")",
":",
"return",
"\"(x,y) = (%4.1f,%4.1f) masse %f\"",
"%",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
",",
"self",
".",
"m",
")"
] | [
29,
4
] | [
31,
72
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
facette.intersection | (self, r) | retourne le point d'intersection avec le rayon r,
retourne None s'il n'y pas d'intersection | retourne le point d'intersection avec le rayon r,
retourne None s'il n'y pas d'intersection | def intersection (self, r) :
"""retourne le point d'intersection avec le rayon r,
retourne None s'il n'y pas d'intersection"""
p = self.intersection_plan (r)
if p == None : return None
if self.point_interieur (p) : return p
else : return None | [
"def",
"intersection",
"(",
"self",
",",
"r",
")",
":",
"p",
"=",
"self",
".",
"intersection_plan",
"(",
"r",
")",
"if",
"p",
"==",
"None",
":",
"return",
"None",
"if",
"self",
".",
"point_interieur",
"(",
"p",
")",
":",
"return",
"p",
"else",
":",
"return",
"None"
] | [
42,
4
] | [
48,
26
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
inverse_couleurs | (noeud) | Inverse les couleurs pour converser un équilibre-noir parfait. | Inverse les couleurs pour converser un équilibre-noir parfait. | def inverse_couleurs(noeud):
"""Inverse les couleurs pour converser un équilibre-noir parfait."""
noeud.couleur = ROUGE
noeud.gauche.couleur = NOIR
noeud.droite.couleur = NOIR | [
"def",
"inverse_couleurs",
"(",
"noeud",
")",
":",
"noeud",
".",
"couleur",
"=",
"ROUGE",
"noeud",
".",
"gauche",
".",
"couleur",
"=",
"NOIR",
"noeud",
".",
"droite",
".",
"couleur",
"=",
"NOIR"
] | [
50,
0
] | [
54,
31
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
tests | () | Fonction de tests. | Fonction de tests. | def tests():
"""Fonction de tests."""
arbre = creer_arbre_rouge_noir_avec_liste([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
noeud = trouve_valeur_dans_arbre_rouge_noir(arbre, 7)
print(noeud.valeur)
print("---")
noeud = trouve_valeur_dans_arbre_rouge_noir(arbre, -1)
if noeud != None:
raise ValueError("-1")
print("-1")
print("---")
parcourt_arbre(arbre, print)
print("---")
parcourt_arbre_avec_parent(arbre, affiche_arrete) | [
"def",
"tests",
"(",
")",
":",
"arbre",
"=",
"creer_arbre_rouge_noir_avec_liste",
"(",
"[",
"0",
",",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
",",
"7",
",",
"8",
",",
"9",
"]",
")",
"noeud",
"=",
"trouve_valeur_dans_arbre_rouge_noir",
"(",
"arbre",
",",
"7",
")",
"print",
"(",
"noeud",
".",
"valeur",
")",
"print",
"(",
"\"---\"",
")",
"noeud",
"=",
"trouve_valeur_dans_arbre_rouge_noir",
"(",
"arbre",
",",
"-",
"1",
")",
"if",
"noeud",
"!=",
"None",
":",
"raise",
"ValueError",
"(",
"\"-1\"",
")",
"print",
"(",
"\"-1\"",
")",
"print",
"(",
"\"---\"",
")",
"parcourt_arbre",
"(",
"arbre",
",",
"print",
")",
"print",
"(",
"\"---\"",
")",
"parcourt_arbre_avec_parent",
"(",
"arbre",
",",
"affiche_arrete",
")"
] | [
140,
0
] | [
153,
53
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
create_df_global | (data, data_global, columns_from_global) | return df | Cette fonction crée et renvoie la dataframe contenant la somme des observations sur tous les établissements. | Cette fonction crée et renvoie la dataframe contenant la somme des observations sur tous les établissements. | def create_df_global(data, data_global, columns_from_global):
"""Cette fonction crée et renvoie la dataframe contenant la somme des observations sur tous les établissements."""
df = (
data.reset_index()
.groupby("date")[["prevision", "reel", "effectif"]]
.sum()
# On enrichit avec les variables exogènes
.join(data_global[columns_from_global])
)
return df | [
"def",
"create_df_global",
"(",
"data",
",",
"data_global",
",",
"columns_from_global",
")",
":",
"df",
"=",
"(",
"data",
".",
"reset_index",
"(",
")",
".",
"groupby",
"(",
"\"date\"",
")",
"[",
"[",
"\"prevision\"",
",",
"\"reel\"",
",",
"\"effectif\"",
"]",
"]",
".",
"sum",
"(",
")",
"# On enrichit avec les variables exogènes",
".",
"join",
"(",
"data_global",
"[",
"columns_from_global",
"]",
")",
")",
"return",
"df"
] | [
41,
0
] | [
50,
13
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
PublicUserApiTests.test_password_too_short | (self) | mot depass au moins 5 caracteres | mot depass au moins 5 caracteres | def test_password_too_short(self):
"""mot depass au moins 5 caracteres"""
payload = {'email': '[email protected]', 'password': 'Ab', 'name': 'test'}
res = self.client.post(CREATE_USER_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
user_exists = get_user_model().objects.filter(
email=payload['email']
).exists()
self.assertFalse(user_exists) | [
"def",
"test_password_too_short",
"(",
"self",
")",
":",
"payload",
"=",
"{",
"'email'",
":",
"'[email protected]'",
",",
"'password'",
":",
"'Ab'",
",",
"'name'",
":",
"'test'",
"}",
"res",
"=",
"self",
".",
"client",
".",
"post",
"(",
"CREATE_USER_URL",
",",
"payload",
")",
"self",
".",
"assertEqual",
"(",
"res",
".",
"status_code",
",",
"status",
".",
"HTTP_400_BAD_REQUEST",
")",
"user_exists",
"=",
"get_user_model",
"(",
")",
".",
"objects",
".",
"filter",
"(",
"email",
"=",
"payload",
"[",
"'email'",
"]",
")",
".",
"exists",
"(",
")",
"self",
".",
"assertFalse",
"(",
"user_exists",
")"
] | [
45,
4
] | [
53,
37
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
genere_tableau_aleatoire_trie | (taille) | return [i for i in range(0,taille)] | cette fonction génère un tableau déjà trié de taille "taille" | cette fonction génère un tableau déjà trié de taille "taille" | def genere_tableau_aleatoire_trie(taille):
""" cette fonction génère un tableau déjà trié de taille "taille" """
return [i for i in range(0,taille)] | [
"def",
"genere_tableau_aleatoire_trie",
"(",
"taille",
")",
":",
"return",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"taille",
")",
"]"
] | [
39,
0
] | [
41,
39
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
sha256sum | (filename) | return h.hexdigest() | calcul le sha256 d'un fichier
Args:
filename (str): répertoire du fichier à hash
Returns:
str: valeur du hash du fichier
| calcul le sha256 d'un fichier | def sha256sum(filename):
"""calcul le sha256 d'un fichier
Args:
filename (str): répertoire du fichier à hash
Returns:
str: valeur du hash du fichier
"""
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(filename, 'rb', buffering=0) as f:
for n in iter(lambda : f.readinto(mv), 0):
h.update(mv[:n])
# print(filename,': ',time.time()-startTime)
return h.hexdigest() | [
"def",
"sha256sum",
"(",
"filename",
")",
":",
"h",
"=",
"hashlib",
".",
"sha256",
"(",
")",
"b",
"=",
"bytearray",
"(",
"128",
"*",
"1024",
")",
"mv",
"=",
"memoryview",
"(",
"b",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
",",
"buffering",
"=",
"0",
")",
"as",
"f",
":",
"for",
"n",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"readinto",
"(",
"mv",
")",
",",
"0",
")",
":",
"h",
".",
"update",
"(",
"mv",
"[",
":",
"n",
"]",
")",
"# print(filename,': ',time.time()-startTime)",
"return",
"h",
".",
"hexdigest",
"(",
")"
] | [
149,
0
] | [
165,
24
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
modifierCompte | () | return render_template("compte.html") | Controleur de la route '/modifierCompte' | Controleur de la route '/modifierCompte' | def modifierCompte():
"Controleur de la route '/modifierCompte' "
def requeteMajCompte(conn, cur, result, idEleve):
for name, value in result.items(): #pour chaque champ du formulaire
if result[name]: #si l'attribut/champ du formulaire a été modifié
#on met à jour la table eleve avec la nouvelle valeur
cur.execute("UPDATE eleve SET {} = ? WHERE idEleve = ? ;".format(name), (value, idEleve))
#on met à jour le dictionnaire du cookie de session voir https://flask.palletsprojects.com/en/1.1.x/api/#sessions
session['user'][name] = value
session.modified = True
#analyse du formulaire
if request.method == 'POST':
#ouverture du formulaire
result = request.form
#ouverture de connexion à la BDD
conn = sqlite3.connect('monavenir.db')
cur = conn.cursor()
#on récupère l'idEleve dans le dictionnaire de session
idEleve = session['user']['idEleve']
requeteMajCompte(conn, cur, result, idEleve)
#enregistrement des modifications dans la BDD
conn.commit()
#fermeture de connexion à la BDD
cur.close()
conn.close()
return render_template("compte.html") | [
"def",
"modifierCompte",
"(",
")",
":",
"def",
"requeteMajCompte",
"(",
"conn",
",",
"cur",
",",
"result",
",",
"idEleve",
")",
":",
"for",
"name",
",",
"value",
"in",
"result",
".",
"items",
"(",
")",
":",
"#pour chaque champ du formulaire\r",
"if",
"result",
"[",
"name",
"]",
":",
"#si l'attribut/champ du formulaire a été modifié\r",
"#on met à jour la table eleve avec la nouvelle valeur\r",
"cur",
".",
"execute",
"(",
"\"UPDATE eleve SET {} = ? WHERE idEleve = ? ;\"",
".",
"format",
"(",
"name",
")",
",",
"(",
"value",
",",
"idEleve",
")",
")",
"#on met à jour le dictionnaire du cookie de session voir https://flask.palletsprojects.com/en/1.1.x/api/#sessions\r",
"session",
"[",
"'user'",
"]",
"[",
"name",
"]",
"=",
"value",
"session",
".",
"modified",
"=",
"True",
"#analyse du formulaire\r",
"if",
"request",
".",
"method",
"==",
"'POST'",
":",
"#ouverture du formulaire\r",
"result",
"=",
"request",
".",
"form",
"#ouverture de connexion à la BDD\r",
"conn",
"=",
"sqlite3",
".",
"connect",
"(",
"'monavenir.db'",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"#on récupère l'idEleve dans le dictionnaire de session\r",
"idEleve",
"=",
"session",
"[",
"'user'",
"]",
"[",
"'idEleve'",
"]",
"requeteMajCompte",
"(",
"conn",
",",
"cur",
",",
"result",
",",
"idEleve",
")",
"#enregistrement des modifications dans la BDD\r",
"conn",
".",
"commit",
"(",
")",
"#fermeture de connexion à la BDD\r",
"cur",
".",
"close",
"(",
")",
"conn",
".",
"close",
"(",
")",
"return",
"render_template",
"(",
"\"compte.html\"",
")"
] | [
191,
0
] | [
218,
41
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
WindowClient.send_error | (self) | Envoie un signal qui déclenchera l'envoi de
l'erreur d'alerte | Envoie un signal qui déclenchera l'envoi de
l'erreur d'alerte | def send_error(self) :
""" Envoie un signal qui déclenchera l'envoi de
l'erreur d'alerte"""
self.output_message.append("alert_is_an_error")
self.w_button['state'] = DISABLED | [
"def",
"send_error",
"(",
"self",
")",
":",
"self",
".",
"output_message",
".",
"append",
"(",
"\"alert_is_an_error\"",
")",
"self",
".",
"w_button",
"[",
"'state'",
"]",
"=",
"DISABLED"
] | [
55,
4
] | [
59,
41
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
SegmentBord_Commun.__init__ | (self, dim) | constructeur, definit la definition de l'image | constructeur, definit la definition de l'image | def __init__(self, dim):
"""constructeur, definit la definition de l'image"""
Segment.__init__(self, Point(0, 0), Point(0, 0))
self.dim = dim | [
"def",
"__init__",
"(",
"self",
",",
"dim",
")",
":",
"Segment",
".",
"__init__",
"(",
"self",
",",
"Point",
"(",
"0",
",",
"0",
")",
",",
"Point",
"(",
"0",
",",
"0",
")",
")",
"self",
".",
"dim",
"=",
"dim"
] | [
23,
4
] | [
26,
22
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Crud.set_ticket | (self, val) | Mettre à jour le ticket de la base de données de la prise | Mettre à jour le ticket de la base de données de la prise | def set_ticket(self, val):
""" Mettre à jour le ticket de la base de données de la prise """
self.ctx["ticket"] = val | [
"def",
"set_ticket",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"ctx",
"[",
"\"ticket\"",
"]",
"=",
"val"
] | [
282,
4
] | [
284,
32
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Scene.construit_image | (self, screen, pygame, fLOG) | construit l'image de synthèse où screen est un objet du module pygame | construit l'image de synthèse où screen est un objet du module pygame | def construit_image(self, screen, pygame, fLOG):
"""construit l'image de synthèse où screen est un objet du module pygame"""
count = 0
nbpixel = int(self.dim[0] * self.dim[1] / 100)
for y in range(0, self.dim[1]):
for x in range(0, self.dim[0]):
p = Pixel(x, y)
r = self.construit_rayon(p)
c = self.rayon_couleur(r, True)
q = (p.x, self.dim[1] - p.y - 1)
d = (int(c.x * 255), int(c.y * 255), int(c.z * 255))
if pygame is None:
for i, di in enumerate(d):
screen[q[0], q[1], i] = di
else:
pygame.draw.line(screen, d, q, q)
count += 1
if pygame is not None:
if count % 150 == 0:
pygame.display.flip()
if count % nbpixel == 0:
fLOG("avancement ", count // nbpixel, "%")
if pygame is not None:
pygame.display.flip() | [
"def",
"construit_image",
"(",
"self",
",",
"screen",
",",
"pygame",
",",
"fLOG",
")",
":",
"count",
"=",
"0",
"nbpixel",
"=",
"int",
"(",
"self",
".",
"dim",
"[",
"0",
"]",
"*",
"self",
".",
"dim",
"[",
"1",
"]",
"/",
"100",
")",
"for",
"y",
"in",
"range",
"(",
"0",
",",
"self",
".",
"dim",
"[",
"1",
"]",
")",
":",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"self",
".",
"dim",
"[",
"0",
"]",
")",
":",
"p",
"=",
"Pixel",
"(",
"x",
",",
"y",
")",
"r",
"=",
"self",
".",
"construit_rayon",
"(",
"p",
")",
"c",
"=",
"self",
".",
"rayon_couleur",
"(",
"r",
",",
"True",
")",
"q",
"=",
"(",
"p",
".",
"x",
",",
"self",
".",
"dim",
"[",
"1",
"]",
"-",
"p",
".",
"y",
"-",
"1",
")",
"d",
"=",
"(",
"int",
"(",
"c",
".",
"x",
"*",
"255",
")",
",",
"int",
"(",
"c",
".",
"y",
"*",
"255",
")",
",",
"int",
"(",
"c",
".",
"z",
"*",
"255",
")",
")",
"if",
"pygame",
"is",
"None",
":",
"for",
"i",
",",
"di",
"in",
"enumerate",
"(",
"d",
")",
":",
"screen",
"[",
"q",
"[",
"0",
"]",
",",
"q",
"[",
"1",
"]",
",",
"i",
"]",
"=",
"di",
"else",
":",
"pygame",
".",
"draw",
".",
"line",
"(",
"screen",
",",
"d",
",",
"q",
",",
"q",
")",
"count",
"+=",
"1",
"if",
"pygame",
"is",
"not",
"None",
":",
"if",
"count",
"%",
"150",
"==",
"0",
":",
"pygame",
".",
"display",
".",
"flip",
"(",
")",
"if",
"count",
"%",
"nbpixel",
"==",
"0",
":",
"fLOG",
"(",
"\"avancement \"",
",",
"count",
"//",
"nbpixel",
",",
"\"%\"",
")",
"if",
"pygame",
"is",
"not",
"None",
":",
"pygame",
".",
"display",
".",
"flip",
"(",
")"
] | [
149,
4
] | [
172,
33
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
corde.display | (self, screen) | affichage de la corde � l'aide du module pyagame | affichage de la corde � l'aide du module pyagame | def display (self, screen) :
"""affichage de la corde � l'aide du module pyagame"""
self.display_courbe_theorique (screen)
x,y = screen.get_size ()
color = (0,0,0)
for p in self.list :
pygame.draw.circle (screen, color, (int (p.x), int (y - p.y)), int (p.m+1))
for i in xrange (0,len (self.list)-1) :
pygame.draw.line (screen, color, \
(int (self.list [i].x), int (y - self.list [i].y)), \
(int (self.list [i+1].x), int (y - self.list [i+1].y))) | [
"def",
"display",
"(",
"self",
",",
"screen",
")",
":",
"self",
".",
"display_courbe_theorique",
"(",
"screen",
")",
"x",
",",
"y",
"=",
"screen",
".",
"get_size",
"(",
")",
"color",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
"for",
"p",
"in",
"self",
".",
"list",
":",
"pygame",
".",
"draw",
".",
"circle",
"(",
"screen",
",",
"color",
",",
"(",
"int",
"(",
"p",
".",
"x",
")",
",",
"int",
"(",
"y",
"-",
"p",
".",
"y",
")",
")",
",",
"int",
"(",
"p",
".",
"m",
"+",
"1",
")",
")",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"self",
".",
"list",
")",
"-",
"1",
")",
":",
"pygame",
".",
"draw",
".",
"line",
"(",
"screen",
",",
"color",
",",
"(",
"int",
"(",
"self",
".",
"list",
"[",
"i",
"]",
".",
"x",
")",
",",
"int",
"(",
"y",
"-",
"self",
".",
"list",
"[",
"i",
"]",
".",
"y",
")",
")",
",",
"(",
"int",
"(",
"self",
".",
"list",
"[",
"i",
"+",
"1",
"]",
".",
"x",
")",
",",
"int",
"(",
"y",
"-",
"self",
".",
"list",
"[",
"i",
"+",
"1",
"]",
".",
"y",
")",
")",
")"
] | [
62,
4
] | [
72,
86
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Admin.emergency_cmd | (self, ctx: MyContext) | Déclenche la procédure d'urgence
A N'UTILISER QU'EN CAS DE BESOIN ABSOLU ! Le bot quittera tout les serveurs après avoir envoyé un mp à chaque propriétaire | Déclenche la procédure d'urgence
A N'UTILISER QU'EN CAS DE BESOIN ABSOLU ! Le bot quittera tout les serveurs après avoir envoyé un mp à chaque propriétaire | async def emergency_cmd(self, ctx: MyContext):
"""Déclenche la procédure d'urgence
A N'UTILISER QU'EN CAS DE BESOIN ABSOLU ! Le bot quittera tout les serveurs après avoir envoyé un mp à chaque propriétaire"""
await ctx.send(await self.emergency()) | [
"async",
"def",
"emergency_cmd",
"(",
"self",
",",
"ctx",
":",
"MyContext",
")",
":",
"await",
"ctx",
".",
"send",
"(",
"await",
"self",
".",
"emergency",
"(",
")",
")"
] | [
426,
4
] | [
429,
46
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
get_list_groupes | (df) | return listeGroupes | Renvoie un dictionnaire qui à chaque index de groupe
renvoie un objet Groupe donnant sa composition.
| Renvoie un dictionnaire qui à chaque index de groupe
renvoie un objet Groupe donnant sa composition.
| def get_list_groupes(df):
"""Renvoie un dictionnaire qui à chaque index de groupe
renvoie un objet Groupe donnant sa composition.
"""
global numPassager
listeGroupes = dict()
for idx, row in df.iterrows():
listeGroupes[idx] = Groupe(
idx=idx,
nb_femmes=row['Femmes'],
nb_hommes=row['Hommes'],
nb_enfants=row['Enfants'],
nb_WCHR=row['WCHR'],
classe=row['Classe'],
transit_time=string_to_min(str(row['TransitTime']))
)
numPassager = 0 # Réinitialisation du compteur
return listeGroupes | [
"def",
"get_list_groupes",
"(",
"df",
")",
":",
"global",
"numPassager",
"listeGroupes",
"=",
"dict",
"(",
")",
"for",
"idx",
",",
"row",
"in",
"df",
".",
"iterrows",
"(",
")",
":",
"listeGroupes",
"[",
"idx",
"]",
"=",
"Groupe",
"(",
"idx",
"=",
"idx",
",",
"nb_femmes",
"=",
"row",
"[",
"'Femmes'",
"]",
",",
"nb_hommes",
"=",
"row",
"[",
"'Hommes'",
"]",
",",
"nb_enfants",
"=",
"row",
"[",
"'Enfants'",
"]",
",",
"nb_WCHR",
"=",
"row",
"[",
"'WCHR'",
"]",
",",
"classe",
"=",
"row",
"[",
"'Classe'",
"]",
",",
"transit_time",
"=",
"string_to_min",
"(",
"str",
"(",
"row",
"[",
"'TransitTime'",
"]",
")",
")",
")",
"numPassager",
"=",
"0",
"# Réinitialisation du compteur",
"return",
"listeGroupes"
] | [
188,
0
] | [
209,
23
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
notify | (textes) | Créer une notification. Le paramètre doit être un tuple
(titre, texte) | Créer une notification. Le paramètre doit être un tuple
(titre, texte) | def notify(textes) :
""" Créer une notification. Le paramètre doit être un tuple
(titre, texte) """
if os.name == "posix" : notification.notify(
title=textes[0], message=textes[1], app_name="alert",
app_icon=ICON)
else :
notif = ToastNotifier()
notif.show_toast(textes[0], textes[1], icon_path=ICON,
duration=470, threaded=True) | [
"def",
"notify",
"(",
"textes",
")",
":",
"if",
"os",
".",
"name",
"==",
"\"posix\"",
":",
"notification",
".",
"notify",
"(",
"title",
"=",
"textes",
"[",
"0",
"]",
",",
"message",
"=",
"textes",
"[",
"1",
"]",
",",
"app_name",
"=",
"\"alert\"",
",",
"app_icon",
"=",
"ICON",
")",
"else",
":",
"notif",
"=",
"ToastNotifier",
"(",
")",
"notif",
".",
"show_toast",
"(",
"textes",
"[",
"0",
"]",
",",
"textes",
"[",
"1",
"]",
",",
"icon_path",
"=",
"ICON",
",",
"duration",
"=",
"470",
",",
"threaded",
"=",
"True",
")"
] | [
38,
0
] | [
47,
40
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
trouve_valeur_dans_arbre_binaire | (arbre, valeur) | return noeud | Trouve une valeur dans l'arbre binaire. | Trouve une valeur dans l'arbre binaire. | def trouve_valeur_dans_arbre_binaire(arbre, valeur):
"""Trouve une valeur dans l'arbre binaire."""
noeud = arbre.noeud
while noeud != None and noeud.valeur != valeur:
if valeur < noeud.valeur:
noeud = noeud.gauche
else:
noeud = noeud.droite
return noeud | [
"def",
"trouve_valeur_dans_arbre_binaire",
"(",
"arbre",
",",
"valeur",
")",
":",
"noeud",
"=",
"arbre",
".",
"noeud",
"while",
"noeud",
"!=",
"None",
"and",
"noeud",
".",
"valeur",
"!=",
"valeur",
":",
"if",
"valeur",
"<",
"noeud",
".",
"valeur",
":",
"noeud",
"=",
"noeud",
".",
"gauche",
"else",
":",
"noeud",
"=",
"noeud",
".",
"droite",
"return",
"noeud"
] | [
19,
0
] | [
28,
16
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
Fourmis.deplacement | (self, couleur) | Déplace la fourmis sur le board d'après les règles du jeu
Args:
couleur (integer): la couleur de la case de départ de la fourmis
| Déplace la fourmis sur le board d'après les règles du jeu | def deplacement(self, couleur):
"""Déplace la fourmis sur le board d'après les règles du jeu
Args:
couleur (integer): la couleur de la case de départ de la fourmis
"""
self.previousPos[0] = self.position[0]
self.previousPos[1] = self.position[1]
if couleur == 0: # case noire
# on déplace la fourmis d'une case à gauche et on change son orientation
# on tourne à gauche
if self.direction == Direction.HAUT:
self.position[1] -= 1
if self.direction == Direction.DROITE:
self.position[0] -= 1
if self.direction == Direction.BAS:
self.position[1] += 1
if self.direction == Direction.GAUCHE:
self.position[0] += 1
self.direction = (self.direction - 1) % 4
if couleur == 1: # case blanche
# On déplace la fourmis d'une case vers la droite
# on tourne à droite
if self.direction == Direction.HAUT:
self.position[1] += 1
if self.direction == Direction.DROITE:
self.position[0] += 1
if self.direction == Direction.BAS:
self.position[1] -= 1
if self.direction == Direction.GAUCHE:
self.position[0] -= 1
self.direction = (self.direction + 1) % 4 | [
"def",
"deplacement",
"(",
"self",
",",
"couleur",
")",
":",
"self",
".",
"previousPos",
"[",
"0",
"]",
"=",
"self",
".",
"position",
"[",
"0",
"]",
"self",
".",
"previousPos",
"[",
"1",
"]",
"=",
"self",
".",
"position",
"[",
"1",
"]",
"if",
"couleur",
"==",
"0",
":",
"# case noire",
"# on déplace la fourmis d'une case à gauche et on change son orientation",
"# on tourne à gauche",
"if",
"self",
".",
"direction",
"==",
"Direction",
".",
"HAUT",
":",
"self",
".",
"position",
"[",
"1",
"]",
"-=",
"1",
"if",
"self",
".",
"direction",
"==",
"Direction",
".",
"DROITE",
":",
"self",
".",
"position",
"[",
"0",
"]",
"-=",
"1",
"if",
"self",
".",
"direction",
"==",
"Direction",
".",
"BAS",
":",
"self",
".",
"position",
"[",
"1",
"]",
"+=",
"1",
"if",
"self",
".",
"direction",
"==",
"Direction",
".",
"GAUCHE",
":",
"self",
".",
"position",
"[",
"0",
"]",
"+=",
"1",
"self",
".",
"direction",
"=",
"(",
"self",
".",
"direction",
"-",
"1",
")",
"%",
"4",
"if",
"couleur",
"==",
"1",
":",
"# case blanche",
"# On déplace la fourmis d'une case vers la droite",
"# on tourne à droite",
"if",
"self",
".",
"direction",
"==",
"Direction",
".",
"HAUT",
":",
"self",
".",
"position",
"[",
"1",
"]",
"+=",
"1",
"if",
"self",
".",
"direction",
"==",
"Direction",
".",
"DROITE",
":",
"self",
".",
"position",
"[",
"0",
"]",
"+=",
"1",
"if",
"self",
".",
"direction",
"==",
"Direction",
".",
"BAS",
":",
"self",
".",
"position",
"[",
"1",
"]",
"-=",
"1",
"if",
"self",
".",
"direction",
"==",
"Direction",
".",
"GAUCHE",
":",
"self",
".",
"position",
"[",
"0",
"]",
"-=",
"1",
"self",
".",
"direction",
"=",
"(",
"self",
".",
"direction",
"+",
"1",
")",
"%",
"4"
] | [
23,
4
] | [
57,
53
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
ListeAccords.HarmonicDescriptors | (self) | Transforme chaque verticalite en objet Accord, calcule la concordance, la coherence et les concordances multiples, et stocke les resultats
sous forme de liste d'Accords"
| Transforme chaque verticalite en objet Accord, calcule la concordance, la coherence et les concordances multiples, et stocke les resultats
sous forme de liste d'Accords"
| def HarmonicDescriptors (self):
''' Transforme chaque verticalite en objet Accord, calcule la concordance, la coherence et les concordances multiples, et stocke les resultats
sous forme de liste d'Accords"
'''
Prec = 0
compte = 1
global listeSpectresAccords, listeSpectresAccords_pic
listeSpectresAccords = []
listeSpectresAccords_pic = []
for verticality in self.tree.iterateVerticalities():
v = Accord(verticality, self.partiels, self.amplitudes, self.K, self.sig, self.decr,self.memory_size, self.memory_decr_ponderation, self.temperament,self.noteDeReferencePourLeTunning)
if verticality.bassTimespan!=None :
v.identifiant = verticality.bassTimespan.element.id
v.ListeHauteursAvecMultiplicite()
v.NombreDeNotes()
if v.nombreDeNotes>=1:
v.SpectreAccord()
listeSpectresAccords.append(v.spectreAccord)
listeSpectresAccords_pic.append(v.spectreAccord_pic)
v.Context()
v.HarmonicChange(Prec)
v.DiffConcordanceContext(Prec)
v.DiffRoughnessContext(Prec)
Prec = v
self.grandeursHarmoniques.append(v)
# print('Accord {}: OK'.format(compte))
compte += 1 | [
"def",
"HarmonicDescriptors",
"(",
"self",
")",
":",
"Prec",
"=",
"0",
"compte",
"=",
"1",
"global",
"listeSpectresAccords",
",",
"listeSpectresAccords_pic",
"listeSpectresAccords",
"=",
"[",
"]",
"listeSpectresAccords_pic",
"=",
"[",
"]",
"for",
"verticality",
"in",
"self",
".",
"tree",
".",
"iterateVerticalities",
"(",
")",
":",
"v",
"=",
"Accord",
"(",
"verticality",
",",
"self",
".",
"partiels",
",",
"self",
".",
"amplitudes",
",",
"self",
".",
"K",
",",
"self",
".",
"sig",
",",
"self",
".",
"decr",
",",
"self",
".",
"memory_size",
",",
"self",
".",
"memory_decr_ponderation",
",",
"self",
".",
"temperament",
",",
"self",
".",
"noteDeReferencePourLeTunning",
")",
"if",
"verticality",
".",
"bassTimespan",
"!=",
"None",
":",
"v",
".",
"identifiant",
"=",
"verticality",
".",
"bassTimespan",
".",
"element",
".",
"id",
"v",
".",
"ListeHauteursAvecMultiplicite",
"(",
")",
"v",
".",
"NombreDeNotes",
"(",
")",
"if",
"v",
".",
"nombreDeNotes",
">=",
"1",
":",
"v",
".",
"SpectreAccord",
"(",
")",
"listeSpectresAccords",
".",
"append",
"(",
"v",
".",
"spectreAccord",
")",
"listeSpectresAccords_pic",
".",
"append",
"(",
"v",
".",
"spectreAccord_pic",
")",
"v",
".",
"Context",
"(",
")",
"v",
".",
"HarmonicChange",
"(",
"Prec",
")",
"v",
".",
"DiffConcordanceContext",
"(",
"Prec",
")",
"v",
".",
"DiffRoughnessContext",
"(",
"Prec",
")",
"Prec",
"=",
"v",
"self",
".",
"grandeursHarmoniques",
".",
"append",
"(",
"v",
")",
"# print('Accord {}: OK'.format(compte))",
"compte",
"+=",
"1"
] | [
138,
4
] | [
170,
23
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
sample_user | (email='[email protected]', password='123456') | return get_user_model().objects.create_user(email, password) | cree un utilisateur de test | cree un utilisateur de test | def sample_user(email='[email protected]', password='123456'):
"""cree un utilisateur de test"""
return get_user_model().objects.create_user(email, password) | [
"def",
"sample_user",
"(",
"email",
"=",
"'[email protected]'",
",",
"password",
"=",
"'123456'",
")",
":",
"return",
"get_user_model",
"(",
")",
".",
"objects",
".",
"create_user",
"(",
"email",
",",
"password",
")"
] | [
6,
0
] | [
8,
64
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
InterfaceJeu.updateColors | (self) | Met à jour les couleurs des carreaux | Met à jour les couleurs des carreaux | def updateColors(self):
"""Met à jour les couleurs des carreaux"""
for i, ligne in enumerate(self.board.matrix):
for j, pixel in enumerate(ligne):
tag = str(j)+"-"+str(i)
C = self.canvas.find_withtag(tag)
if pixel == 1:
self.canvas.itemconfigure(C, fill = "green")
if pixel == 2:
self.canvas.itemconfigure(C, fill = "red") | [
"def",
"updateColors",
"(",
"self",
")",
":",
"for",
"i",
",",
"ligne",
"in",
"enumerate",
"(",
"self",
".",
"board",
".",
"matrix",
")",
":",
"for",
"j",
",",
"pixel",
"in",
"enumerate",
"(",
"ligne",
")",
":",
"tag",
"=",
"str",
"(",
"j",
")",
"+",
"\"-\"",
"+",
"str",
"(",
"i",
")",
"C",
"=",
"self",
".",
"canvas",
".",
"find_withtag",
"(",
"tag",
")",
"if",
"pixel",
"==",
"1",
":",
"self",
".",
"canvas",
".",
"itemconfigure",
"(",
"C",
",",
"fill",
"=",
"\"green\"",
")",
"if",
"pixel",
"==",
"2",
":",
"self",
".",
"canvas",
".",
"itemconfigure",
"(",
"C",
",",
"fill",
"=",
"\"red\"",
")"
] | [
396,
1
] | [
405,
47
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
Events.check_mp_adv | (self, msg: discord.Message) | Teste s'il s'agit d'une pub MP | Teste s'il s'agit d'une pub MP | async def check_mp_adv(self, msg: discord.Message):
"""Teste s'il s'agit d'une pub MP"""
if self.bot.zombie_mode:
return
if msg.author.id == self.bot.user.id or 'discord.gg/' not in msg.content:
return
try:
_ = await self.bot.fetch_invite(msg.content)
except:
return
# d = datetime.datetime.utcnow() - (await msg.channel.history(limit=2).flatten())[1].created_at
# if d.total_seconds() > 600:
await msg.channel.send(await self.bot._(msg.channel,"events.mp-adv")) | [
"async",
"def",
"check_mp_adv",
"(",
"self",
",",
"msg",
":",
"discord",
".",
"Message",
")",
":",
"if",
"self",
".",
"bot",
".",
"zombie_mode",
":",
"return",
"if",
"msg",
".",
"author",
".",
"id",
"==",
"self",
".",
"bot",
".",
"user",
".",
"id",
"or",
"'discord.gg/'",
"not",
"in",
"msg",
".",
"content",
":",
"return",
"try",
":",
"_",
"=",
"await",
"self",
".",
"bot",
".",
"fetch_invite",
"(",
"msg",
".",
"content",
")",
"except",
":",
"return",
"# d = datetime.datetime.utcnow() - (await msg.channel.history(limit=2).flatten())[1].created_at",
"# if d.total_seconds() > 600:",
"await",
"msg",
".",
"channel",
".",
"send",
"(",
"await",
"self",
".",
"bot",
".",
"_",
"(",
"msg",
".",
"channel",
",",
"\"events.mp-adv\"",
")",
")"
] | [
214,
4
] | [
226,
77
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |
|
PrivatRecipeApiTest.test_create_recipe_with_ingredients | (self) | creation de recette avec ingredients | creation de recette avec ingredients | def test_create_recipe_with_ingredients(self):
""" creation de recette avec ingredients"""
ing1 = sample_ingredient(user=self.user, name='poire')
ing2 = sample_ingredient(user=self.user, name='chou')
payload = {
'title': 'pot au feu',
'ingredients': [ing1.id, ing2.id],
'time_minutes': 60,
'price': 100
}
res = self.client.post(RECIPES_URL, payload)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)
recipe = Recipe.objects.get(id=res.data['id'])
ingredients = recipe.ingredients.all()
self.assertEqual(ingredients.count(), 2)
self.assertIn(ing1, ingredients)
self.assertIn(ing2, ingredients) | [
"def",
"test_create_recipe_with_ingredients",
"(",
"self",
")",
":",
"ing1",
"=",
"sample_ingredient",
"(",
"user",
"=",
"self",
".",
"user",
",",
"name",
"=",
"'poire'",
")",
"ing2",
"=",
"sample_ingredient",
"(",
"user",
"=",
"self",
".",
"user",
",",
"name",
"=",
"'chou'",
")",
"payload",
"=",
"{",
"'title'",
":",
"'pot au feu'",
",",
"'ingredients'",
":",
"[",
"ing1",
".",
"id",
",",
"ing2",
".",
"id",
"]",
",",
"'time_minutes'",
":",
"60",
",",
"'price'",
":",
"100",
"}",
"res",
"=",
"self",
".",
"client",
".",
"post",
"(",
"RECIPES_URL",
",",
"payload",
")",
"self",
".",
"assertEqual",
"(",
"res",
".",
"status_code",
",",
"status",
".",
"HTTP_201_CREATED",
")",
"recipe",
"=",
"Recipe",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"res",
".",
"data",
"[",
"'id'",
"]",
")",
"ingredients",
"=",
"recipe",
".",
"ingredients",
".",
"all",
"(",
")",
"self",
".",
"assertEqual",
"(",
"ingredients",
".",
"count",
"(",
")",
",",
"2",
")",
"self",
".",
"assertIn",
"(",
"ing1",
",",
"ingredients",
")",
"self",
".",
"assertIn",
"(",
"ing2",
",",
"ingredients",
")"
] | [
132,
4
] | [
149,
40
] | null | python | fr | ['fr', 'fr', 'fr'] | True | true | null |