Best Python code snippet using stestr_python
apptextview.py
Source:apptextview.py
1# Created by jmlm at 08/04/2020-15:44 - P52from __future__ import unicode_literals3from prettytable import PrettyTable4from myapp.tools.jmlmtools import clear, colorify, MyError5from myapp.controlers import userchoicetext6from myapp.models.category import Category7from myapp.models.store import Store8from myapp.models.product import Product9from myapp.models.bookmark import Bookmark10"""11All the display 12"""13class ConsoleView:14 """15 The consoleView class16 Attributes :17 lines for the differents menus18 Methods:19 Appli --> the main loop20 display_menuXX --> display each menu21 display_product_detail --> display a product detail22 all the method are loop which can be leaved by user only23 """24 def __init__(self):25 clear()26 self.ligne_sep2=colorify("------------", ['lightgreen'])27 self.ligne_sep1 = colorify(" ------------------------", ['cyan'])28 self.ligne_quitter= colorify("0 - ", ['lightgreen']) + colorify("Quitter", ['lightblue'])29 self.titre = colorify("P5 - Open Food Facts" ,['lightblue']) + " - "30 def appli(self):31 """32 the main loop33 to leave : 0 in the first menu34 :return:35 """36 loop = True37 while loop:38 choix_menu0 = 039 choix_menu11 = 040 choix_menu12 = 041 choix_menu13 = 042 choix_menu21 = 043 choix_menu0 = self.display_menu0()44 if choix_menu0 == 0:45 loop = False46 continue47 elif choix_menu0 == 1:48 choix_menu11 = self.display_menu11()49 if choix_menu11 == 0 :50 continue51 choix_menu12 = self.display_menu12(choix_menu11)52 if choix_menu12 == 0:53 continue54 choix_menu13 = self.display_menu13(choix_menu12)55 else:56 choix_menu21 = self.display_menu21()57 def display_menu0(self):58 """59 display the 1st menu60 the input is treated by the specific class UserChoiceText()61 :return: choice 1 or 2 or 0 to leave the program62 """63 loop = True64 choix_menu = 065 while loop:66 clear()67 print("")68 # The text.69 titre = self.titre + colorify("Menu",['lightyellow'])70 ligne1 = colorify("1 - ",['lightgreen']) + \71 colorify("Retrouver un aliment dans une catégorie",['lightblue'])72 ligne2 = colorify("2 - ", ['lightgreen']) + \73 colorify("Retouver les aliments substitués", ['lightblue'])74 if choix_menu == 999:75 ligneErreur = colorify('Erreur - vous devez entrer un choix valide !',['red'])76 print(ligneErreur)77 else:78 print("")79 print(titre)80 print(self.ligne_sep1)81 print(ligne1)82 print(ligne2)83 print(self.ligne_sep2)84 print(self.ligne_quitter)85 choix=userchoicetext.UserChoiceText()86 choix_menu = choix.choice_prompt_numeric("Entrez votre choix : ")87 if choix_menu in [0,1,2]:88 loop = False89 return choix_menu90 else:91 choix_menu = 99992 def display_menu11(self):93 """94 choose the category --> PyInquirer95 display and choice are treated by UserChoiceText() class96 :param self:97 :return: Category or 0 to go back98 """99 loop = True100 while loop:101 clear()102 print("")103 titre = self.titre + colorify(" Menu1.1",['lightyellow'])104 print(titre)105 print(self.ligne_sep1)106 choix = userchoicetext.UserChoiceText()107 cat = choix.category_choice()108 return cat109 def display_menu21(self):110 """111 choose the bookmark112 the chart is displayed by Prettytable113 user can choose a product to display details of the product itself and the bookmarks114 products115 :param self:116 :return:117 """118 loop = True119 while loop:120 clear()121 print("")122 titre = self.titre + colorify(" Menu2.1",['lightyellow'])123 print(titre)124 print(self.ligne_sep1)125 # build the chart126 print(colorify("\nCi-dessous les produits substitués avec le produit de "127 "substition choisi : ",['lightblue']))128 bookmarkk = Bookmark()129 bookmarks = bookmarkk.get_all_bookmarks()130 x = PrettyTable()131 x.field_names = [' Id ', 'Libelle','---->' , 'Id subst', 'Libelle substitution' ]132 x.align[' Id '] = 'r'133 x.align['Id subst'] = 'r'134 x.align['Libelle'] = "l"135 x.align['Libelle substitution'] = "l"136 list_products = []137 list_products2 = []138 for bookmark in bookmarks:139 ligne_tab=[]140 product = Product()141 prod = product.get_product_byid(bookmark[0])142 prod_subst = product.get_product_byid(bookmark[1])143 list_products.append(prod[0])144 list_products2.append((prod[0],prod_subst[0]))145 ligne_tab.append(prod[0])146 ligne_tab.append(prod[1])147 ligne_tab.append("---->")148 ligne_tab.append(prod_subst[0])149 ligne_tab.append(prod_subst[1])150 x.add_row(ligne_tab)151 print(x.get_string())152 # choose a product to display the details or 0 to go back153 print(colorify("Entrez l'id d'un produit pour obtenir son détail et le sdétails des produits "154 "qui lui sont substituables (0 pour retour au menu)", ['lightblue']))155 choix = userchoicetext.UserChoiceText()156 id = choix.choice_prompt_numeric("Entrez votre choix : ")157 if id == 999:158 input(colorify("Erreur : Vous devez entrer un nombre (id) ou 0 pour retour"159 " au menu - Appuyer sur Entrée pour continuer !", ["red"]))160 continue161 elif id == 0:162 loop = False163 continue164 if id not in list_products:165 input(colorify("Erreur : Vous devez entrer un nombre (id) présent dans la listes ci-dessus"166 " - Appuyer sur Entrée pour continuer !", ["red"]))167 continue168 print(colorify("\nDetail du produit: ", ["lightyellow"]))169 # display details170 self.display_product_detail(prod)171 for list_subst in list_products2:172 if list_subst[0] == id:173 ligne = colorify("\nDétail du bookmark :", ['lightmagenta'])174 print(ligne)175 product = Product()176 prod = product.get_product_byid(list_subst[1])177 self.display_product_detail(prod)178 input(colorify("\n\nAppuyer sur entrée pour continuer : ", ["lightcyan"]))179 def display_menu12(self, idcategory):180 """181 choose the product in category in parameter --> PyInquirer182 display and choice are treated by UserChoiceText() class183 :param idcategory:184 :return: product185 """186 loop = True187 while loop:188 clear()189 print("")190 titre = self.titre + colorify(" Menu1.2", ['lightyellow'])191 print(titre)192 print(self.ligne_sep1)193 choix=userchoicetext.UserChoiceText()194 prod = choix.product_choice_bycat(idcategory)195 return prod196 def display_menu13(self, idproduct):197 """198 display the detail of the product in parameter199 display a chart of products which have nutrisocre = or < to select them to be200 substitutes --> recorded as bookmarks201 :param idproduct:202 :return:203 """204 loop = True205 while loop:206 clear()207 print("")208 titre = self.titre + colorify(" Menu1.3", ['lightyellow'])209 print(titre)210 print(self.ligne_sep1)211 # get the product and its category and its stores212 product = Product()213 prod = product.get_product_byid(idproduct)214 cat = Category()215 category = cat.get_category_byid(prod[5])216 store = Store()217 stores = store.get_store_byproduct(idproduct)218 # display detail219 ligne = colorify("Vous avez selectionné le produit suivant :", ['lightcyan'])220 print(ligne)221 self.display_product_detail(prod,category,stores)222 # get substitutes223 subsitutes = product.get_product_bookmarks(idproduct)224 # get already defined bookmarks225 bookmark= Bookmark()226 bookmarks = [element[1] for element in bookmark.get_bookmark_byproduct(idproduct)]227 # building the display table of substitutes with prettytable228 if len(subsitutes):229 x = PrettyTable()230 x.field_names = ['Substitut','id','Libelle','URL','Score','Grade','categorie']231 x.align['Libelle'] = "l"232 x.align["Score"] = "r"233 list_products = []234 for subsitute in subsitutes:235 subsitute=list(subsitute)236 if subsitute[0] == idproduct:237 continue238 list_products.append(subsitute[0])239 if subsitute[0] in bookmarks:240 subsitute.insert(0, "0")241 subsitute = [colorify(element,['green']) for element in subsitute]242 else:243 subsitute.insert(0,"N")244 x.add_row(subsitute)245 # display chart246 ligne = colorify("\nCi-dessous les produits de substitution possibles "247 "- nutriscore inférieur ou égal - ",['lightcyan']) + \248 colorify("(en vert les produits déjà mis en substitués/ookmarks) ",['green'])249 print(ligne)250 print(x.get_string(fields=['Substitut','id','Libelle','URL','Score','Grade'],reversort=True))251 # input the subsitutes id to be in bookmarks252 # choice are treated by UserChoiceText() class253 message = "Entrez les id des produits qui peuvent remplacer le produit choisi séparés par une " \254 "virgule ','. Ils seront alors enregistrés dans la base (0 pour retour au menu) : "255 choice = userchoicetext.UserChoiceText()256 choix = choice.choice_prompt_text(message)257 if choix == '0':258 return 0259 liste_choix=choix.split(',')260 # treat the user input and the errors261 try:262 for choix in liste_choix:263 if not choix.isdigit():264 ligne = colorify("Erreur : Vous devez entrer des id de produits - Abandon "265 "du traitement",['red','bold'])266 print(ligne)267 raise MyError268 else:269 if int(choix) in list_products:270 bookmark = Bookmark()271 rc = bookmark.add_bookmark(idproduct,choix)272 if rc[0] > 0:273 print("%s" % rc[1])274 ligne = colorify(f"Erreur : Echec création bookmark "275 f"{idproduct} {choix}", ['red'])276 print(ligne)277 raise MyError278 else:279 ligne = colorify(f"Création bookmark {idproduct}-{choix} OK !"280 , ['lightgreen'])281 print(ligne)282 else:283 ligne = colorify(f"Erreur le produit {choix} n'est pas dans la liste"284 f"des produits de substitution --> Abandon de ce choix !\n"285 f"Appuyer sur entrée pour continuer !",['red'])286 print(ligne)287 input("")288 except MyError:289 input (colorify("Abandon du traitement - Appuyer sure entrée pour continuer",['red']))290 continue291 input(colorify("Appuyer sur entrée pour continuer",['lightgreen']))292 # return 0293 def display_product_detail(self,prod,category=None,stores=None):294 """295 Display the detail of the product with its category and stores296 :param prod:297 :param category:298 :param stores:299 :return:300 """301 # to get the category id and the stres id if not specified302 if category is None:303 cat = Category()304 category = cat.get_category_byid(prod[5])305 if stores is None:306 store = Store()307 stores = store.get_store_byproduct(prod[0])308 # display309 ligne = colorify("Produit : ", ['lightcyan']) + \310 colorify(prod[1], ['white']) + " - " + \311 colorify(" Catégorie : ", ['lightcyan']) + \312 colorify(category[1], ['white'])313 print(ligne)314 ligne = colorify("Score Nutriscore : ", ['lightcyan']) + \315 colorify(str(prod[3]), ['white']) + " - " + \316 colorify(" Score Grade : ", ['lightcyan']) + \317 colorify(prod[4], ['white'])318 print(ligne)319 ligne = colorify("URL : ", ["lightcyan"]) + colorify(prod[2], ['white'])320 print(ligne)321 if len(stores) > 1:322 mag = "Magasins : "323 else:324 mag = "Magasin : "325 ligne = colorify(mag, ['lightcyan'])326 for stor in stores:327 ligne += colorify(stor[0], ['white'])328 ligne += " - "...
bot_clean.py
Source:bot_clean.py
1''' bot_clean '''2from __future__ import print_function3import sys4from copy import deepcopy5from itertools import izip6FILENAME = 'tests/test1.in'7INFINITY = 100008UNDEFINED = -19def dijkstra(graph, source, distances, prev):10 '''' calculate the minimum distances '''11 queue = []12 for i in range(len(graph)):13 queue.append(i)14 distances.append(INFINITY)15 prev.append(UNDEFINED)16 distances[source] = 017 while queue != []:18 min_val = INFINITY19 node = UNDEFINED20 for i, val in enumerate(queue):21 if distances[val] < min_val:22 min_val = distances[val]23 node = val24 queue.remove(node)25 for neighbor in range(len(graph)):26 if graph[node][neighbor] != 0:27 alt = distances[node] + graph[node][neighbor]28 if alt < distances[neighbor]:29 distances[neighbor] = alt30 prev[neighbor] = node31def get_route(prev, target):32 ''' create the route from start to target '''33 source = []34 while prev[target] != UNDEFINED:35 source.insert(0, target)36 target = prev[target]37 return source38def dirty_rooms(rooms):39 ''' create list with all dirty rooms '''40 list_rooms = []41 for i in rooms.keys():42 dictionary_room = rooms[i]43 if dictionary_room['state'] == 1:44 list_rooms.append(i)45 return list_rooms46def get_next_room(dist, dirty_rooms_list, rooms):47 '''get next room that can be cleaned '''48 min_val = -100049 room = UNDEFINED50 if len(dirty_rooms_list) == 1:51 room = dirty_rooms_list[0]52 else:53 for i, val in enumerate(dist):54 if i in dirty_rooms_list:55 report = float(rooms[i]['dim']) / (val + 1) # avoid dividing by 056 if report > min_val:57 min_val = report58 room = i59 return room60def get_next_room_min(dist, dirty_rooms_list):61 '''get next room that has the minimum distance from the current position '''62 min_val = INFINITY63 room = UNDEFINED64 if len(dirty_rooms_list) == 1:65 room = dirty_rooms_list[0]66 else:67 for i, val in enumerate(dist):68 if i in dirty_rooms_list:69 if min_val > val:70 min_val = val71 room = i72 return room73def pairwise(iterable):74 ''' generate pairs (x, y) '''75 parameter = iter(iterable)76 return izip(parameter, parameter)77def check_clean_room(substances, rooms):78 ''' verify if the robot contains enough substances '''79 list_subst = rooms['listSubst']80 for id_subst, val in pairwise(list_subst):81 if id_subst in substances.keys() and val > substances[id_subst]:82 return False83 return True84def decrease_substances(substances, room_substances):85 ''' decrease the numbers of substances that are used to clean the current room '''86 for subst_id, val in pairwise(room_substances):87 substances[subst_id] -= val88def get_deposit(distances, deposit_list):89 ''' return the closest deposit '''90 min_val = INFINITY91 room = UNDEFINED92 for i, val in enumerate(distances):93 if i in deposit_list and val < min_val:94 min_val = val95 room = i96 return room97def create_plan1(start, list_dirty_rooms, total_time, substances, rooms,98 graph, total_substances, deposit_list, capacity, heuristic):99 ''' method return a plan and the score'''100 time = 0101 score = 0102 result_list = []103 while list_dirty_rooms != [] and time < total_time:104 distances = []105 prev_steps = []106 dijkstra(graph, start, distances, prev_steps)107 # in function of heuristic choose the perfect room108 if heuristic == 0:109 current_room = get_next_room(distances, list_dirty_rooms, rooms)110 else:111 current_room = get_next_room_min(distances, list_dirty_rooms)112 # if any room can't be cleaned then go to refill the robot113 if check_clean_room(substances, rooms[current_room]):114 next_hop = get_route(prev_steps, current_room)115 for i in next_hop:116 time += graph[start][i]117 result = 'Move(' + str(start) + ", " + str(i) + ")"118 result_list.append(result)119 if i == current_room:120 decrease_substances(substances, rooms[current_room]['listSubst'])121 result = 'Clean(' + str(i) + ")"122 result_list.append(result)123 time += rooms[current_room]['dim']124 score += rooms[current_room]['dim']125 start = i126 list_dirty_rooms.remove(current_room)127 else:128 deposit = get_deposit(distances, deposit_list)129 next_hop = get_route(prev_steps, deposit)130 for i in next_hop:131 time += graph[start][i]132 result = 'Move(' + str(start) + ", " + str(i) + ")"133 result_list.append(result)134 if i == deposit:135 result = 'Refill(' + str(i) + ")"136 result_list.append(result)137 time += 1138 for j in range(total_substances):139 substances[j] = capacity140 start = i141 return score, result_list142def makeplan(filename):143 ''' create plan '''144 open_file = open(filename, 'r')145 # read from file146 line_split = open_file.readline().split(" ")147 nr_graph = int(line_split[0])148 total_time = int(line_split[1])149 total_substances = int(line_split[2])150 capacity = int(line_split[3])151 nr_deposits = int(line_split[4])152 nr_rooms = int(line_split[5])153 nr_edges = int(line_split[6])154 start = int(line_split[7])155 # create substances dictionary= {1: C, 2: C, 3: C }156 substances = {}157 for i in range(total_substances):158 substances[i] = capacity159 deposit_list = []160 line_split = open_file.readline().split(" ")161 for i in range(nr_deposits):162 deposit_list.append(int(line_split[i]))163 # build graph164 graph = [[0 for i in range(nr_graph)] for j in range(nr_graph)]165 for edge in range(nr_edges):166 line_split = open_file.readline().split(" ")167 i = int(line_split[0])168 j = int(line_split[1])169 cost = int(line_split[2])170 graph[i][j] = cost171 graph[j][i] = cost172 # rooms = {id: _ , stare: _, dim: _, nrSubst: _, listSubst: []}173 rooms = {}174 for i in range(nr_rooms):175 line_split = open_file.readline().split(" ")176 id_room = int(line_split[0])177 state = int(line_split[1])178 dimension = int(line_split[2])179 nr_substances = int(line_split[3])180 list_substances = []181 for j in range(nr_substances * 2):182 list_substances.append(int(line_split[j + 4]))183 new_room = {'id': id_room,184 'state': state,185 'dim': dimension,186 'nrSubst': nr_substances,187 'listSubst': list_substances}188 rooms[id_room] = new_room189 list_dirty_rooms = dirty_rooms(rooms)190 (score1, result_list1) = create_plan1(start, deepcopy(list_dirty_rooms), total_time,191 deepcopy(substances), rooms, graph, total_substances,192 deposit_list, capacity, 0)193 (score2, result_list2) = create_plan1(start, deepcopy(list_dirty_rooms), total_time,194 deepcopy(substances), rooms, graph, total_substances,195 deposit_list, capacity, 1)196 if score1 > score2:197 return deepcopy(result_list1)198 else:199 return deepcopy(result_list2)200def main(argv):201 ''' main '''202 print(makeplan(FILENAME))203if __name__ == '__main__':...
run_altmini.py
Source:run_altmini.py
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3"""4Created on Tue Feb 23 10:02:31 20215@author: leguillou6"""7import os8import argparse9import numpy as np10import subprocess11from datetime import datetime12import re13def create_new_config_file(src_file,out_file,list_pattern,list_subst):14 line_added = []15 with open(out_file, 'w') as out:16 with open(src_file, 'r') as src:17 lines = src.readlines()18 for line in lines:19 found = False20 for pattern,subst in zip(list_pattern,list_subst):21 if re.search(pattern, line) and line[:len(pattern)]==pattern\22 and line[len(pattern)] in [' ','=']:23 line_added.append(pattern)24 new_line = subst + '\n'25 out.write(new_line)26 found = True27 if not found:28 out.write(line)29 for pattern,subst in zip(list_pattern,list_subst):30 if pattern not in line_added:31 new_line = subst + '\n'32 out.write(new_line)33if __name__ == "__main__":34 35 pwd = os.path.dirname(os.path.abspath(__file__))36 37 # Parsing38 parser = argparse.ArgumentParser(description='')39 parser.add_argument('--p', 40 default='Exp_joint', 41 type=str) # Path of experiment (useful to restart an existing experiment)42 parser.add_argument('--c1', # Path of 1st config file43 default=os.path.join('examples','config_Example2_BM.py'),44 type=str) 45 parser.add_argument('--c2', # Path of 2nd config file46 default=os.path.join('examples','config_Example2_IT.py'),47 type=str) 48 parser.add_argument('--params1', type=str, default=None) # names of iterable parameters for 1st experiment49 parser.add_argument('--params2', type=str, default=None) # names of iterable parameters for 2nd experiment50 parser.add_argument('--i0', default=0, type=int) # First iteration number (useful if the experiment is restarted)51 parser.add_argument('--imax', default=None, type=int) # Maximum number of iterations52 parser.add_argument('--Kmin', default=1e-3, type=float) # Value of K below which the iterations are stopped53 opts = parser.parse_args()54 print("* Parsing:")55 i0 = opts.i056 imax = opts.imax57 if imax is None:58 imax = np.inf59 path_exp = opts.p 60 if i0==0:61 path_exp += '_'+datetime.now().strftime('%Y-%m-%d_%H%M')62 exp_config_file_1 = opts.c163 exp_config_file_2 = opts.c264 params1 = opts.params165 params2 = opts.params266 Kmin = opts.Kmin67 print('path_exp:',path_exp)68 print('config1:',exp_config_file_1)69 print('config2:',exp_config_file_2)70 print('iterable parameters for config1:',params1)71 print('iterable parameters for congig2:',params2)72 print('Startint at iteration n°',i0)73 print('Stopping algorithm when K <',Kmin)74 75 76 # Convergence file77 path_K = os.path.join(path_exp,'K.txt')78 print('Convergence trajectory is written in:',path_K)79 80 # Create experimental directory81 if not os.path.exists(path_exp):82 print('creating',path_exp)83 os.makedirs(path_exp)84 85 # Create new config files86 path_exp_config_file_1 = os.path.join(path_exp,'config1.py')87 path_exp_config_file_2 = os.path.join(path_exp,'config2.py')88 89 create_new_config_file(exp_config_file_1,90 path_exp_config_file_1,91 ['tmp_DA_path ','path_save ','path_obs '],92 ['tmp_DA_path = "' + os.path.join(path_exp,'scratch/Exp1/iteration_0"'),93 'path_save = "' + os.path.join(path_exp,'outputs/Exp1/iteration_0"'),94 'path_obs = "' + os.path.join(path_exp,'obs/Exp1"')]95 )96 97 create_new_config_file(exp_config_file_2,98 path_exp_config_file_2,99 ['tmp_DA_path ','path_save ','path_obs '],100 ['tmp_DA_path = "' + os.path.join(path_exp,'scratch/Exp2/iteration_0"'),101 'path_save = "' + os.path.join(path_exp,'outputs/Exp2/iteration_0"'),102 'path_obs = "' + os.path.join(path_exp,'obs/Exp2"')]103 )104 105 K = np.inf106 i = i0107 108 while K>Kmin and i<=imax:109 110 time0 = datetime.now()111 print('\n*** Iteration n°'+str(i) + ' ***')112 113 # Run iteration114 print('1. Run Mapping experiments')115 run_iteration = os.path.join(pwd,'run_iteration.py')116 cmd = ['python3', run_iteration, 117 '--c1',path_exp_config_file_1,118 '--c2',path_exp_config_file_2,119 '--i',str(i),120 '--K',path_K]121 if params1 is not None:122 cmd.append('--params1')123 cmd.append(params1)124 if params2 is not None:125 cmd.append('--params2')126 cmd.append(params2)127 128 129 print(' '.join(cmd))130 131 out = open(os.path.join(path_exp,'logout_' + str(i) + '.txt'), "w")132 err = open(os.path.join(path_exp,'logerr_' + str(i) + '.txt'), "w")133 subprocess.call(cmd,stdout=out,stderr=err)134 135 # Convergence criteria 136 if i>0:137 print('2. Convergence criteria:')138 with open(path_K,'r') as f:139 last_line = f.readlines()[i-1]140 K1,K2,K = last_line.split(' ')141 print('\tK1',K1)142 print('\tK2',K2)143 print('\tK',K)144 K = float(K)145 i += 1146 time1 = datetime.now()147 print('computation time:',time1-time0)148 149 ...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!