def train(self, epochs, loss_freq, test_freq, valid_freq, valid_number, save_freq, result_path): with self.supervisor.managed_session(config=self.config) as sess: for epoch in range(epochs): loss = None while self._train_data.epochs_completed == epoch: # stop if self.supervisor.should_stop(): break # train x, labels = self._train_data.next_batch() loss, _ = sess.run(fetches=[self.loss, self.train_op], feed_dict={ self.image: x, self.label: labels }) pass if epoch % loss_freq == 0: Tools.print_info("{} loss {}".format(epoch, loss)) if epoch % valid_freq == 0: self._valid(sess, valid_number, epoch, result_path) if epoch % test_freq == 0: self._test(sess, info="test") if epoch % save_freq == 0: self.supervisor.saver.save( sess, os.path.join(self._model_path, "model_{}".format(epoch))) pass pass pass
def _readByte(self, reg): try: result = self.bus.read_byte_data(self.address, reg) return result except: Tools.debug("Error while reading from I2C device at address: " + str(self.address)) return None
def exit(self): """ Cleans-up and releases all resources. """ global _isButtonEnabled Tools.debug("Calling Robot.exit()") self.setButtonEnabled(False) # Stop motors SharedConstants.LEFT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.LEFT_MOTOR_PWM[1].ChangeDutyCycle(0) SharedConstants.RIGHT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.RIGHT_MOTOR_PWM[1].ChangeDutyCycle(0) # Stop button thread, if necessary if _buttonThread != None: _buttonThread.stop() # Stop display display = Display._myInstance if display != None: display.stopTicker() display.clear() Led.clearAll() Tools.delay(2000) # avoid "sys.excepthook is missing"
def captureJPEG(self, width, height): ''' Takes a camera picture with given picture size and returns the image in JPEG format. The picture resolution is width x height (max: 5 MPix) @param width: the width of the picture in pixels (max: 2592) @param height: the height of the picture in pixels (max: 1944) return: the image in JPEG format (as string); None, if the capture fails ''' self._checkRobot() camera = picamera.PiCamera() imageData = StringIO.StringIO() w = int(width) h = int(height) try: Tools.debug("Camera capture with (width, height) = (%d, %d)" % (w, h)) camera.capture(imageData, format="jpeg", resize=(w, h)) imageData.seek(0) data = imageData.getvalue() Tools.debug("Captured jpeg size: " + str(len(data))) return data finally: camera.close() return None # error
def on_post(self, req, resp): try: # Reading Json raw_json = req.stream.read(req.content_length or 0).decode('utf-8') resultdict_json = json.loads(raw_json, object_pairs_hook=OrderedDict, encoding='utf-8') # Converting Json to List list_values = [v for v in resultdict_json.values()] # Database Connection database_connection =get_db_connection() cursor = database_connection.cursor() # Accessing Temporary password function from Tools tempPassword = Tools.TemporaryPassword(size = 8, chars = string.ascii_uppercase + string.digits) # Accessing GenerateTokenId from Tools tokenID = Tools.GenerateTokenId() EmailTools.ActivationEmail(list_values[5],"Intuglo Account Activation",list_values[0],tokenID) status_signup = Tools.SignupUser(resultdict_json['Name'], resultdict_json['PhoneNumber'], resultdict_json['Country'], resultdict_json['Business'], resultdict_json['Industry'],resultdict_json['Email'],resultdict_json['UserType'],2,tokenID,tempPassword,cursor,database_connection) if(status_signup is True): resp.status = falcon.HTTP_200 message = {'Status': 'Your account is successfully created'} result_json = json.dumps(message,default=str) resp.body = result_json else: resp.status = falcon.HTTP_400 message = {'Status': 'Email existed. Try login with another email'} result_json = json.dumps(message) resp.body = result_json except ValueError as err: raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args) except pymysql.IntegrityError as err: raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args) except Exception as err: raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args) finally: cursor.close() database_connection.close()
def __init__(self, id, **kwargs): ''' Creates a light sensor instance with given id. IDs: 0: front left, 1: front right, 2: rear left, 3: rear right The following global constants are defined: LS_FRONT_LEFT = 0, LS_FRONT_RIGHT = 1, LS_REAR_LEFT = 2, LS_REAR_RIGHT = 3. @param id: the LightSensor identifier ''' self.id = id self.sensorState = "DARK" self.sensorType = "LightSensor" self.triggerLevel = 500 self.brightCallback = None self.darkCallback = None self.isRegistered = False for key in kwargs: if key == "bright": self.brightCallback = kwargs[key] elif key == "dark": self.darkCallback = kwargs[key] robot = RobotInstance.getRobot() if robot == None: # deferred registering, because Robot not yet created RobotInstance._sensorsToRegister.append(self) else: if self.brightCallback != None or self.darkCallback != None: robot.registerSensor(self) Tools.debug("LightSensor instance with ID " + str(id) + " created")
def __init__(self, id, **kwargs): ''' Creates an infrared sensor at given port. For the Pi2Go the following infrared sensors are used: id = 0: front center; id = 1: front left; id = 2: front right; id = 3: line left; id = 4: line right. The following global constants are defined: IR_CENTER = 0, IR_LEFT = 1, IR_RIGHT = 2, IR_LINE_LEFT = 3, IR_LINE_RIGHT = 4 @param id: sensor identifier ''' self.id = id self.sensorState = "PASSIVATED" self.sensorType = "InfraredSensor" self.activateCallback = None self.passivateCallback = None for key in kwargs: if key == "activated": self.activateCallback = kwargs[key] elif key == "passivated": self.passivateCallback = kwargs[key] robot = RobotInstance.getRobot() if robot == None: # deferred registering, because Robot not yet created RobotInstance._sensorsToRegister.append(self) else: if self.activateCallback != None or self.passivateCallback != None: robot.registerSensor(self) Tools.debug("InfraredSensor instance with ID " + str(id) + " created")
def crete_bonds_list(self): b = self.read_psf() list_of_bonds = [] atom_list = self.create_atom_list() for i in range(len(b)): if len(b[i]) % 2 == 0: for j in range(len(b[i])): if j == 0: atom_1 = Tools.find_atom(b[i][j], atom_list) atom_2 = Tools.find_atom(b[i][j + 1], atom_list) if atom_1 is not None and atom_2 is not None: bond = Bond(atom_1, atom_2).create_bond() list_of_bonds.append(bond) else: if ((j * 2) + 1) < len(b[i]): atom_1 = Tools.find_atom(b[i][j * 2], atom_list) atom_2 = Tools.find_atom(b[i][(j * 2) + 1], atom_list) if atom_1 is not None and atom_2 is not None: bond = Bond(atom_1, atom_2).create_bond() list_of_bonds.append(bond) else: logging.info('The number of bonds is odd') break return list_of_bonds
def defineNeighbourhood(self, sector=Sector, numberOfcandidatesPerSector=int, neighbourhoodBoundarySize=1.2): if sector.getsize() <= 1: if sector.getid() != 0: temp = self.sectors[0].getvertices() for i in range(1, self.getsectorsNumber()): if sector.getid() == i: continue temp = np.append(temp, [self.sectors[i].getvertices()]) return temp neighbourhoodBoundary = sector.getdiameter( ) * neighbourhoodBoundarySize neighbourhood = np.empty((0)) for i in self.sectors: if i == sector: continue if i.getsize() <= self.sectorMinSize: continue temp = i.getFurthestVertices(numberOfcandidatesPerSector) if not hasattr(temp, "__iter__"): if Tools.distanceCalculationMethod( sector.getcentroid(), temp) <= neighbourhoodBoundary: neighbourhood = np.append(neighbourhood, [temp]) else: for j in temp: if Tools.distanceCalculationMethod( sector.getcentroid(), j) < neighbourhoodBoundary: neighbourhood = np.append(neighbourhood, [j]) return neighbourhood
def getValue(self): ''' Checks, if reflected light is detected. @return: 1, if the sensor detects reflected light; otherwise 0 @rtype: int ''' Tools.delay(1) self._checkRobot() if self.id == SharedConstants.IR_CENTER and \ GPIO.input(SharedConstants.P_FRONT_CENTER) == GPIO.LOW: return 1 elif self.id == SharedConstants.IR_LEFT and \ GPIO.input(SharedConstants.P_FRONT_LEFT) == GPIO.LOW: return 1 elif self.id == SharedConstants.IR_RIGHT and \ GPIO.input(SharedConstants.P_FRONT_RIGHT) == GPIO.LOW: return 1 elif self.id == SharedConstants.IR_LINE_LEFT and \ GPIO.input(SharedConstants.P_LINE_LEFT) == GPIO.LOW: return 1 elif self.id == SharedConstants.IR_LINE_RIGHT and \ GPIO.input(SharedConstants.P_LINE_RIGHT) == GPIO.LOW: return 1 else: return 0
def isButtonDown(self): """ Checks if button is currently pressed. @return: True, if the button is actually pressed """ Tools.delay(1) return GPIO.input(SharedConstants.P_BUTTON) == GPIO.LOW
def _writeByte(self, reg, value): try: self.bus.write_byte_data(self.address, reg, value) except: Tools.debug("Error while writing to I2C device at address: " + str(self.address)) self._isAvailable = False
def reactionSSA(tube, time, tag, isRecordReact): # print("\t\t\t\tCast Number of Chemical Species to Integer") Tools.integerize(tube) # print("\t\t\t\tAppending") Tools.appendProduct(tube) reverse = False # print("\t\t\t\tFinding Reaction") tube.R = Tools.findReactions(tube, reverse) # print("\t\t\t\tStart SSA") if tube.R : ssam = SSAModule() dm = DataModule() if isinstance(tube, DNATube) : molCountsList, spcsList, headList, timeCounts, rTimeEnd = ssam.SSA(tube, time) if isRecordReact : for i in range(len(molCountsList)) : molCounts = molCountsList[i] spcs = spcsList[i] head = headList[i] dm.saveMolCounts(molCounts, spcs, head, tag, tube.lbl) dm.saveMolCounts(timeCounts, ["time"], "time", tag, tube.lbl) elif isinstance(tube, Tube) : molCounts, items, rTimeEnd = ssam.SSA(tube, time) if isRecordReact : dm.saveMolCounts(molCounts, items, "All", tag, tube.lbl) # Tools.plotReactionProcess(molCounts) return rTimeEnd else : print "Error : Tube doesn't have reactions"
def R_learning(coups, parties, id_gagnes, player, name, ratio, nb_partie, epoch): # print ('-'*15, 'Apprentissage', '-'*15) nb_coup_total = 0 for i in range(len(parties)): # print ('-'*15, 'Parties %d' %i, '-'*15) coups[i] = np.array(coups[i]) parties[i] = np.array(parties[i]) parties[i] = np.concatenate(parties[i], axis=0) nb_coup_total += len(coups[i]) if i in id_gagnes: optimizer.lr = np.absolute(optimizer.lr) else: optimizer.lr = np.absolute(optimizer.lr) * -1 # player.policy.model.train_on_batch(np.concatenate(parties[i], axis=0),np.concatenate(coups[i],axis=0)) loss = player.policy.model.train_on_batch(parties[i], coups[i]) # print("loss =",loss) # player.policy.model.train_on_batch(np.concatenate(parties[i], axis=0),coups[i]) date = datetime.datetime.now() filepath = "model/%s/%s_R=%2f_N=%d_H=%s_%s_%sh%s.hdf5" % ( "RL", name, ratio, nb_partie, date.day, date.month, date.hour, date.minute) tfilepath = "model/%s/%s_R=%2f_N=%d_H=%s_%s_%sh%s.txt" % ( "RL", name, ratio, nb_partie, date.day, date.month, date.hour, date.minute) player.policy.model.save(filepath) print('%d coups sur %d parties appris' % (nb_coup_total, len(parties))) Tools.text_file(tfilepath, player.policy.model.model, nb_coup_total, epoch, date) return filepath
def __init__(self): """ Creates a gear instance. """ self.speed = SharedConstants.GEAR_DEFAULT_SPEED self.state = GearState.UNDEFINED Tools.debug("Gear instance created")
def isButtonDown(self): ''' Checks if button is currently pressed. @return: True, if the button is actually pressed ''' Tools.delay(1) return GPIO.input(SharedConstants.P_BUTTON) == GPIO.LOW
def exit(self): """ Cleans-up and releases all resources. """ global _isButtonEnabled Tools.debug("Calling Robot.exit()") self.setButtonEnabled(False) # Stop motors SharedConstants.LEFT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.LEFT_MOTOR_PWM[1].ChangeDutyCycle(0) SharedConstants.RIGHT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.RIGHT_MOTOR_PWM[1].ChangeDutyCycle(0) # Stop button thread, if necessary if _buttonThread != None: _buttonThread.stop() # Stop display display = Display._myInstance if display != None: display.stopTicker() display.clear() Led.clearAll() MyRobot.closeSound() if self.sensorThread != None: self.sensorThread.stop() self.sensorThread.join(2000) # GPIO.cleanup() Do not cleanup, otherwise button will not work any more when coming back # from remote execution Tools.delay(2000) # avoid "sys.excepthook is missing"
def hand_calibration_action(self): #action sequence that help with the calibration #first store the current diff init_roll = self._last_imu['roll'] init_pitch = self._last_imu['pitch'] limit = 20 #wait until either of them is pass the limit while True: if np.abs(self._last_imu['roll'] - init_roll) > limit: break if np.abs(self._last_imu['pitch'] - init_pitch) > limit: break #save those two values roll_x = self._last_imu['roll'] pitch_y = self._last_imu['pitch'] #calculate how much to rotate from current plane point, normal = Tools.create_plane_from_roll_pitch(roll_x, pitch_y) vec = Tools.project_to_plane(normal, np.array([0, 0, 1])) vec = vec / np.linalg.norm(vec) base_vec = np.array([1, 0, 0]) roll_val = np.rad2deg(Tools.get_2D_rotation(base_vec, vec)) roll_val = int(roll_val) if (roll_val < 0): roll_val = 360 + roll_val #print("roll:{}, pitch:{}".format(roll_x, pitch_y)) self._calibration_backend(roll_val)
def breakLog(shellName: str, shellItem: dict): if not FileOS5.orderExists(shellItem, '-f'): # 源文件 return logJson = Tools.getJson(shellItem['-f']) if logJson['boolOk']: logInf = logJson['jsonRes'] if logInf['shellName'] in FileOS5.canBreak: ['removefile', 'removedir', 'renamefile', 'renamedir', 'exchangefile'] for num, val in enumerate(logInf['data']): if logInf['shellName'] in ['removefile', 'removedir', 'exchangefile']: # 移动文件/文件夹,交换文件 oldPath = val['oldPath'] newPath = val['newPath'] copyFODRes = Tools.copyOrMoveFOD(newPath, oldPath, boolFOD=logInf['shellName'] in [ 'removefile', 'exchangefile'], copyOrMove=False) if copyFODRes['boolOk']: print('回退成功', str(num), newPath, oldPath) else: print('回退失败', str(num), newPath, oldPath) elif logInf['shellName'] in ['renamefile', 'renamedir']: # 文件/文件夹改名回退 oldPath = val['oldPath'] newPath = val['newPath'] renameFODRes = Tools.copyOrMoveFOD( newPath, oldPath, boolFOD=logInf['shellName'] == 'renamefile', copyOrMove=False) if renameFODRes['boolOk']: print('回退成功', str(num), newPath, oldPath) else: print('回退失败', str(num), newPath, oldPath) else: print('次命令不支持回退:', logInf['shellName']) else: print('日志错误,错误如下:', logInf['errorInf'])
def _test(self, sess, info): # load batch images, labels = self.data.get_test_data(0) prediction, is_correct, accuracy = sess.run( [self.net.prediction, self.net.is_correct, self.net.accuracy], feed_dict={ self.net.x: images, self.net.y: labels }) labels = np.squeeze(labels, axis=3) * (255 / self.data.class_number) prediction = np.squeeze(prediction, axis=3) * (255 / self.data.class_number) is_correct = np.squeeze(is_correct, axis=3) * 255 Tools.print_info("acc is {}".format(accuracy)) for index in range(len(prediction)): name = "{}_{}".format(info, index) Image.fromarray(images[index]).convert("RGB").save( os.path.join(self.result_path, "{}_i.png".format(name))) Image.fromarray(labels[index]).convert("L").save( os.path.join(self.result_path, "{}_l.png".format(name))) Image.fromarray(prediction[index]).convert("L").save( os.path.join(self.result_path, "{}_p.png".format(name))) Image.fromarray(is_correct[index]).convert("L").save( os.path.join(self.result_path, "{}_c.png".format(name))) pass
def renameFileOrDir(shellName: str, shellItem: dict, logData: dict, boolFOD: bool = True): if not FileOS5.orderExists(shellItem, '-f'): # 源文件 return # 改名规则 rule = [] if '-o' in shellItem: rule = Tools.checkRule( shellItem['-o'], boolAdd='-a' not in shellItem) if not rule['boolOk']: print('改名规则错误', rule['noUseList']) return # 日志 logRealyFile = FileOS5.logRealyPath(shellName, shellItem) # 搜索 print('开始搜索,请等待片刻') findFileRes = Tools.fileRoot(shellItem['-f'], shellItem['-r'], boolson=( '-s' in shellItem), boolFOD=boolFOD, boolShow=('-t' in shellItem)) if not findFileRes['boolOk']: print('出现错误,错误如下:{}'.format(findFileRes['errorInf'])) return print('搜寻总数:', findFileRes['findSum']) # 确认操作 if Tools.checkBegin('确认改名<Y/N>:'): return print('正在修改,请等待片刻') # 复制操作 FileOS5.renameFODItem( findFileRes['findList'], shellName, shellItem, logData, rule, boolFOD=boolFOD) print('成功数:', logData['sum'][0], '失败数:', logData['sum'][1]) # 写入日志 Tools.createLog(shellItem, logRealyFile, logData)
def write_sheet_to_lua_script(self, output_path, sheet_name, sheet): sheet_name = sheet_name.lower() if not os.path.exists(output_path): os.mkdir(output_path) output_filename = output_path + "/" + sheet_name + ".lua" outfp = codecs.open(output_filename, 'w', 'UTF-8') create_time = time.strftime("%a %b %d %H:%M:%S %Y", time.gmtime(time.time())) outfp.write(Tools.SCRIPT_HEAD_STR % (create_time)) outfp.write("local " + sheet_name + " =") outfp.write("\n{") for row_idx, row in sheet.items(): row_key = Tools.get_string(row[0]) outfp.write("\t[" + "\"" + row_key + "\"" + "] = ") row_value = Tools.get_string(row[1]) outfp.write("\"" + row_value + "\",\n") outfp.write("}\n") outfp.write("\nfunction " + sheet_name + ".get_text(key, ...)\n\treturn string.format(" + sheet_name + "[key], ...);\nend\n") outfp.write( "\nfunction " + sheet_name + ".get_temp_text(key, ...)\n\treturn string.format(key, ...);\nend\n" ) outfp.write("\nreturn " + sheet_name) outfp.close()
def train(self, epochs, loss_freq, model_freq, test_freq): with self.supervisor.managed_session(config=self.config) as sess: for step in range(epochs): image_b, label_b = sess.run([self.net.images, self.net.labels]) ind = np.where(label_b == 11) label_b[ind] = 0 image_b[:, ...] -= Config[self.net.dataset]["mean_pixel"] _, loss, accuracy = sess.run( [self.net.train_op, self.net.loss, self.net.accuracy], feed_dict={ self.net.x: image_b, self.net.y: label_b }) # label_b = np.squeeze(label_b, axis=0) # index = label_b.ravel() # image_size = [image_b.shape[1], image_b.shape[2], image_b.shape[3]] # color_image = Config[self.net.dataset]['palette'][index].reshape(image_size) # Image.fromarray(np.squeeze(color_image)).convert("RGB").save('1.png') # Image.fromarray(np.squeeze(label_b)).convert("L").save('2.bmp') # Image.fromarray(np.squeeze(np.asarray(image_b, dtype=np.uint8))).convert("RGB").save('3.png') if step % loss_freq == 0: Tools.print_info("step {} loss : {}, acc : {}".format( step, loss, accuracy)) if step % test_freq == 0: self._test(sess, step) if step % model_freq == 0 or (step + 1) == epochs: self.supervisor.saver.save( sess, os.path.join(self.model_path, "model_epoch_{}".format(step + 1))) pass pass pass
def test(self): # 加载模型 Tools.restore_if_y(self.sess, self.log_dir) # 运行 coord = tf.train.Coordinator() # 线程队列 threads = tf.train.start_queue_runners(coord=coord, sess=self.sess) # Iterate over training steps. batch_number = np.ceil(len(self.reader.images_list) / self.batch_size) for step in range(int(batch_number)): start_time = time.time() raw_outputs, images_name, images_size = self.sess.run( [self.raw_output_op, self.images_name_op, self.images_size_op]) # Predictions:图片变成原来的大小 predictions = [] for index, raw_output in enumerate(raw_outputs): raw_output = tf.expand_dims(raw_output, axis=0) raw_output = tf.image.resize_bilinear(raw_output, size=images_size[index], align_corners=True) raw_output = tf.argmax(raw_output, axis=3) prediction = tf.expand_dims(raw_output, dim=3) prediction = tf.squeeze(prediction, axis=0) predictions.append(self.sess.run(prediction)) duration = time.time() - start_time # 着色 images_result = Tools.decode_labels_test( predictions, num_images=1, num_classes=self.num_classes) self._save_result(images_result, duration, images_name) pass coord.request_stop() coord.join(threads) pass
def click_btn_charge(self): tmp_name = self.context.txt_name.text() tmp_count = int(self.context.txt_counter.text()) tmp_phonenumber = self.context.txt_phonenumber.text() tmp_vip = 0 tmp_current_date = str(datetime.now()) tmp_active = 1 tmp_price = self.context.txt_price.text() if not Tools.validation_text(tmp_name, tmp_count, tmp_phonenumber, tmp_price): Tools.set_error_text(self.context.txt_price, self.context.txt_phonenumber, self.context.txt_counter, self.context.txt_name) return db = database() for i in range(tmp_count): tmp_card_id = RFIDReader().read_card_id() query = "insert into tbl_user (name, phonenumber, vip, card_id, date, active, price) values" \ "('%s', '%s', %d, '%s','%s', %d, %s)" % \ (tmp_name, tmp_phonenumber, tmp_vip, tmp_card_id, tmp_current_date, tmp_active, tmp_price) result = db.insert(query) db.close()
def click_btn_scan(self): tmp_count = self.context.txt_count.text() if not Tools.validation_text(tmp_count): Tools.set_error_text(self.context.txt_count) return tmp_count = int(tmp_count) db = database() for i in range(tmp_count): self.cards_id.append(RFIDReader().read_card_id()) query = """ select tbl_user.name, tbl_order.count, tbl_facility.name, tbl_facility.price from tbl_order inner join tbl_user on tbl_user.id=tbl_order.id_user inner join tbl_facility on tbl_facility.id=tbl_order.id_facility where tbl_order.active=1 and tbl_user.card_id='%s' """ % self.cards_id[-1] data = db.select(query) if data is not None: self.data.append(data) if len(self.data) == 0: return PDF().create_pdf(self.data) db.close() self.context.btn_checkout.setEnabled(True)
def run(self): Tools.debug("Led blinker thread starting") nb = 0 self._isRunning = True while self._isRunning: self.led.setColor(self._onColor) startTime = time.time() while time.time() - startTime < self._onTime / 1000.0 and self._isRunning: time.sleep(0.001) if not self._isRunning: break self.led.setColor(self._offColor) startTime = time.time() while time.time() - startTime < self._offTime / 1000.0 and self._isRunning: time.sleep(0.001) if not self._isRunning: break nb += 1 if nb == self._count: self._isRunning = False self.led.setColor(0, 0, 0) self.led._blinkerThread = None self._isAlive = False Tools.debug("Led blinker thread finished")
def run(self): Tools.debug("Beeper thread started") nb = 0 self._isRunning = True while self._isRunning: if self._onTime <= 0: self._beeper.turnOff() time.sleep(0.01) else: self._beeper.turnOn() startTime = time.time() while time.time( ) - startTime < self._onTime / 1000 and self._isRunning: time.sleep(0.001) if not self._isRunning: break self._beeper.turnOff() startTime = time.time() while time.time( ) - startTime < self._offTime / 1000 and self._isRunning: time.sleep(0.001) if not self._isRunning: break nb += 1 if nb == self._count: self._isRunning = False self._beeper.turnOff() self._beeper._beeperThread = None self._isAlive = False Tools.debug("Beeper thread finished")
def on_patch(self, req, resp, login_id, session): #Authenticate login id and session availability. try: if (MemcacheFunctions.IsSessionValid(login_id, session) is False): resp.status = falcon.HTTP_401 Error = {"Reason": "Invalid Login Credentials or Session is Expired"} result_json = json.dumps(Error) resp.body = result_json return except ValueError as err: raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args) except Exception as err: raise falcon.HTTPError(falcon.HTTP_400, 'Error', err.args) try : # Reading Json raw_json = req.stream.read(req.content_length or 0).decode('utf-8') resultdict_json = json.loads(raw_json, object_pairs_hook=OrderedDict, encoding='utf-8') # Json value quotation_id = resultdict_json['quotation_id'] old_status = resultdict_json['current_quotation_status'] desired_status = resultdict_json['quotation_status'] # Connecting the database database_connection = get_db_connection() cursor = database_connection.cursor() # Check the quotation status cursor.execute("select q.quotation_status, l.official_email\ from ship_quotations q\ join logistic_providers l on q.supplier_login_id = l.login_id\ where q.quotation_id = '"+quotation_id+"'") row = cursor.fetchone() if (cursor.rowcount > 0): book_status_dict = Tools.QuotationStatus(desired_status,old_status) print(book_status_dict) book_status_list = book_status_dict['current_quotation_status'] if(old_status in book_status_list): index_code = book_status_list.index(old_status) Tools.ChangeQuotationStatus(quotation_id, desired_status,cursor,database_connection) resp.status = falcon.HTTP_200 resp.body = ("200") if(desired_status == 'CLOSED'): EmailTools.QTClosedEmailNotify(row['official_email'],quotation_id,10) else: resp.status = falcon.HTTP_202 resp.body = ("202") else: resp.status = falcon.HTTP_204 resp.body = ("204") except ValueError as err: raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args) except pymysql.IntegrityError as err: raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args) except Exception as err: raise falcon.HTTPError(falcon.HTTP_400, traceback.print_exc(file=sys.stdout) , err.args) finally: cursor.close() database_connection.close()
def run_spider(self, url, type): tool = Tools() soup = tool.gethtml(url) cid = self.get_category(soup, type) box_list = soup.select(".zxlist ul") self.get_list_con(box_list, cid)
def __init__(self, batch_size, is_flip, num_classes, test_list, log_dir, save_dir, model_name="model.ckpt"): self.test_list = test_list self.save_dir = Tools.new_dir(save_dir) self.log_dir = Tools.new_dir(log_dir) self.model_name = model_name self.checkpoint_path = os.path.join(self.log_dir, self.model_name) self.num_classes = num_classes self.batch_size = batch_size self.last_pool_size = 90 self.filter_number = 64 self.is_flip = is_flip # 读取数据 self.reader = ReaderTestImage(self.test_list) # net self.raw_output_op, self.images_name_op, self.images_size_op = self._init_net( ) # sess self.sess = tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions( allow_growth=True))) self.sess.run(tf.global_variables_initializer()) pass
def __init__(self, pin=40): self._checkRobot() self.robot = RobotInstance.getRobot() self._pin = pin self._beeperThread = None Tools.debug("Beeper instance created with beeper at pin: " + str(pin)) GPIO.setup(pin, GPIO.OUT) self.turnOff()
def setButtonEnabled(self, enable): """ Enables/disables the push button. The button is enabled, when the Robot is created. @param enable: if True, the button is enabled; otherwise disabled """ Tools.debug("Calling setButtonEnabled() with enable = " + str(enable)) global _isButtonEnabled _isButtonEnabled = enable
def run(self): count = 0 while self.isRunning and count < SharedConstants.BUTTON_LONGPRESS_DURATION: Tools.delay(200) count += 1 if self.isRunning: if _buttonListener != None: _buttonListener(SharedConstants.BUTTON_LONGPRESSED)
def _save_result(self, predictions, duration, file_names): for index, file_name in enumerate(file_names): file_name = os.path.split(str(file_name).split("'")[1])[1] Image.fromarray(predictions[index]).convert("RGB").save( os.path.join(self.save_dir, file_name)) Tools.print_info('duration {} save in {}'.format( duration, os.path.join(self.save_dir, file_name))) pass
def setButtonEnabled(self, enable): ''' Enables/disables the push button. The button is enabled, when the Robot is created. @param enable: if True, the button is enabled; otherwise disabled ''' Tools.debug("Calling setButtonEnabled() with enable = " + str(enable)) global _isButtonEnabled _isButtonEnabled = enable
def __init__(self): ''' Creates a gear instance. ''' self.speed = SharedConstants.GEAR_DEFAULT_SPEED self.state = GearState.UNDEFINED self.arcRadius = 0 Tools.debug("Gear instance created")
def run(self): Tools.debug("===>ButtonThread started") self.isRunning = True startTime = time.time() while self.isRunning and (time.time() - startTime < SharedConstants.BUTTON_LONGPRESS_DURATION): time.sleep(0.1) if self.isRunning: if _buttonListener != None: _buttonListener(SharedConstants.BUTTON_LONGPRESSED) Tools.debug("===>ButtonThread terminated")
def isButtonHit(self): """ Checks, if the button was ever hit or hit since the last invocation. @return: True, if the button was hit; otherwise False """ global _isBtnHit Tools.delay(1) hit = _isBtnHit _isBtnHit = False return hit
def testForValidIds(self): data = self.cleaned_data print "data is ", data Tool = Tools() self.release_ids = Tool.parseOutReleaseIds(data['release_id_string']) if self.release_ids: return True else: return False
def __init__(self, id): ''' Creates a light sensor instance with given id. IDs: 0: front left, 1: front right, 2: rear left, 3: rear right The following global constants are defined: LS_FRONT_LEFT = 0, LS_FRONT_RIGHT = 1, LS_REAR_LEFT = 2, LS_REAR_RIGHT = 3. @param id: the LightSensor identifier ''' self.id = id Tools.debug("LightSensor instance with ID " + str(id) + " created")
def __init__(self, id): ''' Creates a Led instance with given ID. IDs of the double LEDs: 0: front, 1: left side , 2: rear, 3: right side. The following global constants are defined: LED_FRONT = 0, LED_LEFT = 1, LED_REAR = 2, RED_RIGHT = 3. @param id: the LED identifier ''' self.id = id Tools.debug("Led instance with ID " + str(id) + " created")
def run(self): Tools.debug("===>ClickThread started") global _clickThread self.isRunning = True startTime = time.time() while self.isRunning and (time.time() - startTime < SharedConstants.BUTTON_DOUBLECLICK_TIME): time.sleep(0.1) if _clickCount == 1 and not _isLongPressEvent: if _xButtonListener != None: _xButtonListener(SharedConstants.BUTTON_CLICKED) _clickThread = None Tools.debug("===>ClickThread terminated")
def stop(self): """ Stops the gear. (If gear is already stopped, returns immediately.) """ Tools.debug("Calling Gear.stop()") self._checkRobot() if self.state != GearState.STOPPED: SharedConstants.LEFT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.LEFT_MOTOR_PWM[1].ChangeDutyCycle(0) SharedConstants.RIGHT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.RIGHT_MOTOR_PWM[1].ChangeDutyCycle(0) self.state = GearState.STOPPED
def getValue(self): ''' Returns the current intensity value (0..1000). @return: the measured light intensity @rtype: int ''' self._checkRobot() Tools.delay(1) nb = self.id if nb == 0: nb = 1 elif nb == 1: nb = 0 robot = RobotInstance.getRobot() return int(self._readADC(nb) / 255.0 * 1000 + 0.5)
def __init__(self, id, home, inc): ''' Creates a servo motor instance and sets it at home position. For most servos: home = 300, inc = 2 @param id: the id of the motor (0..3) @param home: the PWM duty cycle for the home position (0..4095) @param inc: the increment factor (inc_duty/inc_position) ''' self.id = id self.home = home self.inc = inc self._checkRobot() self.robot = RobotInstance.getRobot() self.robot.pwm.setDuty(SharedConstants.SERVO_0 + self.id, home) Tools.debug("ServoMotor instance created")
def setSpeed(self, speed): """ Sets the speed to the given value (arbitrary units). The speed will be changed to the new value at the next movement call only. The speed is limited to 0..100. @param speed: the new speed 0..100 """ Tools.debug("Calling Gear.setSpeed with speed: " + str(speed)) if self.speed == speed: return if speed > 100: speed = 100 if speed < 0: speed = 0 self.speed = speed self.state = GearState.UNDEFINED
def getValue(self): ''' Returns the distance. @return: Distance from target in cm, or -1 if no object or error @rtype: float ''' self._checkRobot() # Set pins as output and input GPIO.setup(SharedConstants.P_TRIG_ECHO, GPIO.OUT) GPIO.output(SharedConstants.P_TRIG_ECHO, GPIO.LOW) # Allow module to settle time.sleep(0.1) # Send max 10 us trigger pulse GPIO.output(SharedConstants.P_TRIG_ECHO, GPIO.HIGH) time.sleep(0.00001) GPIO.output(SharedConstants.P_TRIG_ECHO, GPIO.LOW) # Prepare for echo GPIO.setup(SharedConstants.P_TRIG_ECHO, GPIO.IN) # Determine echo pulse length start = time.time() count = start end = time.time() # Wait max 1 s for HIGH signal while GPIO.input(SharedConstants.P_TRIG_ECHO) == GPIO.LOW and count - start < 1: count = time.time() if count - start >= 1: Tools.debug("Timeout while waiting for echo going HIGH") return -1 # error start = count # Wait for LOW signal elapsed = 0 while GPIO.input(SharedConstants.P_TRIG_ECHO) == GPIO.HIGH: elapsed = time.time() - start if elapsed > 0.015: # echo considered as failed (distance too big) break # Distance = speed_of_sound * elapsed / 2 distance = 34300 * elapsed / 2.0 # round to 2 decimals distance = int(distance * 100 + 0.5) / 100.0 return distance
def stop(self): ''' Stops the motor. (If motor is already stopped, returns immediately.) ''' Tools.debug("Calling Motor.stop(). MotorID: " + str(self.id)) if self.state == MotorState.STOPPED: return self._checkRobot() if self.id == SharedConstants.MOTOR_LEFT: SharedConstants.LEFT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.LEFT_MOTOR_PWM[1].ChangeDutyCycle(0) else: SharedConstants.RIGHT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.RIGHT_MOTOR_PWM[1].ChangeDutyCycle(0) self.state = MotorState.STOPPED Tools.debug("Done Motor.stop()")
def __init__(self, config): self.logger = logging.getLogger('browbeat.Shaker') self.config = config self.tools = Tools(self.config) self.grafana = Grafana(self.config) self.error_count = 0 self.pass_count = 0 self.test_count = 0 self.scenario_count = 0
def backward(self): ''' Starts the backward rotation with preset speed. The method returns immediately, while the rotation continues. ''' Tools.debug("Calling Motor.backward(). MotorID: " + str(self.id)) if self.state == MotorState.BACKWARD: return self._checkRobot() duty = self.speedToDutyCycle(self.speed) if self.id == SharedConstants.MOTOR_LEFT: SharedConstants.LEFT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.LEFT_MOTOR_PWM[1].ChangeDutyCycle(duty) else: SharedConstants.RIGHT_MOTOR_PWM[0].ChangeDutyCycle(0) SharedConstants.RIGHT_MOTOR_PWM[1].ChangeDutyCycle(duty) self.state = MotorState.BACKWARD Tools.debug("Done Motor.backward()")
def __init__(self, config, hosts=None): self.logger = logging.getLogger('browbeat.Rally') self.config = config self.tools = Tools(self.config) self.connmon = Connmon(self.config) self.grafana = Grafana(self.config) self.error_count = 0 self.pass_count = 0 self.test_count = 0 self.scenario_count = 0
def __init__(self, config): self.logger = logging.getLogger("browbeat.PerfKit") self.config = config self.error_count = 0 self.tools = Tools(self.config) self.connmon = Connmon(self.config) self.grafana = Grafana(self.config) self.test_count = 0 self.scenario_count = 0 self.pass_count = 0
def add_initial_children(self): # add tools, operations, etc. self.children = [] self.tools = Tools() self.tools.load_default() self.Add(self.tools) self.operations = Operations() self.Add(self.operations) self.nccode = NCCode() self.Add(self.nccode)
class Sale_Spider(BaseSpider): name = "sale" db = None tools = None debug = True level_id = '' attributes = [] domain = "http://www.autohome.com.cn/" allowed_domains = ["autohome.com.cn"] start_urls = [ "http://www.autohome.com.cn/b/", ] # parse start def parse(self, response): urls = [] handle = open("./files/sale_urls.log", 'r') while True: url = handle.readline() if len(url) == 0: break urls.append(url[0:-1]) handle.close() self.tools = Tools() for url in urls: yield scrapy.Request(url, callback=self.parse_page) def parse_page(self, response): re_url = re.findall(r"(\d+)", response.url) model_id = re_url[0] re_cars = re.findall(r"<a href=\""+model_id+"\/(\d+)\/options\.html\">.*?<\/a>", response.body) if len(re_cars) > 0 : for car_id in re_cars : option_url = self.tools.build_sub_option_url(model_id, car_id) self.tools.save_file("sub_option_urls.log", option_url)
def main(request): if request.method == "POST": form = DeleteForm(post=request.POST,user=request.session['user']) Tools.deleteGivenFiles(form.data,request) #Deleting files from data in form.data and finding in which folder from session in request return render(request,'base.html',{'message_m':'Files deleted'}) else: formD = DeleteForm() formR = RenameForm() formR.addForm(request.session['user']) formD.addForm(request.session['user']) linki = prepareLinks(request.session['user'],formD) #creates links to download for each file from collections import OrderedDict parameters = OrderedDict() parameters['formD'] = formD parameters['formR'] = formR parameters['links'] = linki display = Tools.Display(parameters) return render(request,"main.html",{'D':display})