def verifyReturn(): content = walkTable() varTypes = [] paramTypes = [] retorno = [] for item in content: if 'info' in item and item['info'][0]['categoria'] == 'variavel': varTypes.append(item['info'][0]['lexema']+'-'+item['tipo']) if 'categoria' in item and item['categoria'] == 'funcao': if len(item['parametros']) > 0: for e in item['parametros']: paramTypes.append(e['lexema']+'-'+e['tipo']) if 'retorno' in item: for r in item['retorno']: retorno.append(r['elemento']) for item in content: if 'categoria' in item and item['categoria'] == 'funcao': if 'retorno' not in item and item['tipo'] != 'vazio': showErrors(getLine(item['lexema']), 'err', item['lexema'], 2) exit(0) for e in range(len(varTypes)): var = varTypes[e].split('-')[0] tipo = varTypes[e].split('-')[1] if var in retorno and tipo != item['tipo']: showErrors(getLine(item['lexema']), 'err', item['lexema'], 2) exit(0) for i in range(len(paramTypes)): param = paramTypes[i].split('-')[0] tipoP = paramTypes[i].split('-')[1] if param in retorno and tipoP != item['tipo']: showErrors(getLine(item['lexema']), 'err', param, 2) exit(0) for r in retorno: if '.' in r and item['tipo'] == 'inteiro': showErrors(getLine('retorna'), 'err', r, 2) exit(0) elif '.' not in r and item['tipo'] == 'flutuante': showErrors(getLine('retorna'), 'err', r, 2) exit(0)
def verifyVarStatement(): content = walkTable() var = [] for item in content: if 'info' in item: if 'lexema' in item['info']: var.append(item['info']['lexema']+'-'+item['escopo']) else: for e in range(len(item['info'])): if 'lexema' in item['info'][e]: var.append(item['info'][e]['lexema']+'-'+item['escopo']) for i in range(0, len(var)): elementi = var[i].split('-')[0] escopo = var[i].split('-')[1] for j in range(0, i): elementj = var[j].split('-')[0] escopoSec = var[j].split('-')[1] if (var[i] == var[j] or (elementi == elementj and escopo != escopoSec)): linha = getLine(elementi) showErrors(linha, 'err', elementi, 11) exit(0)
def read(self,fp): """""" if not self.header.parse(fp): log.error("BaseSPFReader : Can't parse header section, line %d"%common.counter) return False #data section s=getLine(fp) if not s or s!='DATA': log.error("BaseSPFReader : Can't find DATA section, line %d"%common.counter) return False #id=ENTITYNAME(......) while True: beg=0 #log.debug("Reading line %d"%common.counter) s=getLine(fp) if not s: log.error("BaseSPFReader : Unexpected End Of File, line %d"%common.counter) return False if s=="ENDSEC": break i=s.find('=') if i==-1 or s[0]!='#': log.error("BaseSPFReader : Syntax error on entity id, line %d"%common.counter) return False self.currentId=int(s[1:i]) beg=i+1 i=s.find('(',beg) if i==-1 or s[-1]!=')': log.error("BaseSPFReader : Syntax error on entity definition, line %d"%common.counter) return False entityName=s[beg:i] line=s[i+1:-1] currentObj=self.expDataSet.getSPFObject(self.currentId,entityName); currentObj.args.setParams(line) currentObj.load() #log.error("BaseSPFReader : Unexpected entity name : %s line" %(entityName,common.counter)) s=getLine(fp) if not s or s!="END-ISO-10303-21": log.error("BaseSPFReader : Can't find END-ISO-10303-21 token, line %d"%common.counter) return False return True
def read(self,fp): """ read lines to a dict:id->key(params) """ if not self.header.parse(fp): log.error("SubModel : Can't parse header section, line %d"%common.counter) return False #data section s=getLine(fp) if not s or s!='DATA': log.error("SubModel : Can't find DATA section, line %d"%common.counter) return False #id=ENTITYNAME(......) while True: beg=0 s=getLine(fp) if not s: log.error("SubModel : Unexpected End Of File, line %d"%common.counter) return False if s=="ENDSEC": break i=s.find('=') if i==-1 or s[0]!='#': log.error("SubModel : Syntax error on entity id, line %d"%common.counter) return False entityId=int(s[1:i]) beg=i+1 i=s.find('(',beg) if i==-1 or s[-1]!=')': log.error("SubModel : Syntax error on entity definition, line %d"%common.counter) return False entityName=s[beg:i] params=s[i+1:-1] #print "#%s=%s(%s);"%(entityId,entityName,params) self.lines[entityId]=(entityName,params) s=getLine(fp) if not s or s!="END-ISO-10303-21": log.error("SubModel : Can't find END-ISO-10303-21 token, line %d"%common.counter) return False return True
def editLine(storyID=None, lineID=None): if request.method == 'GET' and storyID is not None and lineID is not None and session["logged_in"]: #Retrivies the comment and provides a form to edit return render_template("editLine.html", comment=utils.getLine(lineID)) elif request.method == 'POST' and storyID is not None and lineID is not None: #Edits the line utils.editLine(session["username"],lineID,request.form['line']) return redirect(url_for("story", ID=storyID)) else: return redirect(url_for("home"))
def findVar(tree): st = {} variaveis = [] for node in PreOrderIter(tree): node_name = name(node) if node_name == 'declaracao_variaveis': for n in PreOrderIter(node): if name(n) == 'tipo': st['tipo'] = name(n.children[0]) if 'declaracao_funcao' not in str(n.ancestors): st['escopo'] = 'global' else: st['escopo'] = 'local' elif name(n) == 'lista_variaveis': dados = {} st['info'] = [] for e in PreOrderIter(n): if len(n.children) >= 1: if name(e) == 'var': dados['lexema'] = name(e.children[0]) for i in PreOrderIter(e): if name(i.parent) == 'fator' and i.children[0].is_leaf: linha = getLine(dados['lexema']) if name(i) != 'numero' or '.' in name(i.children[0]): showErrors(linha, 'err', dados['lexema']+'['+name(i.children[0])+']', 13) exit(0) dados['categoria'] = 'vetor' dados['dimensao'] = name(i.children[0]) elif name(i.parent) == 'var': dados['categoria'] = 'variavel' st['info'].append(dados) dados = {} else: dados['lexema'] = name(e) dados['categoria'] = 'variavel' st['info'] = dados dados = {} variaveis.append(st) st = {} return variaveis
def sayCurrentLine(): global instanceGP if (configBE.conf['general']['speakScroll'] or configBE.conf['general']['alwaysSpeakScroll'] ) and not instanceGP.autoScrollRunning: try: if braille.handler.tether == braille.handler.TETHER_REVIEW: scriptHandler.executeScript( globalCommands.commands.script_review_currentLine, None) ui.message(unicode(self.rawText).replace('\0', '')) elif configBE.conf['general']['alwaysSpeakScroll']: speech.speakMessage(getLine()) except BaseException: pass
def verifyCallFunc(tree): content = walkTable() funcsTable = [] funcsTree = [] for item in content: if 'categoria' in item and item['categoria'] == 'funcao': funcsTable.append(item['lexema']) for e in PreOrderIter(tree): if name(e) == 'chamada_funcao': funcsTree.append(name(e.children[0])) for func in funcsTree: if func not in funcsTable: linha = getLine(func) showErrors(linha, 'err', func, 10) exit(0) for func in funcsTable: if func not in funcsTree and func != 'principal': linha = getLine(func) showErrors(linha, 'warn', func, 8)
def getStringFromCondition(conj): res = '' first = True value = sorted(conj, key = sortIfKey) for if_node, flag in value: filename = utils.getFileName(if_node.node) lineno = utils.getLine (if_node.node) if first: first = False prefix = '' else: prefix = ' and ' added = '%s:%d == %s' % (filename, lineno, flag) res += prefix + added return res
def verifyFuncStatement(): content = walkTable() funcs = [] for item in content: if 'categoria' in item and item['categoria'] == 'funcao': funcs.append(item['lexema']) if 'principal' not in funcs: showErrors('-', 'err', 'programa', 18) exit(0) for i in range(0, len(funcs)): for j in range(0, i): if funcs[i] == funcs[j]: linha = getLine(funcs[i]) showErrors(linha, 'err', funcs[i], 5) exit(0)
def sortIfKey(tup): return utils.getLine(tup[0].node)
def parse(self,fp): """parse the header of ifc file """ s=getLine(fp) if not s or s !="ISO-10303-21": log.error("SPFHeader : Bad file type, should be ISO-10303-21.") return False s=getLine(fp) if not s or s!="HEADER": log.error("SPFHeader : Can't find the HEADER section.") return False # FILE_DESCRIPTION arguments #give a (..) and get a vector of arguments #FILE_DESCRIPTION (('ArchiCAD 7.00 Release 2 generated IFC file.', #'Build Number of the Ifc 2x interface: 00054 (01-10-2002)'), '2;1'); s=getLine(fp) i=s.find('(') if not s.startswith("FILE_DESCRIPTION"): log.error("SPFHeader : Can't find the FILE_DESCRIPTION argument.") return False currentParam=parseList(s[i+1:-1]) if not currentParam or len(currentParam)!=2: log.error("SPFHeader : Bad number of arguments for FILE_DESCRIPTION, should be 2") return False vec=parseList(currentParam[0][1:len(currentParam[0])-1]) if not vec: log.error("SPFHeader : Syntax Error in arg 1 of FILE_DESCRIPTION"); return False for arg in vec: self.fileDescription.description.append(fromSPF(arg)) self.fileDescription.implementationLevel=fromSPF(currentParam[1]) s=getLine(fp) i=s.find('(') if not s.startswith("FILE_NAME"): log.error("SPFHeader : Can't find the FILE_DESCRIPTION argument.") return False currentParam=parseList(s[i+1:-1]) if not currentParam: log.error(" SPFHeader : Bad number of arguments for FILE_DESCRIPTION, should be 7 ") return False self.fileName.name=fromSPF(currentParam[0]) self.fileName.timeStamp=currentParam[1] vec=parseList(currentParam[2][1:-1]) if not vec: log.error("SPFHeader : Syntax Error in arg 3 of FILE_NAME") return False for arg in vec: self.fileName.author.append(fromSPF(arg)) vec=parseList(currentParam[3][1:-1]) if not vec: log.error("SPFHeader : Syntax Error in arg 4 of FILE_NAME") return False for arg in vec: self.fileName.organization.append(fromSPF(arg)) self.fileName.preprocessorVersion=fromSPF(currentParam[4]) self.fileName.originatingSystem =fromSPF(currentParam[5]) self.fileName.authorization =fromSPF(currentParam[6]) s=getLine(fp) i=s.find('(') if not s.startswith("FILE_SCHEMA"): log.error("SPFHeader : Can't find the FILE_SCHEMA argument.") return False currentParam=parseList(s[i+1:-1]) vec=parseList(currentParam[0][1:-1]) for arg in vec: self.fileSchema.schemaIdentifiers.append(fromSPF(arg)) self.otherFields='' found=False for i in range(0,5): s=getLine(fp) if not s: return False if s=="ENDSEC": found=True break self.otherFields+=s if not found: log.error("SPFHeader : Can't find ENDSEC") return False return True
def gestionConnexionClient(self): # fonction appelée lorsqu'une connexion client entrante survient print ("Une connexion entrante est détectée") # -- connexion du client -- self.clientTcpDistant = ( self.serveurTcp.nextPendingConnection() ) # récupère le TcpSocket correspondant au client connecté # l'objet client est un TcpSocket et dispose donc de toutes les fonctions du TcpSocket etatConnexion = self.clientTcpDistant.waitForConnected(5000) # attend connexion pendant 5 secondes maxi # message état connexion if etatConnexion: # si la connexion est OK .. print ("Connexion au serveur OK !") print ( "IP du client connecté : " + str(self.clientTcpDistant.peerAddress().toString()) ) # affiche IP du client distant self.lineEditIPClientDistant.setText(self.clientTcpDistant.peerAddress().toString()) # MAJ champ IP client print ( "IP du serveur local : " + str(self.clientTcpDistant.localAddress().toString()) ) # affiche IP du serveur local auquel le client est connecté self.lineEditIPServeurLocal.setText(self.clientTcpDistant.localAddress().toString()) # MAJ champ IP serveur else: print ("Connexion au serveur impossible...") # exit # sort du try mais reste dans la fonction def return # sort de def # suite si la connexion est ok... # -- lecture des données en réception = réception de la requête du client distant test = self.clientTcpDistant.waitForReadyRead() # attendre que client soit prêt pour réception de données if test == True: print ("Données client distant prêtes") else: print ("Données client distant pas prêtes") chaineTrans = str( self.clientTcpDistant.readAll() ) # lit les données en réception - première lecture - readAll lit ligne à ligne... # chaineTrans =str(self.clientTcpLocal.readData(1024)) # lit les données en réception - première lecture - read() lit ligne à ligne... chaineReception = "" # print chaineTrans - debug # while len(chaineTrans): # tant que chaine Trans pas vide - obligé car réception ligne à ligne while chaineTrans != "": # tant que chaine Trans pas vide - obligé car réception ligne à ligne chaineReception = chaineReception + chaineTrans chaineTrans = "" # RAZ chaine Trans test = self.clientTcpDistant.waitForReadyRead( 1000 ) # attendre que client soit à nouveau prêt pour réception de données if test == True: # si prêt à recevoir données # print ("Client prêt à recevoir des données") chaineTrans = str(self.clientTcpDistant.readAll()) # lit la suite des données en réception # chaineTrans =str(self.clientTcpLocal.readData(1024)) # lit la suite des données en réception - read() lit ligne à ligne... # print self.clientTcpLocal.isOpen() # debug # print (">"+chaineTrans) # debug # else: # print("Client pas prêt à recevoir des données") # -- fin réception réponse client # si on veut message erreur si problème, utiliser readData(taillemax) print ("Données reçues : ") print ("-------------------------------------------") print chaineReception print ("-------------------------------------------") self.textEditReceptionReseau.append(chaineReception) # ajoute réception à la zone texte # -- +/- analyse de la requete reçue -- # ------> analyse si la chaine reçue est une requete GET avec chaine format /&chaine= càd si requête Ajax-------- if chaineReception.startswith("GET /&"): print ("Requête AJAX reçue") reponseAjax = "" # pour mémoriser éléments de la réponse Ajax au fur et à mesure analyse # ----- extraction de la chaine allant de & à = indexStart = chaineReception.find("&") # position debut print ("indexStart = " + str(indexStart)) # debug indexEnd = chaineReception.find("=") # position fin print ("indexEnd = " + str(indexEnd)) # debug chaineAnalyse = chaineReception[ indexStart + 1 : indexEnd ] # garde chaine fonction(xxxx) à partir de GET /&fonction(xxxx)= # [a:b] 1er caractère inclusif (d'où le +1) , dernier exclusif print ("Chaine recue : " + chaineAnalyse) # debug # ---------------------->> +/- ici analyse de la chaine <<------------------ # --- ls ( ) -- # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn) result = utils.testInstructionString( chaineAnalyse, "ls(", True ) # appelle fonction test instruction format fonction(chaine) if result: print ("result = " + result) reponseAjax = reponseAjax + result + "\n" # ajoute à la réponse Ajax # if (result=="/"): cheminAbsolu = self.lineEditCheminRep.text() + result # le chemin absolu à utiliser contenu = utils.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne print (contenu) # affiche le contenu du rép - self.textEdit.setText(contenu) # efface le champ texte et affiche le fichier à la zone texte reponseAjax = reponseAjax + contenu # ajoute à la réponse Ajax # --- read ( ) -- # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn) result = utils.testInstructionString( chaineAnalyse, "read(", True ) # appelle fonction test instruction format fonction(chaine) if result: print ("result = " + result) reponseAjax = reponseAjax + result + "\n" # ajoute à la réponse Ajax # if (result=="/"): cheminAbsolu = self.lineEditCheminRep.text() + "/" + result # le chemin absolu à utiliser # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne contenu = utils.readFile(cheminAbsolu) # readFile renvoie chaine print (contenu) # affiche le contenu du fichier reponseAjax = reponseAjax + contenu # ajoute à la réponse Ajax # --- lines ( ) -- # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn) result = utils.testInstructionString( chaineAnalyse, "lines(", True ) # appelle fonction test instruction format fonction(chaine) if result: print ("result = " + result) reponseAjax = reponseAjax + result + "\n" # ajoute à la réponse Ajax # if (result=="/"): cheminAbsolu = self.lineEditCheminRep.text() + "/" + result # le chemin absolu à utiliser # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne contenu = str(utils.getNumberOfLines(cheminAbsolu)) # getNumberOfLines renvoie int - nombre de lignes print (contenu) # affiche le contenu du fichier reponseAjax = reponseAjax + contenu # ajoute à la réponse Ajax # --- size ( fichier) -- # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn) result = utils.testInstructionString( chaineAnalyse, "size(", True ) # appelle fonction test instruction format fonction(chaine) if result: print ("result = " + result) reponseAjax = reponseAjax + result + "\n" # ajoute à la réponse Ajax # if (result=="/"): cheminAbsolu = self.lineEditCheminRep.text() + "/" + result # le chemin absolu à utiliser # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne contenu = str(utils.sizeFile(cheminAbsolu)) # getNumberOfLines renvoie int - nombre de lignes print (contenu) # affiche le contenu du fichier reponseAjax = reponseAjax + contenu # ajoute à la réponse Ajax # --- write ( ) -- # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn) result = utils.testInstructionString( chaineAnalyse, "write(", True ) # appelle fonction test instruction format fonction(chaine) if result: print ("result = " + result) reponseAjax = reponseAjax + result + "\n" # ajoute à la réponse Ajax subResult = result.split(",") # sépare les sous chaînes séparées par , print subResult if len(subResult) == 2: # si on a bien 2 sous chaînes # if (result=="/"): cheminAbsolu = self.lineEditCheminRep.text() + "/" + subResult[0] # le chemin absolu à utiliser # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne contenu = utils.writeFile(cheminAbsolu, str(subResult[1]) + "\n") # writeFile renvoie chaine print (contenu) # affiche le contenu du fichier reponseAjax = reponseAjax + contenu # ajoute à la réponse Ajax else: reponseAjax = reponseAjax + "Erreur format\n" # ajoute à la réponse Ajax # --- getline ( fichier, ligne) -- # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn) result = utils.testInstructionString( chaineAnalyse, "getline(", True ) # appelle fonction test instruction format fonction(chaine) if result: print ("result = " + result) reponseAjax = reponseAjax + result + "\n" # ajoute à la réponse Ajax subResult = result.split(",") # sépare les sous chaînes séparées par , print subResult if len(subResult) == 2: # si on a bien 2 sous chaînes # if (result=="/"): cheminAbsolu = self.lineEditCheminRep.text() + "/" + subResult[0] # le chemin absolu à utiliser if subResult[1].isalnum(): # si 2ème param est bien en chiffres contenu = utils.getLine(cheminAbsolu, str(subResult[1])) # getLine renvoie chaine print (contenu) # affiche le contenu du fichier reponseAjax = reponseAjax + contenu # ajoute à la réponse Ajax else: reponseAjax = reponseAjax + "Erreur format\n" # ajoute à la réponse Ajax # --- testdatalog ( fichier, nombrelignes) -- # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn) result = utils.testInstructionString( chaineAnalyse, "testdatalog(", True ) # appelle fonction test instruction format fonction(chaine) if result: print ("result = " + result) reponseAjax = reponseAjax + result + "\n" # ajoute à la réponse Ajax subResult = result.split(",") # sépare les sous chaînes séparées par , print subResult if len(subResult) == 2: # si on a bien 2 sous chaînes # if (result=="/"): cheminAbsolu = self.lineEditCheminRep.text() + "/" + subResult[0] # le chemin absolu à utiliser if subResult[1].isalnum(): # si 2ème param est bien en chiffres contenu = self.testDatalog(cheminAbsolu, str(subResult[1])) # testDatalog renvoie chaine print (contenu) # affiche le contenu du fichier reponseAjax = reponseAjax + contenu # ajoute à la réponse Ajax else: reponseAjax = reponseAjax + "Erreur format\n" # ajoute à la réponse Ajax # --- createfile ( ) -- # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn) result = utils.testInstructionString( chaineAnalyse, "createfile(", True ) # appelle fonction test instruction format fonction(chaine) if result: print ("result = " + result) reponseAjax = reponseAjax + result + "\n" # ajoute à la réponse Ajax # if (result=="/"): cheminAbsolu = self.lineEditCheminRep.text() + "/" + result # le chemin absolu à utiliser # contenu = self.getContentDir(cheminAbsolu) # getContentDir renvoie chaîne contenu = utils.createFile(cheminAbsolu) # readFile renvoie chaine print (contenu) # affiche le contenu du fichier reponseAjax = reponseAjax + contenu # ajoute à la réponse Ajax # --- remove ( ) -- # testInstructionString (self, chaineTestIn, chaineRefIn, debugIn) result = utils.testInstructionString( chaineAnalyse, "remove(", True ) # appelle fonction test instruction format fonction(chaine) if result: print ("result = " + result) reponseAjax = reponseAjax + result + "\n" # ajoute à la réponse Ajax # if (result=="/"): cheminAbsolu = self.lineEditCheminRep.text() + "/" + result # le chemin absolu à utiliser contenu = utils.removeFile(cheminAbsolu) # readFile renvoie chaine print (contenu) # affiche le contenu du fichier reponseAjax = reponseAjax + contenu # ajoute à la réponse Ajax # ----- avec params chiffrés --- """ args=utils.testInstructionLong(chaineAnalyse, "lines(", True) # extrait paramètre chaine au format racine (xx,xx,xx,..) if args: # args est True si 1 ou plusieurs paramètres numériques sont trouvés - None sinon print args """ # --- construction de la réponse complète # reponse=self.plainTextEditReponseHttp.toPlainText() +chaineAnalyse+"\n" # Utf-8 # reponse=self.enteteHttp+chaineAnalyse+"\n"+result+"\n" # +str(args)+"\n" # Utf-8 reponse = self.enteteHttp + chaineAnalyse + "\n" + reponseAjax + "\n" self.envoiChaineClientTcp(reponse) # envoi la reponse au client - appelle fonction commune """ self.textEditEnvoiReseau.append(reponse) # ajoute à la zone texte d'envoi print reponse.toAscii() # convertit en ascii le String - avec conversion unicode... #reponse=QString.fromUtf8(reponse) # 2ers octets UTF-8 seulement reponseByteArray=reponse.toAscii() # convertit en ascii le String - avec conversion unicode... #byteArray=QByteArray() #byteArray.append(reponse) test=self.clientTcpDistant.write(reponseByteArray) # écrit les données vers le serveur avec CRLF if test==-1 : print ("Erreur en écriture vers le client") else: print (str(test)+ " octets envoyés vers le client") #self.textEditReceptionReseau.append("Reponse envoyee au client : " + str(reponseByteArray)+"\n") test=self.clientTcpDistant.waitForBytesWritten() # attend fin envoi if test==False : print("Problème envoi") else: print ("envoi réussi") """ # -- fin si GET /& # ---------> si la chaine recue commence par GET et pas une réponse précédente = on envoie page initiale entiere elif chaineReception.startswith("GET"): # -- écriture des données vers le client = envoi de la réponse du serveur local -- # test=self.clientTcpLocal.writeData("GET") # écrit les données vers le serveur # test=self.clientTcpDistant.writeData(str(self.lineEditReponse.text())) # écrit les données vers le serveur # reponse=str(QString.fromUtf8(self.plainTextEditReponse.toPlainText()))+str("\n") # reponse=self.plainTextEditReponseHttp.toPlainText() +self.plainTextEditReponseHtml.toPlainText()+"\n" # Utf-8 # reponseHtml=self.plainTextEditReponseHtml.toPlainText() # partie Html de la réponse # reponseHtml.replace(self.lineEditChaineSubstHtml.text(), "var val = new Array(100,200,300,400,500,600);"); # debug - remplace chaine des valeurs à passer au client # typiquement, la réponse html contient du code javascript avec un tableau de valeurs var val = new Array(0,0,0,0,0,0); # celui-ci est remplacé par le tableau de nouvelles valeurs """ reponseHtml.replace(self.lineEditChaineSubstHtml.text(), "var val = new Array(" +str(self.lcdNumber_A0.intValue())+"," +str(self.lcdNumber_A1.intValue()) +"," +str(self.lcdNumber_A2.intValue())+"," +str(self.lcdNumber_A3.intValue())+"," +str(self.lcdNumber_A4.intValue())+"," +str(self.lcdNumber_A5.intValue()) +");"); # remplace chaine des valeurs à passer au client - ici les valeurs des lcdNumber """ # --- la réponse HTML + Javascript reponseHtml = "" # -- début html + le head avec javascript -- #### ATTENTION : les sections """ """ qui suivent ne sont pas des commentaires mais du code HTML/Javascript actif envoyé au client #### NE PAS EFFACER +++ reponseHtml = ( reponseHtml + """ <!DOCTYPE html> <html> <head> <meta charset=\"utf-8\" /> <title>Titre</title> <!-- Debut du code Javascript --> <script language=\"javascript\" type=\"text/javascript\"> <!-- //-- variables et objets globaux var textarea=null; var textInputX=null; //--- fonction appelée sur clic bouton function onclickButton() { // click Button ON requeteAjax(\"&\"+textInput.value+\"=\", drawData); // envoi requete avec &chaine= et fonction de gestion resultat } // fin onclickButton //--- fonction executee au lancement window.onload = function () { // au chargement de la page textarea = document.getElementById(\"textarea\"); // declare objet canvas a partir id = nom textarea.value=\"\";// efface le contenu textInput= document.getElementById(\"valeur\"); // declare objet champ text a partir id = nom" } // fin onload //--- fonction de requete AJAX function requeteAjax(chaineIn, callback) { var xhr = XMLHttpRequest(); xhr.open(\"GET\", chaineIn, true); // envoi requete avec chaine personnalisee xhr.send(null); //------ gestion de l'évènement onreadystatechange ----- xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { //alert(xhr.responseText); callback(xhr.responseText); } // fin if }; // fin function onreadystatechange } // fin fonction requeteAjax //-- fonction de gestion de la reponse a la requete AJAX -- function drawData(stringDataIn) { // ajoute la réponse au champ texte textarea.value=textarea.value+stringDataIn; // ajoute la chaine au début - décale vers le bas... textarea.setSelectionRange(textarea.selectionEnd-1,textarea.selectionEnd-1); // se place à la fin -1 pour avant saut de ligne } // fin fonction drawData //--> </script> <!-- Fin du code Javascript --> </head> """ ) # les parenthèses encadrent la chaîne et la variable comme si c'était la même ligne # -- le body + fin HTML -- reponseHtml = ( reponseHtml + """ <body> Serveur Python <br/> <input type=\"text\" id=\"valeur\" size=\"50\" /> <button type=\"button\" onclick=\"onclickButton()\">Envoyer</button> <br/> En provenance du serveur : <br/> <textarea id=\"textarea\" rows=\"10\" cols=\"50\" > </textarea> <br/> </body> </html> """ ) # les parenthèses encadrent la chaîne et la variable comme si c'était la même ligne # --- construction de la réponse complète # reponse=self.plainTextEditReponseHttp.toPlainText() +reponseHtml+"\n" # Utf-8 reponse = self.enteteHttp + reponseHtml + "\n" # Utf-8 self.envoiChaineClientTcp(reponse) # envoi la reponse au client - appelle fonction commune """ self.textEditEnvoiReseau.append(reponse) # ajoute à la zone texte d'envoi print reponse.toAscii() # convertit en ascii le String - avec conversion unicode... #reponse=QString.fromUtf8(reponse) # 2ers octets UTF-8 seulement reponseByteArray=reponse.toAscii() # convertit en ascii le String - avec conversion unicode... #byteArray=QByteArray() #byteArray.append(reponse) test=self.clientTcpDistant.write(reponseByteArray) # écrit les données vers le serveur avec CRLF if test==-1 : print ("Erreur en écriture vers le client") else: print (str(test)+ " octets envoyés vers le client") #self.textEditReceptionReseau.append("Reponse envoyee au client : " + str(reponseByteArray)+"\n") test=self.clientTcpDistant.waitForBytesWritten() # attend fin envoi if test==False : print("Problème envoi") else: print ("envoi réussi") """ # -- fin si "GET" = fin envoi page initiale complète # -- fin de la connexion -- self.clientTcpDistant.close() # fin de la connexion print ("Fermeture du client tcp distant effectuée") print ("===========================================") print ("")
def findFunc(tree): st = {} funcoes = [] retorno = False for node in PreOrderIter(tree): st['categoria'] = 'funcao' node_name = name(node) if node_name == 'declaracao_funcao': for n in PreOrderIter(node): if name(n) == 'tipo' and name(n.parent) == 'declaracao_funcao': st['tipo'] = name(n.children[0]) elif name(n) == 'cabecalho': st['lexema'] = name(n.children[0]) if 'tipo' not in str(n.siblings): st['tipo'] = 'vazio' if 'parametro' in str(n.children): parametros = {} st['parametros'] = [] for e in PreOrderIter(n): father = e.parent if name(father) == 'tipo' and name(father.parent) == 'parametro': parametros['tipo'] = name(e) parametros['lexema'] = name(e.parent.siblings[0]) st['parametros'].append(parametros) parametros = {} if st['lexema'] == 'principal': linha = getLine('principal') if len(st['parametros']) >= 1: showErrors(linha, 'err', st['parametros'][0]['tipo'], 19) exit(0) if st['tipo'] != 'inteiro': showErrors(linha, 'err', st['tipo'], 9) exit(0) elif name(n) == 'corpo' and len(st['lexema']) >= 2: for e in PreOrderIter(n): if name(e) == 'chamada_funcao': if e.children[0].is_leaf: linha = e.children[0].lineno - 21 if 'principal' in str(e.children): if st['lexema'] != 'principal': linha = getLine('principal') showErrors(linha, 'err', 'principal', 3) else: showErrors(linha, 'err', 'principal', 4) exit(0) if name(e) == 'retorna': retorno = True st['retorno'] = [] retorno = {} for child in PreOrderIter(e): if (child.is_leaf): retorno['tipo'] = name(child.parent) retorno['elemento'] = name(child) st['retorno'].append(retorno) retorno = {} funcoes.append(st) st = {} return funcoes
def verifyCallVar(tree): content = walkTable() varTable = [] varTableTypes = [] varTree = [] params = [] attrVar = [] funcsTable = [] exp = [] temp = [] for e in PreOrderIter(tree): if name(e) == 'var': varTree.append(name(e.children[0])) if 'escreva' in str(e.ancestors) or 'leia' in str(e.ancestors): temp.append(name(e.children[0])) if name(e) == 'indice': for i in PreOrderIter(e): if i.is_leaf and name(i.parent) != 'numero' or '.' in name(i): showErrors(getLine(name(e.siblings[0])), 'err', name(e.siblings[0]), 13) exit(0) if name(e) == 'var' and name(e.parent) == 'atribuicao': if ('operador_soma' not in str(e.parent.descendants) and 'operador_multiplicacao' not in str(e.parent.descendants)): for i in PreOrderIter(e.siblings[0]): if i.is_leaf and name(i.parent) != 'chamada_funcao': attrVar.append(name(e.children[0])+'_'+name(i)+'_var') elif i.is_leaf and name(i.parent) == 'chamada_funcao': attrVar.append(name(e.children[0])+'_'+name(i)+'_func') else: for i in PreOrderIter(e.siblings[0]): if name(i).startswith('operador_'): for j in PreOrderIter(i.siblings[0]): if j.is_leaf: exp.append(name(e.children[0])+'_'+name(j)) for k in PreOrderIter(i.siblings[1]): if k.is_leaf: exp.append(name(e.children[0])+'_'+name(k)) for item in content: if 'info' in item: if 'lexema' in item['info']: varTable.append(item['info']['lexema']) varTableTypes.append(item['info']['lexema']+'_'+item['tipo']) else: for e in range(len(item['info'])): if 'lexema' in item['info'][e]: varTable.append(item['info'][e]['lexema']) varTableTypes.append(item['info'][e]['lexema']+'_'+item['tipo']) elif 'parametros' in item and len(item['parametros']) > 0: for e in range(len(item['parametros'])): params.append(item['parametros'][e]['lexema']) if 'categoria' in item and item['categoria'] == 'funcao': funcsTable.append(item['lexema']+'_'+item['tipo']) for e in varTableTypes: nameVt = e.split('_')[0] typeVt = e.split('_')[1] for i in attrVar: nameVar = i.split('_')[0] receptVar = i.split('_')[1] category = i.split('_')[2] if category == 'var' and nameVt == nameVar: for j in varTableTypes: if j.split('_')[0] == receptVar and j.split('_')[1] != typeVt: showErrors(getLine(nameVt), 'err', nameVt, 20) exit(0) elif receptVar.isdigit(): if typeVt != 'inteiro': showErrors(getLine(nameVar), 'err', nameVar, 20) exit(0) elif isFloat(receptVar): if typeVt != 'flutuante': showErrors(getLine(nameVar), 'err', nameVar, 20) exit(0) for e in funcsTable: nameFunc = e.split('_')[0] typeFunc = e.split('_')[1] for i in attrVar: nameVar = i.split('_')[0] receptVar = i.split('_')[1] category = i.split('_')[2] for j in varTableTypes: if category == 'func' and nameFunc == receptVar and typeFunc != j.split('_')[1] and nameVar == j.split('_')[0]: showErrors(getLine(nameVar), 'err', nameVar, 20) exit(0) for e in varTableTypes: nameVt = e.split('_')[0] typeVt = e.split('_')[1] for j in exp: nameVar = j.split('_')[0] receptVar = j.split('_')[1] if nameVar == nameVt: for k in varTableTypes: if k.split('_')[0] == receptVar and k.split('_')[1] != typeVt: showErrors(getLine(nameVar), 'err', nameVar, 20) exit(0) elif receptVar.isdigit(): if typeVt != 'inteiro': showErrors(getLine(nameVar), 'err', nameVar, 20) exit(0) elif isFloat(receptVar): if typeVt != 'flutuante': showErrors(getLine(nameVar), 'err', nameVar, 20) exit(0) noRepeat = [] for e in varTree: if varTree.count(e) == 1: noRepeat.append(e) for e in noRepeat: if e not in params and e in varTable: linha = getLine(e) showErrors(linha, 'warn', e, 21) for i in range(0, len(varTree)): element = varTree[i] if element not in varTable and element not in params: linha = getLine(element) showErrors(linha, 'err', element, 14) exit(0) for i in range(0, len(varTable)): element = varTable[i] if element not in varTree or element in temp and element not in attrVar: linha = getLine(element) showErrors(linha, 'warn', element, 1)
def verifyParameters(tree): content = walkTable() size = 0 args = [] params = [] argsComp = [] p = {} a = {} ags = {} for item in content: if 'categoria' in item and item['categoria'] == 'funcao': size = len(item['parametros']) nameFunc = item['lexema'] if size > 0: p['func'] = nameFunc p['tipo'] = item['parametros'][0]['tipo'] p['nome'] = item['parametros'][0]['lexema'] params.append(p) p = {} for e in PreOrderIter(tree): if name(e) == 'lista_argumentos' and name(e.siblings[0]) == nameFunc: newSize = -1 if name(e.children[0]) == 'None': newSize = 0 else: newSize = len(e.children) if newSize != size: linha = getLine(nameFunc) showErrors(linha, 'err', nameFunc, 6) exit(0) else: for i in PreOrderIter(e): if i.is_leaf and name(i.parent) == 'var': a['func'] = nameFunc a['nome'] = name(i) args.append(a) a = {} for item in content: if 'info' in item: if 'lexema' in item['info']: for a in args: if a['nome'] == item['info']['lexema']: ags['func'] = a['func'] ags['nome'] = a['nome'] ags['tipo'] = item['tipo'] argsComp.append(ags) ags = {} else: for e in range(len(item['info'])): if 'lexema' in item['info'][e]: for a in args: if a['nome'] == item['info'][e]['lexema']: ags['func'] = a['func'] ags['nome'] = a['nome'] ags['tipo'] = item['tipo'] argsComp.append(ags) ags = {} for e in params: for i in argsComp: if e['func'] == i['func'] and e['tipo'] != i['tipo']: showErrors(getLine(e['func']), 'err', e['func'], 7) exit(0)