Best Python code snippet using lisa_python
visualise.py
Source:visualise.py
...52 age_avg, degree_avg = [[],[]]53 age_std, degree_std = [[],[]]54 for file_name in file_names:55 file = open(f"stats/fb_age_" + file_name)56 avg, std = get_average(file, index)57 age_avg += [avg]58 age_std += [std]59 file = open(f"stats/fb_degree_" + file_name)60 avg, std = get_average(file, index)61 degree_avg += [avg]62 degree_std += [std]63 # Plot graphs64 plt.subplot(121)65 plt.ylim(0,max(max(age_avg),max(degree_avg))+max(max(age_std),max(degree_std)))66 plt.errorbar(parameters, age_avg, yerr=age_std, label="age", marker="o", markersize=3, linestyle="dotted", linewidth=0.5, elinewidth=1)67 plt.subplot(122)68 plt.ylim(0,max(max(age_avg),max(degree_avg))+max(max(age_std),max(degree_std)))69 plt.errorbar(parameters, degree_avg, yerr=degree_std, label="degree", marker="o", markersize=3, linestyle="dotted", linewidth=0.5, elinewidth=1)70 plt.show()71def graph_methods(data, parameter):72 """73 This function plots the data for all vaccination methods in one graph.74 The parameters decide what is plotted:75 - data: this parameter decides which data to plot (time, infections or deaths).76 - parameter: this parameter decides which parameter of the model is on the y-axis.77 """78 # Generate index of data79 if data == "time":80 title = "Time taken for virus to die out for different values of " + parameter + "."81 ylabel = "time (days)"82 index = 183 elif data == "infections":84 title = "Total infections for different values of " + parameter + "."85 ylabel = "number of infections"86 index = 287 else:88 title = "Death toll for different values of " + parameter + "."89 ylabel = "death toll"90 index = 391 # Generate file name and list of values for correct parameter92 none_method = True93 if parameter == "infection_rate":94 parameters = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]95 file_names = []96 for p in parameters:97 file_names.append(f"{format(p, '.1f')}_5_10_25_0.05_0.05.txt")98 elif parameter == "incubation_period":99 parameters = [4, 5, 6, 7]100 file_names = []101 for p in parameters:102 file_names.append(f"1.0_{p}_10_25_0.05_0.05.txt")103 elif parameter == "infection_time":104 parameters = [6, 8, 10, 12, 14]105 file_names = []106 for p in parameters:107 file_names.append(f"1.0_5_{p}_25_0.05_0.05.txt")108 elif parameter == "vaccination_rate":109 none_method = False110 parameters = [15, 20, 25, 30, 35]111 file_names = []112 for p in parameters:113 file_names.append(f"1.0_5_10_{p}_0.05_0.05.txt")114 elif parameter == "vaccine_spread_effectiveness":115 none_method = False116 parameters = [0.03, 0.04, 0.05, 0.06, 0.07]117 file_names = []118 for p in parameters:119 file_names.append(f"1.0_5_10_25_{format(p, '.2f')}_0.05.txt")120 else:121 none_method = False122 parameters = [0.03, 0.04, 0.05, 0.06, 0.07]123 file_names = []124 for p in parameters:125 file_names.append(f"1.0_5_10_25_0.05_{format(p, '.2f')}.txt")126 # Find averages and standard deviations of data127 diff = 0.05 * (parameters[1] - parameters[0])128 if none_method:129 none_avg, none_std = [[],[]]130 for file_name in file_names:131 file = open("stats/fb_none_" + file_name)132 avg, std = get_average(file, index)133 none_avg += [avg]134 none_std += [std]135 parameters1 = [p - diff for p in parameters]136 plt.errorbar(parameters1, none_avg, yerr=none_std, label="none", marker="o", markersize=3, linestyle="dotted", linewidth=0.5, elinewidth=1)137 random_avg, age_avg, degree_avg = [[] for i in range(3)]138 random_std, age_std, degree_std = [[] for i in range(3)]139 for file_name in file_names:140 file = open(f"stats/fb_random_" + file_name)141 avg, std = get_average(file, index)142 random_avg += [avg]143 random_std += [std]144 file = open(f"stats/fb_age_" + file_name)145 avg, std = get_average(file, index)146 age_avg += [avg]147 age_std += [std]148 file = open(f"stats/fb_degree_" + file_name)149 avg, std = get_average(file, index)150 degree_avg += [avg]151 degree_std += [std]152 # Plot graphs153 diff = 0.05 * (parameters[1] - parameters[0])154 parameters2 = [p + diff for p in parameters]155 parameters3 = [p + 2 * diff for p in parameters]156 plt.errorbar(parameters, random_avg, yerr=random_std, label="random", marker="o", markersize=3, linestyle="dotted", linewidth=0.5, elinewidth=1)157 plt.errorbar(parameters2, age_avg, yerr=age_std, label="age", marker="o", markersize=3, linestyle="dotted", linewidth=0.5, elinewidth=1)158 plt.errorbar(parameters3, degree_avg, yerr=degree_std, label="degree", markersize=3, marker="o", linestyle="dotted", linewidth=0.5, elinewidth=1)159 plt.title(title)160 plt.ylabel(ylabel)161 plt.xlabel(parameter)162 plt.legend()163 plt.show()164def sensitivity(parameter):165 """166 This function prints the sensitivity for each parameter.167 """168 # Get averages of 20% deviations169 if parameter == "incubation_period":170 file = open("stats/fb_random_1.0_4_10_25_0.05_0.05.txt")171 avg_infected_1 = get_average(file, 2)[0]172 avg_death_1 = get_average(file, 3)[0]173 file = open("stats/fb_random_1.0_6_10_25_0.05_0.05.txt")174 avg_infected_2 = get_average(file, 2)[0]175 avg_death_2 = get_average(file, 3)[0]176 elif parameter == "infection_time":177 file = open("stats/fb_random_1.0_5_8_25_0.05_0.05.txt")178 avg_infected_1 = get_average(file, 2)[0]179 avg_death_1 = get_average(file, 3)[0]180 file = open("stats/fb_random_1.0_5_12_25_0.05_0.05.txt")181 avg_infected_2 = get_average(file, 2)[0]182 avg_death_2 = get_average(file, 3)[0]183 elif parameter == "vaccination_rate":184 file = open("stats/fb_random_1.0_5_10_20_0.05_0.05.txt")185 avg_infected_1 = get_average(file, 2)[0]186 avg_death_1 = get_average(file, 3)[0]187 file = open("stats/fb_random_1.0_5_10_30_0.05_0.05.txt")188 avg_infected_2 = get_average(file, 2)[0]189 avg_death_2 = get_average(file, 3)[0]190 elif parameter == "vaccine_spread_effectiveness":191 file = open("stats/fb_random_1.0_5_10_25_0.04_0.05.txt")192 avg_infected_1 = get_average(file, 2)[0]193 avg_death_1 = get_average(file, 3)[0]194 file = open("stats/fb_random_1.0_5_10_25_0.06_0.05.txt")195 avg_infected_2 = get_average(file, 2)[0]196 avg_death_2 = get_average(file, 3)[0]197 else:198 file = open("stats/fb_random_1.0_5_10_25_0.05_0.04.txt")199 avg_infected_1 = get_average(file, 2)[0]200 avg_death_1 = get_average(file, 3)[0]201 file = open("stats/fb_random_1.0_5_10_25_0.05_0.06.txt")202 avg_infected_2 = get_average(file, 2)[0]203 avg_death_2 = get_average(file, 3)[0]204 205 # Calculate differences on deviations206 diff_infected = abs(avg_infected_1 - avg_infected_2) / 2207 diff_death = abs(avg_death_1 - avg_death_2) / 2208 center_infected = (avg_infected_1 + avg_infected_2) / 2209 center_death = (avg_death_1 + avg_death_2) / 2210 211 print(parameter)212 print(" - 20% difference infected:", round(100 * diff_infected / center_infected, 1), "%")...
main.py
Source:main.py
...20 lektor.grades[course] = [grade]21 else:22 return 'ÐÑибка'23 def get_comparison (self, student):24 if get_average(self.grades) == get_average(student.grades):25 print('РавнÑ')26 if get_average(self.grades) > get_average(student.grades):27 print(28 f'СÑедние оÑенки {self.surname} {self.name} {get_average(self.grades)} лÑÑÑе Ñем {get_average(student.grades)} Ñ {student.surname} {student.name}')29 else:30 print(31 f'СÑедние оÑенки {student.surname} {student.name} {get_average(student.grades)} лÑÑÑе Ñем {get_average(self.grades)} Ñ {self.surname} {self.name}')32 return33 def __str__(self):34 lec = f"""ÐмÑ: {self.name} 35ФамилиÑ: {self.surname} 36СÑеднÑÑ Ð¾Ñенка за дз: {get_average(self.grades)}37ÐÑÑÑÑ Ð² пÑоÑеÑÑе изÑÑениÑ: {self.courses_in_progress}38ÐавеÑÑеннÑе кÑÑÑÑ: {self.finished_courses}39"""40 return lec41class Mentor:42 def __init__(self, name, surname):43 self.name = name44 self.surname = surname45 self.courses_attached = []46class Reviewer(Mentor):47 def __init__(self, name, surname):48 self.courses_attached = []49 super().__init__(name, surname)50 def rate_hw(self, student, course, grade):51 if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress:52 if course in student.grades:53 student.grades[course] += [grade]54 else:55 student.grades[course] = [grade]56 else:57 return 'ÐÑибка'58 def __str__(self):59 rev = f"""ÐмÑ: {self.name} 60ФамилиÑ: {self.surname}"""61 return rev62class Lecturer(Mentor):63 def __init__(self, name, surname):64 super().__init__(name, surname)65 self.grades = {}66 self.averege_grade = 067 def get_comparison(self, lektor):68 if get_average(self.grades) == get_average(lektor.grades):69 print('РавнÑ')70 if get_average(self.grades) > get_average(lektor.grades):71 print(f'СÑедние оÑенки {self.surname} {self.name} {get_average(self.grades)} лÑÑÑе Ñем {get_average(lektor.grades)} Ñ {lektor.surname} {lektor.name}')72 else:73 print(f'СÑедние оÑенки {lektor.surname} {lektor.name} {get_average(lektor.grades)} лÑÑÑе Ñем {get_average(self.grades)} Ñ {self.surname} {self.name}')74 return75 def __lt__(self, other):76 return self.averege_grade < other.averege_grade77 def __str__(self):78 lec = f"""ÐмÑ: {self.name} 79ФамилиÑ: {self.surname} 80СÑеднÑÑ Ð¾Ñенка за лекÑии: {get_average(self.grades)}81"""82 return lec83def get_average(grade_l):84 num = 085 null = 086 iter = 087 for i in grade_l.values():88 for p in i:89 if null < p:90 num += p91 iter +=192 else:93 continue94 res = num / iter95 return res96klubnickin = Lecturer('Grishka', 'Klubnickin')97klubnickin.courses_attached += ['Python']98arbuzov = Lecturer('Andrey', 'Arbuzov')99arbuzov.courses_attached += ['JS']100tomatov = Student('Ruslan', 'Tomatov', 'm')101tomatov.finished_courses += ['OOP']102tomatov.courses_in_progress += ['Python', 'JS']103tomatov.rate_lekt(klubnickin, 'Python', 8)104tomatov.rate_lekt(arbuzov, 'JS', 7)105ogurcova = Student('Natalia', 'Ogurcova', 'w')106ogurcova.finished_courses += ['JS']107ogurcova.courses_in_progress += ['Python', 'OOP']108ogurcova.rate_lekt(klubnickin, 'Python', 3)109ogurcova.averege_grade = 3110persikov = Reviewer('Valera', 'Persikov')111persikov.courses_attached += ['JS']112persikov.rate_hw(tomatov, 'JS', 10)113persikov.rate_hw(tomatov, 'JS', 8)114persikov.rate_hw(ogurcova, 'JS', 5)115persikov.rate_hw(ogurcova, 'JS', 10)116yablokov = Reviewer('Stanislav', 'Yablokov')117yablokov.courses_attached += ['Python']118yablokov.rate_hw(tomatov, 'Python', 6)119yablokov.rate_hw(tomatov, 'Python', 7)120yablokov.rate_hw(ogurcova, 'Python', 5)121yablokov.rate_hw(ogurcova, 'Python', 8)122Lecturer.get_comparison(klubnickin, arbuzov)123print(arbuzov)124print(klubnickin)125Student.get_comparison(ogurcova, tomatov)126print(ogurcova)127stud_l = [tomatov.grades, ogurcova.grades]128grades = []129def get_averange_course_stud(stud_l, course):130 num = 0131 null = 0132 iter = 0133 for stud in stud_l:134 if course in stud:135 grades.append(stud[course])136 for i in grades:137 for p in i:138 if null < p:139 num += p140 iter += 1141 else:142 continue143 res = num / iter144 grades.clear()145 return (f'Ðо кÑÑÑÑ {course} ÑÑеднÑÑ Ð¾Ñенка Ñ ÑÑÑденÑов {res}')146print(get_averange_course_stud(stud_l, 'JS'))147print(get_averange_course_stud(stud_l, 'Python'))148lect_l = [klubnickin.grades, arbuzov.grades]149grades_lec = []150def get_averange_course_lect(lect_l, course):151 num = 0152 null = 0153 iter = 0154 for lect in lect_l:155 if course in lect:156 grades_lec.append(lect[course])157 for i in grades_lec:158 for p in i:159 if null < p:160 num += p161 iter += 1162 else:163 continue164 res = num / iter165 grades_lec.clear()166 return (f'Ðо кÑÑÑÑ {course} ÑÑеднÑÑ Ð¾Ñенка Ñ Ð»ÐµÐºÑоÑов {res}')167print(get_averange_course_lect(lect_l, 'JS'))168print(get_averange_course_lect(lect_l, 'Python'))169tomatov.averege_grade = get_average(tomatov.grades)170ogurcova.averege_grade = get_average(ogurcova.grades)171klubnickin.averege_grade = get_average(klubnickin.grades)172arbuzov.averege_grade = get_average(arbuzov.grades)173is_lt_stud = (ogurcova < tomatov)174print(is_lt_stud)175is_lt_lect = (klubnickin > arbuzov)...
sensehat.py
Source:sensehat.py
...32 """Get CPU temperature."""33 res = os.popen("vcgencmd measure_temp").readline()34 t_cpu = float(res.replace("temp=", "").replace("'C\n", ""))35 return t_cpu36def get_average(temp_base):37 """Use moving average to get better readings."""38 if not hasattr(get_average, "temp"):39 get_average.temp = [temp_base, temp_base, temp_base]40 get_average.temp[2] = get_average.temp[1]41 get_average.temp[1] = get_average.temp[0]42 get_average.temp[0] = temp_base43 temp_avg = (get_average.temp[0] + get_average.temp[1]44 + get_average.temp[2]) / 345 return temp_avg46def setup_platform(hass, config, add_devices, discovery_info=None):47 """Set up the Sense HAT sensor platform."""48 data = SenseHatData(config.get(CONF_IS_HAT_ATTACHED))49 dev = []50 for variable in config[CONF_DISPLAY_OPTIONS]:51 dev.append(SenseHatSensor(data, variable))52 add_devices(dev, True)53class SenseHatSensor(Entity):54 """Representation of a Sense HAT sensor."""55 def __init__(self, data, sensor_types):56 """Initialize the sensor."""57 self.data = data58 self._name = SENSOR_TYPES[sensor_types][0]59 self._unit_of_measurement = SENSOR_TYPES[sensor_types][1]60 self.type = sensor_types61 self._state = None62 @property63 def name(self):64 """Return the name of the sensor."""65 return self._name66 @property67 def state(self):68 """Return the state of the sensor."""69 return self._state70 @property71 def unit_of_measurement(self):72 """Return the unit the value is expressed in."""73 return self._unit_of_measurement74 def update(self):75 """Get the latest data and updates the states."""76 self.data.update()77 if not self.data.humidity:78 _LOGGER.error("Don't receive data")79 return80 if self.type == 'temperature':81 self._state = self.data.temperature82 if self.type == 'humidity':83 self._state = self.data.humidity84 if self.type == 'pressure':85 self._state = self.data.pressure86class SenseHatData:87 """Get the latest data and update."""88 def __init__(self, is_hat_attached):89 """Initialize the data object."""90 self.temperature = None91 self.humidity = None92 self.pressure = None93 self.is_hat_attached = is_hat_attached94 @Throttle(MIN_TIME_BETWEEN_UPDATES)95 def update(self):96 """Get the latest data from Sense HAT."""97 from sense_hat import SenseHat98 sense = SenseHat()99 temp_from_h = sense.get_temperature_from_humidity()100 temp_from_p = sense.get_temperature_from_pressure()101 t_total = (temp_from_h + temp_from_p) / 2102 if self.is_hat_attached:103 t_cpu = get_cpu_temp()104 t_correct = t_total - ((t_cpu - t_total) / 1.5)105 t_correct = get_average(t_correct)106 else:107 t_correct = get_average(t_total)108 self.temperature = t_correct109 self.humidity = sense.get_humidity()...
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!!