def getAllAndroidSDKTargets(): utils.execute("android list target > target_list.log") with open("target_list.log", "r") as fd: return [ line.strip() for line in fd.readlines() if line.startswith("id:") ] utils.removeFile("target_list.log")
def _clean_env(self): del_file_list = ["src", "bin", "gen", "res", "AndroidManifest.xml"] print "Start to clean env...." for file in del_file_list: utils.removeFile(os.path.join(self._proj_path, file)) # shutil.rmtree( os.path.join( self._proj_path, "src" )) # shutil.rmtree(os.path.join(self._proj_path, "bin")) # shutil.rmtree(os.path.join(self._proj_path, "gen")) # shutil.rmtree(os.path.join(self._proj_path, "res")) # # shutil.rmtree( os.path.join( self._proj_path, "libs" ) ) # os.remove( os.path.join( self._proj_path, "AndroidManifest.xml" )) if os.path.exists(TEMP_SVN_PATH): #存在.svn文件,用更新 exec_cmd("svn up %s 1>&0" % self._proj_path) else: #不存在.svn文件,用导出 svn_url = config.APK_TEMP_FILE_SVN % (self._version, self._config["project_name"]) exec_cmd("svn export --force --ignore-externals %s %s" % (svn_url, self._proj_path))
def readGeomFile(filename): """Read a pyFormex Geometry File. A pyFormex Geometry File can store multiple geometrical objects in a native format that can be efficiently read back into pyformex. The format is portable over different pyFormex versions and even to other software. - `filename`: the name of an existing pyFormex Geometry File. If the filename ends on '.gz', it is considered to be a gzipped file and will be uncompressed transparently during the reading. Returns a dictionary with the geometric objects read from the file. If object names were stored in the file, they will be used as the keys. Else, default names will be provided. """ gzip = filename.endswith('.gz') if gzip: filename = utils.gunzip(filename, unzipped='', remove=False) f = geomfile.GeometryFile(filename, mode='r') objects = f.read() if gzip: utils.removeFile(filename) return objects
def readGeomFile(filename): """Read a pyFormex Geometry File. A pyFormex Geometry File can store multiple geometrical objects in a native format that can be efficiently read back into pyformex. The format is portable over different pyFormex versions and even to other software. - `filename`: the name of an existing pyFormex Geometry File. If the filename ends on '.gz', it is considered to be a gzipped file and will be uncompressed transparently during the reading. Returns a dictionary with the geometric objects read from the file. If object names were stored in the file, they will be used as the keys. Else, default names will be provided. """ gzip = filename.endswith('.gz') if gzip: filename = utils.gunzip(filename,unzipped='',remove=False) f = geomfile.GeometryFile(filename,mode='r') objects = f.read() if gzip: utils.removeFile(filename) return objects
def training(): # One Epoch is when an Entire dataset is passed forward and backward through the neural network only ONCE! epochs = 1000 #Total number of training example present in a sigle batch batch_size = 32 training_percentage = 0.8 # file path file_path = os.path.dirname(os.path.abspath(inspect.stack()[0][1])) savings = file_path + '\\savings\\' dataset = file_path + '\\dataset\\' tokenizer_file = os.path.join(savings, 't.pickle') encoder_file = os.path.join(savings, 'e.pickle') class_file = os.path.join(savings, 'c.pickle') model_file = os.path.join(savings, 'm.h5') dataset_file = os.path.join(dataset, 'Youtube01-Psy.csv') #Create savings folder if not exists os.makedirs(os.path.dirname(tokenizer_file), exist_ok=True) removeFile(tokenizer_file) removeFile(encoder_file) removeFile(class_file) removeFile(model_file) data = pd.read_csv('data.txt') print(data.head()) training_size = int(len(data) * training_percentage) train_content = data['text'][:training_size] train_class = data['result'][:training_size] test_content = data['text'][training_size:] test_class = data['result'][training_size:] number_words_dataset = countingWords(train_content) tokenize = text.Tokenizer(num_words=number_words_dataset , char_level=False) tokenize.fit_on_texts(train_content) # tf-idf x_train = tokenize.texts_to_matrix(train_content, mode='tfidf') x_test = tokenize.texts_to_matrix(test_content, mode='tfidf') with open(tokenizer_file, 'wb') as handle: pickle.dump(tokenize,handle, protocol=pickle.HIGHEST_PROTOCOL) encoder = LabelEncoder() encoder.fit(train_class) y_train = encoder.transform(train_class) y_test = encoder.transform(test_class) with open(encoder_file, 'wb') as handle: pickle.dump(encoder,handle, protocol=pickle.HIGHEST_PROTOCOL) num_classes = np.max(y_train + 1) with open(class_file, 'wb') as handle: pickle.dump(num_classes,handle) y_train = utils.to_categorical(y_train, num_classes) y_test = utils.to_categorical(y_test, num_classes) ############################################################################################# model = Sequential() model.add(Dense(num_classes * 8, input_shape=(number_words_dataset,), activation = 'relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes * 4, activation = 'relu')) model.add(Dropout(0.2)) model.add(Dense(num_classes * 2, activation = 'relu')) model.add(Dropout(0.2)) #output layer model.add(Dense(num_classes, activation = 'softmax')) ############################################################################################# model.compile(loss= 'binary_crossentropy', optimizer= 'adam', metrics=['categorical_accuracy']) # model.compile(loss= 'categorical_crossentropy', # optimizer= 'adam', # metrics=['accuracy']) stopper = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta= 0, patience=2, verbose=1, mode='auto', baseline=None) model_history = model.fit(x_train,y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1, callbacks=[stopper]) score = model.evaluate(x_test, y_test, batch_size=batch_size,verbose=1) print("\n\n Test score: ", score[0]) print("\n\n Test accuracy: ", score[1]) model.save(model_file) # plot with losses loss = model_history.history['loss'] val_loss = model_history.history['val_loss'] plt.plot(loss) plt.plot(val_loss) plt.legend(['loss', 'val_loss']) plt.ylabel('Loss', fontsize=15) plt.xlabel('Epochs', fontsize=15) plt.show() text_labels = encoder.classes_ y_softmax = model.predict(x_test) y_test_1d = [] y_pred_1d = [] for i in range(len(y_test)): probs = y_test[i] index_arr = np.nonzero(probs) one_hot_index = index_arr[0].item(0) y_test_1d.append(one_hot_index) for i in range(0, len(y_softmax)): probs = y_softmax[i] predicted_index = np.argmax(probs) y_pred_1d.append(predicted_index) def plot_confusion_matrix(cm, classes, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title, fontsize=20) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45, fontsize=15) plt.yticks(tick_marks, classes, fontsize=15) fmt = '.2f' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.ylabel('True label', fontsize=20) plt.xlabel('Predicted label', fontsize=20) cnf_matrix = confusion_matrix(y_test_1d, y_pred_1d) plt.figure(figsize=(44,37)) plot_confusion_matrix(cnf_matrix, classes=text_labels, title="Confusion matrix") plt.show()
def training(): # One Epoch is when an Entire dataset is passed forward and backward through the neural network only ONCE! epochs = 1000 #Total number of training example present in a sigle batch batch_size = 32 training_percentage = 0.8 # file path file_path = './' savings = file_path + 'savings' dataset = file_path + 'dataset' tokenizer_file = os.path.join(savings, 't.pickle') encoder_file = os.path.join(savings, 'e.pickle') class_file = os.path.join(savings, 'c.pickle') model_file = os.path.join(savings, 'm.h5') dataset_file = os.path.join(dataset, 'demofile.csv') #Create savings folder if not exists os.makedirs(os.path.dirname(tokenizer_file), exist_ok=True) removeFile(tokenizer_file) removeFile(encoder_file) removeFile(class_file) removeFile(model_file) data = pd.read_csv(dataset_file) print(data.head()) training_size = int(len(data) * training_percentage) train_content = data['CONTENT'][:training_size] train_class = data['CLASS'][:training_size] test_content = data['CONTENT'][training_size:] test_class = data['CLASS'][training_size:] number_words_dataset = countingWords(train_content) tokenize = text.Tokenizer(num_words=number_words_dataset, char_level=False) tokenize.fit_on_texts(train_content) # tf-idf x_train = tokenize.texts_to_matrix(train_content, mode='tfidf') x_test = tokenize.texts_to_matrix(test_content, mode='tfidf') with open(tokenizer_file, 'wb') as handle: pickle.dump(tokenize, handle, protocol=pickle.HIGHEST_PROTOCOL) encoder = LabelEncoder() encoder.fit(train_class) y_train = encoder.transform(train_class) y_test = encoder.transform(test_class) with open(encoder_file, 'wb') as handle: pickle.dump(encoder, handle, protocol=pickle.HIGHEST_PROTOCOL) num_classes = np.max(y_train + 1) with open(class_file, 'wb') as handle: pickle.dump(num_classes, handle) y_train = utils.to_categorical(y_train, num_classes) y_test = utils.to_categorical(y_test, num_classes) model = Sequential() model.add( Dense(num_classes * 8, input_shape=(number_words_dataset, ), activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes * 4, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(num_classes * 2, activation='relu')) model.add(Dropout(0.2)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) stopper = keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=2, verbose=1, mode='auto', baseline=None) model_history = model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_split=0.1, callbacks=[stopper]) score = model.evaluate(x_test, y_test, batch_size=batch_size, verbose=1) print("\n\n Test score: ", score[0]) print("\n\n Test accuracy: ", score[1]) model.save(model_file) acc = model_history.history['acc'] val_loss = model_history.history['val_loss'] plt.plot(acc) plt.plot(val_loss) plt.legend(['acc', 'val_loss']) plt.ylabel('Loss', fontsize=15) plt.xlabel('Epochs', fontsize=15) plt.show()
def clean(self): utils.removeFile(utils.tempPath(InstallLib.FORGE_NAME)) utils.removeFile(InstallLib.FORGE_NAME + ".log") utils.removeFile(utils.tempPath(InstallLib.MODPACK_NAME))
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 ("")