How to use after method in qawolf

Best JavaScript code snippet using qawolf

regression_linear_model.py

Source:regression_linear_model.py Github

copy

Full Screen

1#!/usr/bin/env python2# Regression Stuff3from sklearn.datasets import fetch_olivetti_faces4from sklearn.utils.validation import check_random_state5from sklearn.ensemble import ExtraTreesRegressor6from sklearn.neighbors import KNeighborsRegressor7from sklearn.linear_model import LinearRegression8from sklearn.linear_model import RidgeCV9from sklearn.linear_model import BayesianRidge10from sklearn.linear_model import Lasso11from sklearn.linear_model import TheilSenRegressor12# Python Stuff13import glob14import copy15import itertools16import numpy as np17import matplotlib.pyplot as plt18import math19# ROS Stuff20import actionlib21from actionlib import SimpleActionClient22from geometry_msgs.msg import Pose, PoseStamped, Quaternion, TransformStamped, \23 Point, PointStamped, Vector3, Transform24from interactive_markers.interactive_marker_server import InteractiveMarkerServer25from manipulation_msgs.srv import GraspPlanning, GraspPlanningRequest26from manipulation_msgs.msg import GraspPlanningAction, GraspPlanningGoal27import moveit_commander28from moveit_msgs.msg import AttachedCollisionObject, CollisionObject, PlanningScene, PlanningSceneComponents29from moveit_msgs.srv import GetPlanningScene, GetPositionFK, GetPositionIK30from pr2_controllers_msgs.msg import JointTrajectoryAction, JointTrajectoryGoal31import rosbag32import rospy33from sensor_msgs.msg import PointCloud234import sensor_msgs.point_cloud2 as pc235from shape_msgs.msg import SolidPrimitive36from std_msgs.msg import Header37import tf38from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint39from visualization_msgs.msg import Marker40# Local Stuff41from joint_states_listener.srv import ReturnJointStates42from pr2_pick_contest.msg import Trial, Record43from pr2_pick_contest.srv import GetItems, SetItems, GetTargetItems44from pr2_pick_contest.srv import LookupItem45from pr2_pick_main import publish_gripper, publish_bounding_box, publish_cluster46from pr2_pick_perception.msg import Object, BoundingBox47from pr2_pick_perception.srv import CropShelf, CropShelfResponse, \48 DeleteStaticTransform, FindCentroid, LocalizeShelf, LocalizeShelfResponse, \49 SetStaticTransform, PlanarPrincipalComponents, GetItemDescriptor, ClassifyTargetItem50from pr2_gripper_grasp_planner_cluster.srv import SetPointClusterGraspParams, SetPointClusterGraspParamsRequest51from object_recognition_clusters.srv import FindClusterBoundingBox, FindClusterBoundingBoxRequest52class TrialAnalyser:53 def __init__(self):54 self._x_before = {}55 self._y_before = {}56 self._yaw_before = {}57 self._x_after = {}58 self._y_after = {}59 self._yaw_after = {}60 self.markers = rospy.Publisher('pr2_pick_visualization', Marker)61 def get_bounding_box_diff(self, trial):62 action = trial.params.action.data63 #rospy.loginfo("Action: " + str(action))64 if not self._x_before.has_key(action):65 self._x_before[action] = []66 self._y_before[action] = []67 self._yaw_before[action] = []68 self._x_after[action] = []69 self._y_after[action] = []70 self._yaw_after[action] = []71 before_box = trial.before.boundingbox72 after_box = trial.after.boundingbox73 self._x_after[action].append(after_box.pose.pose.position.x)74 self._x_before[action].append(before_box.pose.pose.position.x)75 self._y_after[action].append(after_box.pose.pose.position.y)76 self._y_before[action].append(before_box.pose.pose.position.y)77 q_before = (78 before_box.pose.pose.orientation.x,79 before_box.pose.pose.orientation.y,80 before_box.pose.pose.orientation.z,81 before_box.pose.pose.orientation.w)82 q_after = (83 after_box.pose.pose.orientation.x,84 after_box.pose.pose.orientation.y,85 after_box.pose.pose.orientation.z,86 after_box.pose.pose.orientation.w)87 euler_before = tf.transformations.euler_from_quaternion(q_before)88 euler_after = tf.transformations.euler_from_quaternion(q_after)89 yaw_before = euler_before[2]90 yaw_after = euler_after[2]91 yaw_diff = yaw_after - yaw_before92 # rospy.loginfo("Before: {}".format(before_box))93 # rospy.loginfo("Before yaw: {}".format(yaw_before*180/math.pi))94 # rospy.loginfo("After: {}".format(after_box))95 # rospy.loginfo("After yaw: {}".format(yaw_after*180/math.pi))96 if (math.fabs(after_box.dimensions.x - before_box.dimensions.x) > 0.02) and (math.fabs(after_box.dimensions.y - before_box.dimensions.y) > 0.02):97 rospy.loginfo("Wrong axes")98 yaw_before -= math.pi/2.099 100 if yaw_before < 0:101 if (math.fabs(yaw_after - (yaw_before + math.pi))) < (math.fabs(yaw_after - yaw_before)):102 rospy.loginfo("Flipped")103 yaw_before = (yaw_before + math.pi)104 else:105 if (math.fabs(yaw_after - (yaw_before - math.pi))) < (math.fabs(yaw_after - yaw_before)):106 rospy.loginfo("Flipped")107 yaw_before = (yaw_before - math.pi)108 rospy.loginfo("Yaw diff: {}".format(yaw_diff*180/math.pi))109 self._yaw_before[action].append(copy.copy(yaw_before))110 self._yaw_after[action].append(copy.copy(yaw_after))111 def get_test_data(self, trial):112 action = trial.params.action.data113 #rospy.loginfo("Action: " + str(action))114 x_before = {}115 y_before = {}116 _yaw_before = {}117 x_after = {}118 y_after = {}119 _yaw_after = {}120 if not x_before.has_key(action):121 x_before[action] = []122 y_before[action] = []123 _yaw_before[action] = []124 x_after[action] = []125 y_after[action] = []126 _yaw_after[action] = []127 before_box = trial.before.boundingbox128 after_box = trial.after.boundingbox129 x_after[action].append(after_box.pose.pose.position.x)130 x_before[action].append(before_box.pose.pose.position.x)131 y_after[action].append(after_box.pose.pose.position.y)132 y_before[action].append(before_box.pose.pose.position.y)133 q_before = (134 before_box.pose.pose.orientation.x,135 before_box.pose.pose.orientation.y,136 before_box.pose.pose.orientation.z,137 before_box.pose.pose.orientation.w)138 q_after = (139 after_box.pose.pose.orientation.x,140 after_box.pose.pose.orientation.y,141 after_box.pose.pose.orientation.z,142 after_box.pose.pose.orientation.w)143 euler_before = tf.transformations.euler_from_quaternion(q_before)144 euler_after = tf.transformations.euler_from_quaternion(q_after)145 yaw_before = euler_before[2]146 yaw_after = euler_after[2]147 yaw_diff = yaw_after - yaw_before148 # rospy.loginfo("Before: {}".format(before_box))149 # rospy.loginfo("Before yaw: {}".format(yaw_before*180/math.pi))150 # rospy.loginfo("After: {}".format(after_box))151 # rospy.loginfo("After yaw: {}".format(yaw_after*180/math.pi))152 if (math.fabs(after_box.dimensions.x - before_box.dimensions.x) > 0.02) and (math.fabs(after_box.dimensions.y - before_box.dimensions.y) > 0.02):153 rospy.loginfo("Wrong axes")154 yaw_before -= math.pi/2.0155 156 if yaw_before < 0:157 if (math.fabs(yaw_after - (yaw_before + math.pi))) < (math.fabs(yaw_after - yaw_before)):158 rospy.loginfo("Flipped")159 yaw_before = (yaw_before + math.pi)160 else:161 if (math.fabs(yaw_after - (yaw_before - math.pi))) < (math.fabs(yaw_after - yaw_before)):162 rospy.loginfo("Flipped")163 yaw_before = (yaw_before - math.pi)164 rospy.loginfo("Yaw diff: {}".format(yaw_diff*180/math.pi))165 _yaw_before[action].append(copy.copy(yaw_before))166 _yaw_after[action].append(copy.copy(yaw_after))167 return x_before, x_after, y_before, y_after, _yaw_before, _yaw_after168 # self._action_names.append(trial.params.action)169 # self._item_names.append(trial.params.item_name) 170 def estimate(self):171 # plot x_diffs172 file_name = raw_input("Please enter the path to a test bag file: ")173 174 # rospy.loginfo("Current file: " + file_name)175 bag = rosbag.Bag(file_name)176 trial = None177 for topic, trial_msg, t in bag.read_messages():178 _x_before, _x_after, _y_before, _y_after, _yaw_before, _yaw_after = self.get_test_data(trial_msg)179 trial = trial_msg180 bag.close()181 action = _x_before.keys()[0]182 train_x_before = self._x_before[action]183 train_y_before = self._y_before[action]184 train_yaw_before = self._yaw_before[action]185 train_x_after = self._x_after[action]186 train_y_after = self._y_after[action]187 train_yaw_after = self._yaw_after[action]188 test_x_before = _x_before[action]189 test_y_before = _y_before[action]190 test_yaw_before = _yaw_before[action]191 test_x_after = _x_after[action]192 test_y_after = _y_after[action]193 test_yaw_after = _yaw_after[action]194 rospy.loginfo("Train x before: {}".format(train_x_before))195 rospy.loginfo("Train y before: {}".format(train_y_before))196 rospy.loginfo("Train yaw before: {}".format(train_yaw_before))197 rospy.loginfo("Test x before: {}".format(test_x_before))198 rospy.loginfo("Test y before: {}".format(test_y_before))199 rospy.loginfo("Test yaw before: {}".format(test_yaw_before))200 rospy.loginfo("Test x after: {}".format(test_x_after))201 rospy.loginfo("Test y after: {}".format(test_y_after))202 rospy.loginfo("Test yaw after: {}".format(test_yaw_after))203 # # Load the faces datasets204 # data = fetch_olivetti_faces()205 # targets = data.target206 # data = data.images.reshape((len(data.images), -1))207 # train = data[targets < 30]208 # test = data[targets >= 30] # Test on independent people209 # # Test on a subset of people210 # n_faces = 5211 # rng = check_random_state(4)212 # face_ids = rng.randint(test.shape[0], size=(n_faces, ))213 # test = test[face_ids, :]214 # n_pixels = data.shape[1]215 # X_train = train[:, :np.ceil(0.5 * n_pixels)] # Upper half of the faces216 # y_train = train[:, np.floor(0.5 * n_pixels):] # Lower half of the faces217 # X_test = test[:, :np.ceil(0.5 * n_pixels)]218 # y_test = test[:, np.floor(0.5 * n_pixels):]219 # Fit estimators220 ESTIMATORS = {221 # "Extra trees": ExtraTreesRegressor(n_estimators=10, max_features=32,222 # random_state=0),223 # "K-nn": KNeighborsRegressor(),224 "Linear Regression": LinearRegression(),225 "Ridge": RidgeCV(),226 # "Bayesian Ridge": BayesianRidge(),227 # "Theil-Sen Regressor": TheilSenRegressor(),228 "Lasso": Lasso(),229 }230 y_test_predict = dict()231 for name, estimator in ESTIMATORS.items():232 estimator.fit(zip(train_x_before, train_y_before, train_yaw_before), zip(train_x_after, train_y_after, train_yaw_after))233 y_test_predict[name] = estimator.predict(zip(test_x_before, test_y_before, test_yaw_before))234 rospy.loginfo("Predictions: {}".format(y_test_predict))235 rospy.loginfo("Pose: {}".format(trial.before.boundingbox.pose))236 # First publish original bounding box237 publish_bounding_box(self.markers, trial.before.boundingbox.pose, 238 (trial.before.boundingbox.dimensions.x), 239 (trial.before.boundingbox.dimensions.y), 240 (trial.before.boundingbox.dimensions.z),241 1.0, 1.0, 0.0, 0.5, 20)242 # And true result243 publish_bounding_box(self.markers, trial.after.boundingbox.pose, 244 (trial.after.boundingbox.dimensions.x), 245 (trial.after.boundingbox.dimensions.y), 246 (trial.after.boundingbox.dimensions.z),247 0.0, 1.0, 0.0, 0.5, 21)248 # Now one for each estimator249 colour = [{"r": 1.0, "g": 0.0, "b": 0.0}, {"r": 0.0, "g": 0.0, "b": 1.0}, 250 {"r": 1.0, "g": 0.0, "b": 1.0}, {"r": 0.0, "g": 1.0, "b": 1.0}]251 for j, est in enumerate(sorted(ESTIMATORS)):252 x = y_test_predict[est][0][0]253 y = y_test_predict[est][0][1]254 yaw = y_test_predict[est][0][2]255 pose = PoseStamped()256 pose.header.frame_id = "bin_K"257 pose.pose.position.x = x258 pose.pose.position.y = y259 pose.pose.position.z = trial.before.boundingbox.pose.pose.position.z260 quaternion = tf.transformations.quaternion_from_euler(0, 0, yaw)261 #type(pose) = geometry_msgs.msg.Pose262 pose.pose.orientation.x = quaternion[0]263 pose.pose.orientation.y = quaternion[1]264 pose.pose.orientation.z = quaternion[2]265 pose.pose.orientation.w = quaternion[3]266 publish_bounding_box(self.markers, pose, 267 (trial.after.boundingbox.dimensions.x), 268 (trial.after.boundingbox.dimensions.y), 269 (trial.after.boundingbox.dimensions.z),270 colour[j]["r"], colour[j]["g"], colour[j]["b"], 0.5, j + 30)271if __name__ == '__main__':272 rospy.init_node('trial_analyser')273 ta = TrialAnalyser()274 path = raw_input("Please enter the path to folder with the bag files: ")275 file_list = glob.glob( path + '/*.bag')276 for file_name in file_list:277 if not file_name[-13:] == 'evaluated.bag':278 continue279 # rospy.loginfo("Current file: " + file_name)280 bag = rosbag.Bag(file_name)281 for topic, trial_msg, t in bag.read_messages():282 ta.get_bounding_box_diff(trial_msg)283 bag.close()...

Full Screen

Full Screen

Retry.py

Source:Retry.py Github

copy

Full Screen

1#!/usr/bin/evn python2# -*- coding:utf-8 -*-3# FileName Retry.py4# Author: HeyNiu5# Created Time: 201608096"""7重试机制 >> 默认3次81.待全部接口遍历后,读取写入本地的数据,取出已遍历的接口名92.读取遍历前的全部接口名,与上一步的数据求diff103.diff接口再从遍历前的接口中取出相关数据,加入重试队列114.重试上述步骤,直至diff不存在或重试次数耗尽12"""13import os14import base.Request15import sessions.ReadSessions16import utils.FileUtil17import utils.Consts18def retry11(app_type, retry=3):19 """20 重试机制,默认3次21 :param app_type: 1 >> 咚咚; 2 >> 家在; 3 >> 装修22 :param retry: 重试次数23 :return:24 """25 r1 = Retry(retry)26 if len(r1.get_diff()) > 0:27 print('发现diff接口,重试机制启动...')28 r1.retry1(app_type)29class Retry(object):30 def __init__(self, retry):31 """32 初始化33 :param retry:34 """35 self.retry = retry36 self.after_normal_sessions_path = '%s%s%s' % (37 utils.Consts.SESSIONS_PATH, "\\Sessions\\", utils.Consts.HOST)38 def __get_normal_after_sessions(self):39 """40 获取遍历后正常(接口通过)的接口列表41 :return:42 """43 return utils.FileUtil.get_file_list(self.after_normal_sessions_path)44 def __get_not_normal_after_sessions(self):45 """46 获取需要人工验证的接口VerifyRequest47 :return:48 """49 return self.__get_check_after_sessions('VerifyRequest')50 def __get_crash_after_sessions(self):51 """52 获取程序异常接口ProgramCrash53 :return:54 """55 return self.__get_check_after_sessions('ProgramCrash')56 def __get_unexpected_after_sessions(self):57 """58 获取非预期接口Unexpected59 :return:60 """61 return self.__get_check_after_sessions('Unexpected')62 def __get_field_change_after_sessions(self):63 """64 获取字段改变接口FieldChange65 :return:66 """67 return self.__get_check_after_sessions('FieldChange')68 def __get_check_after_sessions(self, sessions_type):69 """70 获取需要检查的接口列表,已去重71 :param sessions_type:72 :return:73 """74 path = '%s\\Check\\%s.txt' % (self.after_normal_sessions_path, sessions_type)75 if os.path.exists(path):76 l = open(path, encoding='utf-8').readlines()77 sessions1 = ('%s.txt' % (i.replace('\n', '')[::-1].split('/', 1)[0][::-1]) for i in l if78 i.startswith('Request url: '))79 return list(set(sessions1))80 return ()81 def get_diff(self):82 """83 获取diff接口84 diff 接口包含类型85 1.response 响应码 非200的接口86 2.请求超时的接口87 3.其他未知情况的接口(如 代码异常导致)88 :return:89 """90 before_sessions = utils.Consts.BEFORE_SESSIONS91 after_sessions = []92 normal_after_sessions = self.__get_normal_after_sessions()93 not_normal_after_sessions = self.__get_not_normal_after_sessions()94 unexpected_after_sessions = self.__get_unexpected_after_sessions()95 field_change_after_sessions = self.__get_field_change_after_sessions()96 crash_after_sessions = self.__get_crash_after_sessions()97 if normal_after_sessions is not None:98 after_sessions.extend(normal_after_sessions)99 if not_normal_after_sessions is not None:100 after_sessions.extend(not_normal_after_sessions)101 if crash_after_sessions is not None:102 after_sessions.extend(crash_after_sessions)103 if unexpected_after_sessions is not None:104 after_sessions.extend(unexpected_after_sessions)105 if field_change_after_sessions is not None:106 after_sessions.extend(field_change_after_sessions)107 return list(set(before_sessions).difference(set(after_sessions)))108 def __get_diff_sessions(self):109 """110 从本地磁盘读取diff接口sessions(request url; request header; ...)111 pass: 一个接口多条session112 :return:113 """114 diff = self.get_diff()115 for d in diff:116 print('diff sessions: %s' % (d, ))117 total_session = sessions.ReadSessions.ReadSessions().get_single_session(d)118 if len(total_session) == 0:119 print('发现录制异常接口:' + d)120 print('执行移除操作,移除重试队列')121 # 移除录制异常的接口122 os.remove('%s\\Api\\%s\\%s' % (utils.Consts.SESSIONS_PATH, utils.Consts.HOST, d))123 # 全局变量遍历前的全部接口也需要移除124 utils.Consts.BEFORE_SESSIONS.remove(d)125 else:126 yield sessions.ReadSessions.ReadSessions().get_single_session(d)127 def __will_request_sessions(self):128 """129 将要重跑的sessions,把多个接口的多个session合并为一个列表130 :return:131 """132 s = self.__get_diff_sessions()133 return (j for i in s for j in i)134 def __request_sessions(self, app_type):135 """136 请求接口137 :return:138 """139 s = self.__will_request_sessions()140 base.Request.thread_pool(app_type, s)141 def retry1(self, app_type):142 """143 重试的接口类型144 1.response 响应码 非200的接口145 2.请求超时的接口146 3.其他未知情况的接口(如 代码异常导致)147 注意:已经知道失败的接口不会再重试,目前是这样考虑的148 :return:149 """150 temp = self.retry151 while self.retry > 0:152 self.retry -= 1153 # 请求接口154 print('第%d次尝试请求diff...' % (temp - self.retry,))155 self.__request_sessions(app_type)156 # 再次求差异化文件,还有diff继续,否则停止157 if len(self.get_diff()) > 0 and self.retry > 0:158 print('发现diff存在,继续尝试请求...')159 continue160 else:161 break162 print('diff机制退出...')163 # 重试机制完成,再对比一次数据,用于生成报告164 self.get_diff()165if __name__ == "__main__":...

Full Screen

Full Screen

plugin.py

Source:plugin.py Github

copy

Full Screen

1from Screens.Screen import Screen2from Screens.MessageBox import MessageBox3from Plugins.Plugin import PluginDescriptor4from Components.ConfigList import ConfigListScreen5from Components.ActionMap import ActionMap6from Components.config import config7from Components.NimManager import nimmanager as nimmgr8class SecParameterSetup(Screen, ConfigListScreen):9 skin = """10 <screen position="center,center" size="620,455" title="Satellite equipment setup" >11 <widget name="config" position="10,10" size="600,450" />12 </screen>"""13 def __init__(self, session):14 self.skin = SecParameterSetup.skin15 self["actions"] = ActionMap(["SetupActions", "MenuActions"],16 {17 "ok": self.keySave,18 "cancel": self.keyCancel,19 "menu": self.setDefault,20 }, -2)21 Screen.__init__(self, session)22 self.setTitle(_("Satellite equipment setup"))23 list = [24 (_("Delay after diseqc reset command"), config.sec.delay_after_diseqc_reset_cmd),25 (_("Delay after diseqc peripherial poweron command"), config.sec.delay_after_diseqc_peripherial_poweron_cmd),26 (_("Delay after continuous tone disable before diseqc"), config.sec.delay_after_continuous_tone_disable_before_diseqc),27 (_("Delay after final continuous tone change"), config.sec.delay_after_final_continuous_tone_change),28 (_("Delay after last voltage change"), config.sec.delay_after_final_voltage_change),29 (_("Delay between diseqc commands"), config.sec.delay_between_diseqc_repeats),30 (_("Delay after last diseqc command"), config.sec.delay_after_last_diseqc_command),31 (_("Delay after toneburst"), config.sec.delay_after_toneburst),32 (_("Delay after change voltage before switch command"), config.sec.delay_after_change_voltage_before_switch_command),33 (_("Delay after enable voltage before switch command"), config.sec.delay_after_enable_voltage_before_switch_command),34 (_("Delay between switch and motor command"), config.sec.delay_between_switch_and_motor_command),35 (_("Delay after set voltage before measure motor power"), config.sec.delay_after_voltage_change_before_measure_idle_inputpower),36 (_("Delay after enable voltage before motor command"), config.sec.delay_after_enable_voltage_before_motor_command),37 (_("Delay after motor stop command"), config.sec.delay_after_motor_stop_command),38 (_("Delay after voltage change before motor command"), config.sec.delay_after_voltage_change_before_motor_command),39 (_("Delay before sequence repeat"), config.sec.delay_before_sequence_repeat),40 (_("Motor running timeout"), config.sec.motor_running_timeout),41 (_("Motor command retries"), config.sec.motor_command_retries),42 (_("Unicable delay after enable voltage before switch command"), config.sec.unicable_delay_after_enable_voltage_before_switch_command),43 (_("Unicable delay after change voltage before switch command"), config.sec.unicable_delay_after_change_voltage_before_switch_command),44 (_("Unicable delay after last diseqc command"), config.sec.unicable_delay_after_last_diseqc_command) ]45 ConfigListScreen.__init__(self, list)46 def setDefault(self):47 self.session.openWithCallback(self.setDefaultCallback, MessageBox, _("Set default settings?"), MessageBox.TYPE_YESNO)48 def setDefaultCallback(self, answer):49 if answer:50 config.sec.delay_after_diseqc_reset_cmd.value = 5051 config.sec.delay_after_diseqc_peripherial_poweron_cmd.value = 15052 config.sec.delay_after_continuous_tone_disable_before_diseqc.value = 2553 config.sec.delay_after_final_continuous_tone_change.value = 1054 config.sec.delay_after_final_voltage_change.value = 1055 config.sec.delay_between_diseqc_repeats.value = 12056 config.sec.delay_after_last_diseqc_command.value = 5057 config.sec.delay_after_toneburst.value = 5058 config.sec.delay_after_change_voltage_before_switch_command.value = 2059 config.sec.delay_after_enable_voltage_before_switch_command.value = 20060 config.sec.delay_between_switch_and_motor_command.value = 70061 config.sec.delay_after_voltage_change_before_measure_idle_inputpower.value = 50062 config.sec.delay_after_enable_voltage_before_motor_command.value = 90063 config.sec.delay_after_motor_stop_command.value = 50064 config.sec.delay_after_voltage_change_before_motor_command.value = 50065 config.sec.delay_before_sequence_repeat.value = 7066 config.sec.motor_running_timeout.value = 36067 config.sec.motor_command_retries.value = 168 config.sec.delay_after_diseqc_reset_cmd.save()69 config.sec.delay_after_diseqc_peripherial_poweron_cmd.save()70 config.sec.delay_after_continuous_tone_disable_before_diseqc.save()71 config.sec.delay_after_final_continuous_tone_change.save()72 config.sec.delay_after_final_voltage_change.save()73 config.sec.delay_between_diseqc_repeats.save()74 config.sec.delay_after_last_diseqc_command.save()75 config.sec.delay_after_toneburst.save()76 config.sec.delay_after_change_voltage_before_switch_command.save()77 config.sec.delay_after_enable_voltage_before_switch_command.save()78 config.sec.delay_between_switch_and_motor_command.save()79 config.sec.delay_after_voltage_change_before_measure_idle_inputpower.save()80 config.sec.delay_after_enable_voltage_before_motor_command.save()81 config.sec.delay_after_motor_stop_command.save()82 config.sec.delay_after_voltage_change_before_motor_command.save()83 config.sec.delay_before_sequence_repeat.save()84 config.sec.motor_running_timeout.save()85 config.sec.motor_command_retries.save()86 self.close(True)87session = None88def confirmed(answer):89 global session90 if answer:91 session.open(SecParameterSetup)92def SecSetupMain(Session, **kwargs):93 global session94 session = Session95 session.openWithCallback(confirmed, MessageBox, _("Please do not change any values unless you know what you are doing!"), MessageBox.TYPE_INFO)96def SecSetupStart(menuid):97 show = False98 # other menu than "scan"?99 if menuid != "scan":100 return [ ]101 # only show if DVB-S frontends are available102 for slot in nimmgr.nim_slots:103 if slot.isCompatible("DVB-S"):104 return [(_("Satellite equipment setup"), SecSetupMain, "satellite_equipment_setup", None)]105 return [ ]106def Plugins(**kwargs):107 if (nimmgr.hasNimType("DVB-S")):108 return PluginDescriptor(name=_("Satellite equipment setup"), description=_("Setup your satellite equipment"), where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc=SecSetupStart)109 else:...

Full Screen

Full Screen

moodRatingTime.py

Source:moodRatingTime.py Github

copy

Full Screen

1import pandas2import matplotlib.pyplot as plt3import numpy as np4import math5import cv26from PIL import Image7import datetime8df = pandas.read_csv('../data/moodLogFinal.csv')9df2after = pandas.read_csv('../data/moodLogFinalAfter.csv')10# 22. april 16.46 shift from no light control to light control11getEnergy = True12def reverse(n): 13 return 160 - n14timestamps = df["Timestamp"]15if(getEnergy):16 energyLevel = df["y"]17 energyLevel = map(reverse, energyLevel)18else:19 energyLevel = df["x"]20minutes = []21timestampsAfter = df2after["Timestamp"]22if(getEnergy):23 energyLevelAfter = df2after["y"]24 energyLevelAfter = map(reverse, energyLevelAfter)25else:26 energyLevelAfter = df2after["x"]27minutesAfter = []28for i in range(len(df)):29 date = datetime.datetime.fromtimestamp(df['Timestamp'][i] / 1e3)30 thisMinute = int(date.strftime("%M"))31 thisHour = int(date.strftime("%H"))32 minute = thisHour * 60 + thisMinute33 minutes.append(minute)34for i in range(len(df2after)):35 date = datetime.datetime.fromtimestamp(df['Timestamp'][i] / 1e3)36 thisMinute = int(date.strftime("%M"))37 thisHour = int(date.strftime("%H"))38 minute = thisHour * 60 + thisMinute39 minutesAfter.append(minute)40# AVG morning before41avgMorningBefore = 042avgMorningBeforeEnergy = 043counter = 044counter2 = 045while(counter < len(minutes)):46 if(minutes[counter] < 800):47 avgMorningBefore = avgMorningBefore + minutes[counter]48 avgMorningBeforeEnergy = avgMorningBeforeEnergy + energyLevel[counter]49 counter2 = counter2 + 150 counter = counter + 151avgMorningBefore = avgMorningBefore / counter252avgMorningBeforeEnergy = avgMorningBeforeEnergy / counter253# AVG evening before54avgEveningBefore = 055avgEveningBeforeEnergy = 056counter = 057counter2 = 058while(counter < len(minutes)):59 if(minutes[counter] > 800):60 avgEveningBefore = avgEveningBefore + minutes[counter]61 avgEveningBeforeEnergy = avgEveningBeforeEnergy + energyLevel[counter]62 counter2 = counter2 + 163 counter = counter + 164 print(counter2)65avgEveningBefore = avgEveningBefore / counter266avgEveningBeforeEnergy = avgEveningBeforeEnergy / counter267print(avgMorningBefore, avgMorningBeforeEnergy)68 69# AVG morning after70avgMorningAfter = 071avgMorningAfterEnergy = 072counter = 073counter2 = 074while(counter < len(minutesAfter)):75 if(minutes[counter] < 800):76 avgMorningAfter = avgMorningAfter + minutesAfter[counter]77 avgMorningAfterEnergy = avgMorningAfterEnergy + energyLevelAfter[counter]78 counter2 = counter2 + 179 counter = counter + 180avgMorningAfter = avgMorningAfter / counter281avgMorningAfterEnergy = avgMorningAfterEnergy / counter282# AVG evening after83avgEveningAfter = 084avgEveningAfterEnergy = 085counter = 086counter2 = 087while(counter < len(minutesAfter)):88 if(minutes[counter] > 800):89 avgEveningAfter = avgEveningAfter + minutesAfter[counter]90 avgEveningAfterEnergy = avgEveningAfterEnergy + energyLevelAfter[counter]91 counter2 = counter2 + 192 counter = counter + 193avgEveningAfter = avgEveningAfter / counter294avgEveningAfterEnergy = avgEveningAfterEnergy / counter295# From 0 to 16096area = np.pi*597# Plot98plt.grid(color='#eeeeee', linestyle='-', linewidth=1)99plt.scatter(minutes, energyLevel, s=area, color="#ff4040", label="Before")100plt.scatter(minutesAfter, energyLevelAfter, s=area, color="#4040ff", label="After")101#plt.scatter(avgMorningBefore, avgMorningBeforeEnergy, s=area, color="#00ff00", label="Before avg")102#plt.scatter(avgEveningBefore, avgEveningBeforeEnergy, s=area, color="#00ff00", label="Before avg")103#plt.scatter(avgMorningAfter, avgMorningAfterEnergy, s=area, color="#ffff00", label="After avg")104#plt.scatter(avgEveningAfter, avgEveningAfterEnergy, s=area, color="#ffff00", label="After avg")105plt.plot([avgMorningBefore, avgEveningBefore], [avgMorningBeforeEnergy, avgEveningBeforeEnergy], color="#ff4040", label="Before (avg)")106plt.plot([avgMorningAfter, avgEveningAfter], [avgMorningAfterEnergy, avgEveningAfterEnergy], color="#4040ff", label="After (avg)")107plt.title('Time of mood rating and energy level')108plt.xlabel('Time of day in minutes')109if(getEnergy):110 plt.ylabel('Energy level')111else:112 plt.ylabel('Happiness')113plt.ylim(0, 160)114plt.legend()...

Full Screen

Full Screen

moodBoxPlot.py

Source:moodBoxPlot.py Github

copy

Full Screen

1import pandas2import matplotlib.pyplot as plt3import numpy as np4import math5import cv26from PIL import Image7import datetime8df = pandas.read_csv('../data/moodLogFinal.csv')9df2after = pandas.read_csv('../data/moodLogFinalAfter.csv')10# 22. april 16.46 shift from no light control to light control11getEnergy = True12def reverse(n): 13 return 160 - n14timestamps = df["Timestamp"]15energyLevel = df["y"]16energyLevel = map(reverse, energyLevel)17happinessLevel = df["x"]18minutes = []19timestampsAfter = df2after["Timestamp"]20energyLevelAfter = df2after["y"]21energyLevelAfter = map(reverse, energyLevelAfter)22happinessLevelAfter = df2after["x"]23minutesAfter = []24for i in range(len(df)):25 date = datetime.datetime.fromtimestamp(df['Timestamp'][i] / 1e3)26 thisMinute = int(date.strftime("%M"))27 thisHour = int(date.strftime("%H"))28 minute = thisHour * 60 + thisMinute29 minutes.append(minute)30for i in range(len(df2after)):31 date = datetime.datetime.fromtimestamp(df['Timestamp'][i] / 1e3)32 thisMinute = int(date.strftime("%M"))33 thisHour = int(date.strftime("%H"))34 minute = thisHour * 60 + thisMinute35 minutesAfter.append(minute)36# AVG morning before37avgMorningBefore = 038avgMorningBeforeEnergy = 039counter = 040counter2 = 041while(counter < len(minutes)):42 if(minutes[counter] < 800):43 avgMorningBefore = avgMorningBefore + minutes[counter]44 avgMorningBeforeEnergy = avgMorningBeforeEnergy + energyLevel[counter]45 counter2 = counter2 + 146 counter = counter + 147avgMorningBefore = avgMorningBefore / counter248avgMorningBeforeEnergy = avgMorningBeforeEnergy / counter249# AVG evening before50avgEveningBefore = 051avgEveningBeforeEnergy = 052counter = 053counter2 = 054while(counter < len(minutes)):55 if(minutes[counter] > 800):56 avgEveningBefore = avgEveningBefore + minutes[counter]57 avgEveningBeforeEnergy = avgEveningBeforeEnergy + energyLevel[counter]58 counter2 = counter2 + 159 counter = counter + 160 print(counter2)61avgEveningBefore = avgEveningBefore / counter262avgEveningBeforeEnergy = avgEveningBeforeEnergy / counter263print(avgMorningBefore, avgMorningBeforeEnergy)64 65# AVG morning after66avgMorningAfter = 067avgMorningAfterEnergy = 068counter = 069counter2 = 070while(counter < len(minutesAfter)):71 if(minutes[counter] < 800):72 avgMorningAfter = avgMorningAfter + minutesAfter[counter]73 avgMorningAfterEnergy = avgMorningAfterEnergy + energyLevelAfter[counter]74 counter2 = counter2 + 175 counter = counter + 176avgMorningAfter = avgMorningAfter / counter277avgMorningAfterEnergy = avgMorningAfterEnergy / counter278# AVG evening after79avgEveningAfter = 080avgEveningAfterEnergy = 081counter = 082counter2 = 083while(counter < len(minutesAfter)):84 if(minutes[counter] > 800):85 avgEveningAfter = avgEveningAfter + minutesAfter[counter]86 avgEveningAfterEnergy = avgEveningAfterEnergy + energyLevelAfter[counter]87 counter2 = counter2 + 188 counter = counter + 189avgEveningAfter = avgEveningAfter / counter290avgEveningAfterEnergy = avgEveningAfterEnergy / counter291box_plot_data=[energyLevel, energyLevelAfter, happinessLevel, happinessLevelAfter]92plt.boxplot(box_plot_data, labels=['Energy before', 'Energy after', 'Happiness before', 'Happiness after'])...

Full Screen

Full Screen

blacklist_filter.py

Source:blacklist_filter.py Github

copy

Full Screen

1# coding=utf-82"""3@author: xing4@contact: 1059252359@qq.com5@file: blacklist_filter.py6@date: 2021/3/3 10:067@desc: 8"""9import re10from pre_processing.prepro_utils import *11from pre_processing.email_sender import *12def removeDross(dir_path, source_db_path, before_uglifyjs_db_path, after_uglifyjs_db_path):13 # 读取数据14 total_data = read_data_from_db_files(source_db_path)15 # 1. 再去掉一部分超长的数据16 after_too_long_data = [i for i in total_data if not len(i) > 100000]17 logging.info(f'·After removing the data with rows greater than 10W, remaining: {len(after_too_long_data)}')18 # 2. 过滤掉所有nock类数据,该类数据没有什么意义19 after_nock_data = [i for i in after_too_long_data if not i.startswith('function(nock')]20 logging.info(f'·After removing the Nock data, remaining: {len(after_nock_data)}')21 # 3. 过滤掉形如 function(...) {}的数据22 after_immediate_data = []23 discarded_functions = []24 pattern_1 = re.compile('^function(.*?){}$')25 for function in after_nock_data:26 if re.match(pattern_1, function) is not None:27 discarded_functions.append(function)28 else:29 after_immediate_data.append(function)30 logging.info(f'After removing the function(...), remaining: {len(after_immediate_data)}')31 # 4. 过滤掉其中所有非英文数据32 after_english_data = filter_english_data(after_immediate_data)33 logging.info(f'·After removing all non-English data, remaining: {len(after_english_data)}')34 # 5. 按黑名单内容过滤35 after_blacklist_filter_data = filter_blacklist_data(after_english_data)36 logging.info(f'·After removing the data in the blacklist, remaining: {len(after_blacklist_filter_data)}')37 # 5.5 暂存一下38 if not os.path.exists(dir_path):39 os.mkdir(dir_path)40 list2db(after_too_long_data, os.path.join(dir_path, before_uglifyjs_db_path)) # total_data_guolvhou.db,共288665条。uglifyjs美化后剩余288564条41 # 6. 利用uglifyjs去除注释以及美化(格式化),存入数据库备份42 # 此处应当注意 uglifyjs安装的路径,必要时需要进入uglifyjs_filter中修改43 after_uglifyjs_data = uglifyjs_filter(after_blacklist_filter_data, 32)44 after_uglifyjs_data = deduplicate(after_uglifyjs_data) # 采用不稳定去重45 list2db(after_uglifyjs_data, os.path.join(dir_path, after_uglifyjs_db_path))46 logging.info(f'·After deannotating, beautifying, and deduplicating, remaining: {len(after_uglifyjs_data)}')47 # # 执行完成后邮件告知48 # EmailSender = email_sender('1059252359@qq.com')...

Full Screen

Full Screen

main_spanish.py

Source:main_spanish.py Github

copy

Full Screen

1# Dependencies2import os3from sentiment_analysis_spanish import sentiment_analysis4# Select political leader5leader = "lula"6# Get rise and fall text files as single strings7file_path = os.path.join(os.getcwd(), "data", leader, "spanish", "rise.txt")8with open(file_path, 'r', encoding = "utf-8") as file:9 str_before = file.read()10file_path = os.path.join(os.getcwd(), "data", leader, "spanish", "fall.txt")11with open(file_path, 'r', encoding = "utf-8") as file:12 str_after = file.read()13# Sentiment analysis, see https://pypi.org/project/sentiment-analysis-spanish/14# Initialize sentiment analysis class15sentiment = sentiment_analysis.SentimentAnalysisSpanish()16print("--- PARAGRAPH BY PARAGRAPH ANALYSIS ---")17# Make rise article into paragraph-based list and do sentiment analysis18para_before = str_before.split("\n")19before_sentiment = list()20for i in range(len(para_before)):21 before_sentiment.append(sentiment.sentiment(para_before[i]))22print("Average sentiment for rise article is {:.4f}".format(23 sum(before_sentiment)/len(before_sentiment), 2))24# Make fall article into paragraph-based list and do sentiment analysis25para_after = str_after.split("\n")26after_sentiment = list()27for i in range(len(para_after)):28 after_sentiment.append(sentiment.sentiment(para_after[i]))29print("Average sentiment for fall article is {:.4f}".format(30 sum(after_sentiment)/len(after_sentiment), 2))31# Get ratio based result to see fall/rise sentiment32print("Ratio of fall/rise sentiment is thus {:.4f}".format(33 (sum(after_sentiment)/len(after_sentiment))/(sum(before_sentiment)/len(before_sentiment))))34print("--- SENTENCE BY SENTENCE ANALYSIS ---")35# Now do this per sentence36sen_before = str_before.replace("\n", "").split(".")37before_sentiment = list()38for i in range(len(sen_before)):39 before_sentiment.append(sentiment.sentiment(sen_before[i]))40print("Average sentiment for rise article is {:.4f}".format(41 sum(before_sentiment)/len(before_sentiment), 2))42sen_after = str_after.replace("\n", "").split(".")43after_sentiment = list()44for i in range(len(sen_after)):45 after_sentiment.append(sentiment.sentiment(sen_after[i]))46print("Average sentiment for fall article is {:.4f}".format(47 sum(after_sentiment)/len(after_sentiment), 2))48# Get ratio based result to see fall/rise sentiment49print("Ratio of fall/rise sentiment is thus {:.4f}".format(...

Full Screen

Full Screen

79.py

Source:79.py Github

copy

Full Screen

1with open("p079_keylog.txt") as f:2 content = [line.rstrip('\n') for line in f]34after = {}5#print(after)6for c in content:7 if int(c[0]) not in after.keys():8 after[int(c[0])] = []9 if int(c[1]) not in after.keys():10 after[int(c[1])] = []11 if int(c[2]) not in after.keys():12 after[int(c[2])] = []13 if int(c[1]) not in after[int(c[0])]:14 after[int(c[0])].append(int(c[1]))15 if int(c[2]) not in after[int(c[0])]:16 after[int(c[0])].append(int(c[2]))17 if int(c[2]) not in after[int(c[1])]:18 after[int(c[1])].append(int(c[2]))19k = list(after.keys())20k.sort(key=lambda x: len(after[x]), reverse=True) ...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { launch } = require('qawolf');2const selectors = require('./selectors/test');3describe('test', () => {4 let browser;5 let page;6 beforeAll(async () => {7 browser = await launch();8 });9 afterAll(async () => {10 await browser.close();11 });12 beforeEach(async () => {13 page = await browser.newPage();14 });15 afterEach(async () => {16 await page.close();17 });18 it('test', async () => {19 await page.click(selectors['test']);20 await page.type(selectors['test'], 'test');21 await page.click(selectors['test']);22 await page.type(selectors['test'], 'test');23 await page.click(selectors['test']);24 await page.type(selectors['test'], 'test');25 await page.click(selectors['test']);26 await page.type(selectors['test'], 'test');27 await page.click(selectors['test']);28 await page.type(selectors['test'], 'test');29 await page.click(selectors['test']);30 await page.type(selectors['test'], 'test');31 await page.click(selectors['test']);32 await page.type(selectors['test'], 'test');33 await page.click(selectors['test']);34 await page.type(selectors['test'], 'test');35 await page.click(selectors['test']);36 await page.type(selectors['test'], 'test');37 await page.click(selectors['test']);38 await page.type(selectors['test'], 'test');39 await page.click(selectors['test']);40 await page.type(selectors['test'], 'test');41 await page.click(selectors['test']);42 await page.type(selectors['test'], 'test');43 await page.click(selectors['test']);44 await page.type(selectors['test'], 'test');45 await page.click(selectors['test']);46 await page.type(selectors['test'], 'test');47 await page.click(selectors['test']);48 await page.type(selectors['test'], 'test');49 await page.click(selectors['test']);50 await page.type(selectors['test'], 'test');51 await page.click(selectors['test']);52 await page.type(selectors['test'], 'test');53 await page.click(selectors['test']);54 await page.type(selectors['test'], 'test');55 await page.click(selectors['test']);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { after, before } = require('qawolf');2const { chromium } = require('playwright');3let browser;4let context;5beforeAll(async () => {6 browser = await chromium.launch();7 context = await browser.newContext();8});9beforeEach(async () => {10 await before(context);11});12afterEach(async () => {13 await after(context);14});15afterAll(async () => {16 await browser.close();17});18test('test', async () => {19});20const { after, before } = require('qawolf');21const { chromium } = require('playwright');22let browser;23let context;24beforeAll(async () => {25 browser = await chromium.launch();26 context = await browser.newContext();27});28beforeEach(async () => {29 await before(context);30});31afterEach(async () => {32 await after(context);33});34afterAll(async () => {35 await browser.close();36});37test('test', async () => {38});39const { after, before } = require('qawolf');40const { chromium } = require('playwright');41let browser;42let context;43beforeAll(async () => {44 browser = await chromium.launch();45 context = await browser.newContext();46});47beforeEach(async () => {48 await before(context);49});50afterEach(async () => {51 await after(context);52});53afterAll(async () => {54 await browser.close();55});56test('test', async () => {57});58const { after, before } = require('qawolf');59const { chromium } = require('playwright');60let browser;61let context;62beforeAll(async () => {63 browser = await chromium.launch();64 context = await browser.newContext();65});66beforeEach(async () => {67 await before(context);68});69afterEach(async () => {70 await after(context);71});72afterAll(async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1await page.click('button');2await page.click('button');3await page.click('button');4await page.click('button');5await page.click('button');6await page.click('button');7await page.click('button');8await page.click('button');9await page.click('button');10await page.click('button');11await page.click('button');12await page.click('button');13await page.click('button');14await page.click('button');15await page.click('button');16await page.click('button');17await page.click('button');18await page.click('button');19await page.click('button');20await page.click('button');21await page.click('button');22await page.click('button');23await page.click('button');24await page.click('button');25await page.click('button');26await page.click('button');27await page.click('button');28await page.click('button');29await page.click('button');30await page.click('button');31await page.click('button');32await page.click('button');33await page.click('button');34await page.click('button');35await page.click('button');36await page.click('button');37await page.click('button');38await page.click('button');39await page.click('button');40await page.click('button');41await page.click('button');42await page.click('button');43await page.click('button');44await page.click('button');45await page.click('button');46await page.click('button');47await page.click('button');48await page.click('button');49await page.click('button');50await page.click('button');51await page.click('button');52await page.click('button');53await page.click('button');54await page.click('button');55await page.click('button

Full Screen

Using AI Code Generation

copy

Full Screen

1const { after } = require('qawolf');2afterAll(async () => {3 await after({ launch: false });4});5const { launch } = require('qawolf');6const { test, expect } = require('@playwright/test');7const { setContext } = require('qawolf');8test.describe('test', () => {9 test.beforeAll(async ({ browser }) => {10 const context = await browser.newContext();11 await setContext(context);12 });13 test('test', async () =>

Full Screen

Using AI Code Generation

copy

Full Screen

1const { launch, browserName } = require('qawolf');2const assert = require('assert');3const selectors = require('../selectors/test.json');4let browser;5let page;6beforeAll(async () => {7 page = await browser.newPage();8});9afterAll(async () => {10 await browser.close();11});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run qawolf automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful