def run(self): if self.enable: print "Suck activating" else: print "Suck deactivating" movement.suck(self.enable)
def compute_sens_ppv(self): """ Compute sensitivity and ppv of the interaction """ self.ppv=np.arange(float(len(self.interactions))) self.sensitivity=np.arange(float(len(self.interactions))) self.classtype=np.arange(len(self.interactions)) intefunc=self.defintefunction() i=0 for interactid in self.interactions: #Position d'interaction sRNA mRNA predict_RNA=self.dbmanage.getPositionsbyIntid(interactid[0]) ncomp=self.exp_inf.getExpPair(self.dbmanage.getsRNAbyIntid(interactid[0]),self.dbmanage.getmRNAbyIntid(interactid[0])) #Paire qui existe if(ncomp!=None): self.classtype[i]=1 else: self.classtype[i]=0 if(ncomp and predict_RNA): #zone d'interaction predite Pinteract=self.getInteraction(self.pos[i],self.getRangePosit(predict_RNA,0),self.getRangePosit(predict_RNA,1),self.getRangePosit(predict_RNA,2),self.getRangePosit(predict_RNA,3),True,intefunc) #zone d'interaction reelle Rinteract=self.getInteraction(self.pos[i],self.exp_inf.sRNA_deb[ncomp],self.exp_inf.sRNA_fin[ncomp],self.exp_inf.mRNA_deb[ncomp],self.exp_inf.mRNA_fin[ncomp],False,intefunc) #Calcul de la precision self.ppv[i]=self.compute_ppv(Pinteract, Rinteract) #Calcul de la sensibilite self.sensitivity[i]=self.compute_sensitivity(Pinteract,Rinteract) else: self.ppv[i]=np.nan self.sensitivity[i]=np.nan i+=1 #Communication object data=Communication() data.classtype=self.classtype data.ppv=self.ppv data.sensitivity=self.sensitivity return data
def Supervisor(D, graph=None): """ Build Tensorflow graph and run iterations """ if graph == None: graph = tf.Graph() # Build Tensorflow graph with graph.as_default(): # Get Test inputs and labels for compute accuracy from D inputs, labels = D # Build a Graph that computes the logits predictions from the model. logits = mdnn.CNN_model(inputs, graph) # Calculate loss and accuracy. loss = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits)) accuracy = tf.reduce_mean( tf.cast(tf.nn.in_top_k(logits, labels, 1), tf.float32)) # Build an initialization operation to run below. init = tf.global_variables_initializer() #init_glob = tf.variables_initializer(tf.get_collection("W_global")) # Tensorflow op to update parameters from PS get_W = df.get_w(graph, "W_global") with tf.Session(config=tf.ConfigProto( intra_op_parallelism_threads=1)) as sess: #Initialize TF variables sess.run([init]) tf.train.start_queue_runners(sess=sess) iteration = 0 while iteration < FLAGS.iter_max: s = sck.socket(sck.AF_INET, sck.SOCK_STREAM) s.connect((FLAGS.ip_PS, FLAGS.port)) #Get parameters from PS com.send_msg(s, "", "GET_W") _, data = com.recv_msg(s) iteration, W = com.decode_variables(data) s.close() #Update parameters sess.run(get_W, {key + "_delta:0": value for key, value in W.items()}) #Compute gradients stored in Tensorflow variables score, loss_value = sess.run([accuracy, loss]) print("---------------------------------------") print("Iteration ", iteration) print("Test accuracy :", score * 100, "%") print("Test Loss :", loss_value) print("---------------------------------------") # Compute accuracy every minute time.sleep(60)
def Interaction_data(self): """ Get interaction position data """ self.type_sol=self.type_sol intefunc=self.defintefunction() interact=[] i=0 for interactid in self.interactions: if((i%500)==0): print("%d/%d"%(i+1,len(self.interactions))) #Position d'interaction sRNA mRNA predict_RNA=self.dbmanage.getPositionsbyIntid(interactid[0]) #Paire qui existe if(predict_RNA): sRNA_deb=self.getRangePosit(predict_RNA,0) sRNA_end=self.getRangePosit(predict_RNA,1) mRNA_deb=self.getRangePosit(predict_RNA,2) mRNA_end=self.getRangePosit(predict_RNA,3) #zone d'interaction predite Pinteract=self.getInteraction(self.pos[i],sRNA_deb,sRNA_end,mRNA_deb,mRNA_end,True,intefunc) #simplication de la position if(self.type_sol==0 or self.type_sol==1): temp=[sRNA_deb[self.pos[i]],sRNA_end[self.pos[i]],mRNA_deb[self.pos[i]],mRNA_end[self.pos[i]]] elif(self.type_sol==2 or self.type_sol==3): temp=[min(sRNA_deb),max(sRNA_end),min(mRNA_deb),max(mRNA_end)] else: temp=[sRNA_deb,sRNA_end,mRNA_deb,mRNA_end] interact+=[temp+[len(Pinteract[0]),len(Pinteract[1])]] else: interact+=[None] i+=1 #Communication object data=Communication() data.interact=interact return data
def run(self): """ Compute normalized score """ self.norm_score=np.arange(float(len(self.interactions))) self.pos=np.arange(len(self.interactions)) #Score to normalise #listscore=self.dbmanage.getAllScore(self.interactions) #Len sRNA listlensRNA=self.dbmanage.getAllsRNAlenbyIntid(self.interactions) listlenmRNA=self.dbmanage.getAllmRNAlenbyIntid(self.interactions) funcspec=self.defnormfunction() for i in xrange(len(self.interactions)): if((i%500)==0): print("%d/%d"%(i+1,len(self.interactions))) score=self.dbmanage.getScore(self.interactions[i][0]) #if(listscore[i]!=None): # funcspec(listscore[i],np.log(float(listlensRNA[i]*listlenmRNA[i])),self.score_type,i) if(score!=None): funcspec(score,np.log(float(listlensRNA[i]*listlenmRNA[i])),self.score_type,i) #Cas mfe / energy if(self.score_type==2 or self.score_type==3): self.norm_score[i]=-self.norm_score[i] #Nothing is predicted else: self.norm_score[i]=np.nan #Communication object data=Communication() data.norm_score=self.norm_score data.pos=self.pos return data
def receiver(): global table_of_nodes sock = Communication.setReceiver() while True: node_info = json.loads(Communication.receiveMessage(sock)) #When a message is received, a field is added to it indicating the #timestamp of when the message was received node_info.update({'Received': str(datetime.datetime.now())}) #Ignore the own messages sent if node_info['ID'] == NodeID: continue else: lock.acquire() if node_info['Type'] == 'Beacon': try: table_of_nodes = Util.addToTable(node_info, table_of_nodes, 1) finally: lock.release() if node_info['Type'] == 'CAM': try: table_of_nodes = Util.addToTable(node_info, table_of_nodes, 1) finally: lock.release() process_CAM(node_info)
def turn_back(self): for i in range(3): movement.turn(360) time.sleep(1) for i in range(3): movement.turn(-360) time.sleep(1)
def sender(): timeToSendMessage = time.time() + 0.5 while True: lock.acquire() try: number_of_nodes = len(table_of_nodes) finally: lock.release() while time.time() > timeToSendMessage: messageToSend = { 'Type': 'Beacon', 'ID': NodeID, 'Coordinates': gpsInfo, 'Timestamp': str(datetime.datetime.now()) } data = json.dumps(messageToSend) Communication.sendMessage(data) timeToSendMessage = time.time() + 0.5
def move_square(self, sleeptime=2): """ Move in a square """ for i in range(4): movement.drive(1) time.sleep(sleeptime) movement.turn(90) time.sleep(sleeptime)
def sendOrder2Chef(): global gCurrOrder global gOrderId # Print Order PrintMethods.printOrderDetails(gCurrOrder) # Create Xml String orderXmlStr = xmlMethods.order2xmlStr(gCurrOrder) Communication.sendData(orderXmlStr)
def alignment_test(self): for i in range(0, 20): movement.drive(-.10) time.sleep(0.5) for j in range(0, 5): m = self.see() if len(m) > 0: print "Distance %s \n Angle %s" % (m[0].dist, m[0].rot_y) else: print 'cannot see marker'
def main(): # Start Comminucation Communication.init() # Pause (2 Seconds) # time.sleep(2) # Start User Interface UserInterface.startDisplay()
def move_snake(self, sleeptime=2): """ Move in a square """ for turn in [90, -90]: for i in range(2): movement.drive(.5) time.sleep(sleeptime) movement.turn(turn) time.sleep(sleeptime)
def reset_hammer(self): """Reset routine. See Communication.py for a description. Args: self: Class variables Returns: """ button = "C" cm.readard(self.ser, button)
def loading_hammer(self): """Loading routine. See Communication.py for a description. Args: self: Class variables Returns: """ button = "D" cm.readard(self.ser, button)
def calibration(self): """Calibration routine. See Communication.py for a description. Args: self: Class variables Returns: """ button = "E" cm.readard(self.ser, button)
def _quit(self, master): """Quits the application and restarts the kernel and resets the hammer to the ZERO position. Args: master: tkinter root Returns: """ button = "C" cm.readard(self.ser, button) master.quit() master.destroy() exit()
def main(): global gCurrOrderId # Start Comminucation Communication.init() # Database Init dbSQLite3.init() gCurrOrderId = dbSQLite3.getMaxOid() # Pause (2 Seconds) time.sleep(2) # Kitchen Display KitchenDisplay.startDisplay()
def SelectHeroes(): nHeroes=cm.GetInt("How many players are there? (Max 4)",1,4) allowedHeroes=['Harry','Hermione','Ron','Neville','Random'] selectedHeroes=[] for i in range(nHeroes): message="Select a hero from: " for x in allowedHeroes: message+=x+" " message+="\n" while True: txt=input(message) if txt in allowedHeroes: if txt=='Random': txt=allowedHeroes[randint(0,len(allowedHeroes)-2)] print("You got",txt) selectedHeroes.append(Hero(txt,False)) allowedHeroes.remove(txt) break else: print("Not a valid option!!") return selectedHeroes
def run(settings): """ Run does the high level translation work receiving the settings already parsed """ original_language = Language(Language.languages_choose[int(settings.origin_language) - 1]) destiny_language = Language(Language.languages_choose[int(settings.destination_language) - 1]) translation = Translation(original_language, destiny_language) word = settings.word translated_word = Communication.translate(word, translation) print "\nThe translated word is: %s" % translated_word again = raw_input("Do you wish to translate any more words from %s to %s? [y/n]: " % (original_language, destiny_language)) if again == 'y': word2 = raw_input("Please type the Word:") settings.word = word2 run(settings) elif again == 'n': again2 = raw_input("Do you wish to translate any more words? [y/n] ") if again2 == 'y': settings = process_command_line(None) run(settings) else: return os.EX_OK # Returns everything went ok to the environment else: print "wtf? You are doing it Wrong. Quiting!" # sometimes I just miss goto statement. Am I weird? bah. return 1
def __init__(self, vid, pid, interface): self.vid = vid self.pid = pid self.interface = interface self.comm = Communication.communication(vid, pid, interface) #self.interruptInterval = self.comm.ioctl(vid, pid, interface, 0, 0, 0, 0, 0, 0, IN0, IOCTL_INTERRUPT_INTERVAL) self.interruptInterval = 500
def waitForBillRequest(): global gCurrOrderId # Receive Order orderXmlStr = Communication.recvData() # Generate Bill bill = generateBill() # Print Bill PrintMethods.printBillDetails(bill) # Insert Bill dbSQLite3.insertBill(gCurrOrderId, bill) # Send Bill billXmlStr = xmlMethods.bill2xmlStr(bill) Communication.sendData(billXmlStr)
def __init__(self, x_lower, y_lower, width, height, number_of_agents, targets_per_agent, controller_type): self.x_lower = x_lower self.y_lower = y_lower self.x_upper = x_lower + width self.y_upper = y_lower + height self.target_types = list(string.ascii_uppercase) self.number_of_agents = number_of_agents self.targets_per_agent = targets_per_agent self.number_of_targets = number_of_agents * targets_per_agent self.agents = [] self.targets = [] self.public_channel = Communication.CommunicationChannel(0) for i in range(number_of_agents): found_space = False while not found_space: position = [random.randint(self.x_lower, self.x_upper), random.randint(self.y_lower, self.y_upper)] found_space = self.validPosition(position, True) agent = Agent.Agent(self, position[0], position[1], self.target_types[i], controller_type) self.public_channel.addAccess(agent.controller) agent.controller.channels["Public"] = self.public_channel self.agents.append(agent) for j in range(targets_per_agent): found_space = False while not found_space: position = [random.randint(self.x_lower, self.x_upper), random.randint(self.y_lower, self.y_upper)] found_space = self.validPosition(position, False) target = Object.Target(position[0], position[1], self.target_types[i]) self.targets.append(target) i = 0 while i < len(self.agents) - 1: j = i + 1 while j < len(self.agents): channel = Communication.CommunicationChannel(1) agent1 = self.agents[i] agent2 = self.agents[j] channel.addAccess(agent1.controller) agent1.controller.channels[agent2.body.target_type] = channel channel.addAccess(agent2.controller) agent2.controller.channels[agent1.body.target_type] = channel j += 1 i += 1
def camera_error_calibration(self): ''' Do not run during other logic is a locking function - this does not account for error, but allows humans to fix camera For use: Put a box directly ahead of the robot, with it facing the camera. Run this function with a device linked to the robot to get the debug output Ajust the camera till the outputed error is ~0 ''' movement.drive(-2) while 1: markers = self.see_cube() rot = 0 if (len(markers) > 0): rot = markers[0].rot_y distance = markers[0].dist print("Box at heading {0}, distance {1}".format(rot, distance)) time.sleep(2) else: print("No markers seen")
def chatWithTuringOne(self, name): newCommunication = Communication.Communication(name, self.wechatBot) while (True): self.wechatBot.switchToChatAreaBySearch(name) newMessages = newCommunication.readRecentMessage() newMessages = helper.filterNewMessageIreceived(newMessages) if (len(newMessages) != 0): replys = self.getReplyFromTuring(newMessages) self.sendMessage(replys)
def online(self): # begin working, power on each slave thread communication_type = self.config['communication_type'] if (communication_type == 'simplex'): self.communication_thread = Communication.SimplexCommunication(self.config, self) elif (communication_type == 'duplex_client'): self.communication_thread = Communication.DuplexClientCommunication(self.config, self) elif (communication_type == 'duplex_server'): self.communication_thread = Communication.DuplexServerCommunication(self.config, self) elif (communication_type == 'shortterm_client'): self.communication_thread = Communication.ShortTermClientCommunication(self.config, self) else: raise ValueError('invalid communication type[' + communication_type + ']') self.communication_thread.openCommunication() management_cases = self.config['management_cases'] self.management_thread = NetManagement(self.config, self.fielddef, self.package, management_cases, self) self.management_thread.openService() self.start()
def waitForOrderDetails(): global gCurrOrder # Receive Order orderXmlStr = Communication.recvData() gCurrOrder = Order() xmlMethods.xmlStr2order(orderXmlStr, gCurrOrder) # Print Order PrintMethods.printOrderDetails(gCurrOrder) orderId = genearteOrderId() dbSQLite3.insertMaxOid(orderId) # Send OrderId Communication.sendData(str(orderId)) # Insert Order dbSQLite3.insertOrder(orderId, gCurrOrder) return gCurrOrder
def getOrderDetailsStr(): global gCurrOrder global gOrderId # Wait for Order Id orderIdStr = Communication.recvData() gOrderId = int(orderIdStr) if (gCurrOrder.item_1.name[0] == 'F'): food = True else: food = False orderStr = ("======================================================" + "\n" " Order Id : " + str(gOrderId) + "\n\n" " Date : " + gCurrOrder.date + "\n" " Time : " + gCurrOrder.time + "\n" " Table : " + str(gCurrOrder.tableNum) + "\n" " Items : " + str(gCurrOrder.numItems) + "\n") if gCurrOrder.numItems > 0: orderStr = orderStr + (" Item 1 :" + "\n" " Name : " + gCurrOrder.item_1.name + "\n" " Quantity : " + str(gCurrOrder.item_1.quantity) + "\n") if (food == True): orderStr = orderStr + ( " Spice : " + gCurrOrder.item_1.spiceLevel + "\n" " Cook : " + gCurrOrder.item_1.cookLevel + "\n") if gCurrOrder.numItems > 1: orderStr = orderStr + (" Item 2 :" + "\n" " Name : " + gCurrOrder.item_2.name + "\n" " Quantity : " + str(gCurrOrder.item_2.quantity) + "\n") if (food == True): orderStr = orderStr + ( " Spice : " + gCurrOrder.item_2.spiceLevel + "\n" " Cook : " + gCurrOrder.item_2.cookLevel + "\n") if gCurrOrder.numItems > 2: orderStr = orderStr + (" Item 3 :" + "\n" " Name : " + gCurrOrder.item_3.name + "\n" " Quantity : " + str(gCurrOrder.item_3.quantity) + "\n") if (food == True): orderStr = orderStr + ( " Spice : " + gCurrOrder.item_3.spiceLevel + "\n" " Cook : " + gCurrOrder.item_3.cookLevel + "\n") orderStr = orderStr + "======================================================" return orderStr
def run(self): """ Compute pValue """ i=0 pValue=np.arange(float(len(self.interactions))) for interactid in self.interactions: #Take random data ncomp=self.rand_inf.getRandRna(self.softname,self.dbmanage.getsRNAbyIntid(interactid[0])) if(ncomp!=None): if(self.rand_inf.slope[ncomp] and self.rand_inf.intercept[ncomp]): scale=-1.0/self.rand_inf.slope[ncomp] location=self.rand_inf.intercept[ncomp]*scale pValue[i]=1.0-np.exp(-np.exp(-((self.norm_score[i]-location)/scale) )) else: pValue[i]=np.nan else: print("No data for %s with %s"%(self.dbmanage.getsRNAbyIntid(interactid[0]),self.softname)) pValue[i]=np.nan i+=1 #Communication object data=Communication() data.pValue=pValue return data
def run_thread(day, schools): for i in schools: group = one.build_time_pool(day, i) for y in group: locations = one.select_all_addresses(i, day, y) vehicle_data, location_data, driver_indices, passenger_indices, drivers, passengers = one.locations( i, day, y) # potential bug when requests to google distance matrix api are synchronized (DDoS attack) # https://developers.google.com/maps/documentation/distance-matrix/web-service-best-practices#synchronized-requests matrix, time_matrix = createDistanceMatrix.main( one.select_all_addresses(i, day, y)) routes, dropped_nodes, durations = Algorithm.main( vehicle_data, location_data, matrix, time_matrix) routes_temp = copy.deepcopy(routes) urls = url_constructer.construct_route_url(locations, routes_temp) for u in urls: print(u) temp1, temp2 = Json.build_list(urls, routes, dropped_nodes, driver_indices, passenger_indices, drivers, passengers, day, y, durations) filepath, filename = Json.fill_data_matrix(i, day, y, temp1, temp2) Communication.sftp_upload(filepath, filename) sleep(120)
def move_to_cube_old(self, marker): """ Try to move to a marker """ rot = marker.rot_y dist = marker.dist rot, dist2 = self.adjust_angle(rot, dist) direction_turned = math.copysign(90, rot) print("Turning 90 degrees {0}clockwise.".format( "anti" * (direction_turned == -90))) movement.turn(direction_turned) print("Driving...") movement.drive(dist * abs(math.sin(math.radians(rot)))) print("Turning 90 degrees {0}clockwise.".format( "anti" * (direction_turned == 90))) movement.turn(-direction_turned) print("Driving...") movement.drive(dist * math.cos(math.radians(rot)))
def lift_test(self): time.sleep(10) print("Head") movement.liftArms(movement.LIFT_HEAD) time.sleep(10) print("Holding") movement.liftArms(movement.LIFT_HOLDING) time.sleep(10) print("Down") movement.liftArms(movement.LIFT_GROUND) time.sleep(10)
def __init__(self, brain): bot = webdriver.Firefox() self.bot = bot bot.get("https://wx.qq.com/") self.communicationWithOne = Communication.Communication("danger", self) self.brain = brain while (1): ##self.showQRcode() ##if not self.isElementExist("//div[@id='search_bar']"): if not self.is_element_visible( (By.XPATH, "//div[@id='search_bar']")): ### print("請掃描二維碼並點擊確認") time.sleep(1) else: break
def __init__(self, port, baud=57600, password=0x00000000, address=0xffffffff): """ Class to control finger sensor :param port: Communication port :param baud: Communication speed :param password: Sensor password :param address: Sensor address """ self._password = password self._address = address # Open serial port try: self.com = Communication.Communication(port=port, device_address=self._address, baud_rate=baud) except IOError as err: print(err) sys.exit(1)
def getBillDetailsStr(): global gOrderId # Receive Bill billXmlStr = Communication.recvData() bill = Bill() xmlMethods.xmlStr2bill(billXmlStr, bill) # Print Bill PrintMethods.printBillDetails(bill) billStr = ("======================================================" + "\n" " Order Id : " + str(gOrderId) + "\n\n" " Date : " + bill.date + "\n" " Time : " + bill.time + "\n" " Table : " + str(bill.tableNum) + "\n" " Items : " + str(bill.numItems) + "\n" " G Total : $" + str(bill.grandTotal) + "\n") if bill.numItems > 0: billStr = billStr + (" Item 1 :" + "\n" " Name : " + bill.item_1.name + "\n" " Quantity : " + str(bill.item_1.quantity) + "\n" " Price : $" + str(bill.item_1.price) + "\n" " Total : $" + str(bill.item_1.totalPrice) + "\n") if bill.numItems > 1: billStr = billStr + (" Item 1 :" + "\n" " Name : " + bill.item_2.name + "\n" " Quantity : " + str(bill.item_2.quantity) + "\n" " Price : $" + str(bill.item_2.price) + "\n" " Total : $" + str(bill.item_2.totalPrice) + "\n") if bill.numItems > 2: billStr = billStr + (" Item 1 :" + "\n" " Name : " + bill.item_3.name + "\n" " Quantity : " + str(bill.item_3.quantity) + "\n" " Price : $" + str(bill.item_3.price) + "\n" " Total : $" + str(bill.item_3.totalPrice) + "\n") billStr = billStr + "======================================================" return billStr
self.modechanging = 0 vid = self.main_frame(cap) vid = self.contour_goal_detection(vid) print "Mode 2 :" if self.log == 1: self.display_video(vid, vid) key = cv2.waitKey(100) & 0xFF if key == 27: break if __name__ == "__main__": run_event = threading.Event() run_event.set() communication = Communication() communication.connect() # ------------------------------------------------------ # Run the referee main = Main(0, "Main", communication, run_event) # ------------------------------------------------------ # Run the referee referee = Referee(1, "Referee", "B", "B", main, run_event) referee.connect() main.start() referee.start() try: while 1:
def getSendCom(self,computer,type_analysis,tab,dbmanage,rand_inf): """ Create communication object """ data=Communication() data.type_analysis=type_analysis if(type_analysis==0): data.interactions=computer.interactions[tab[0]:tab[1]] data.type_sol=computer.type_sol data.score_type=computer.score_type elif(type_analysis==1 or type_analysis==3): data.interactions=computer.interactions[tab[0]:tab[1]] data.type_sol=computer.type_sol #Matrice partielle data.pos=computer.pos[tab[0]:tab[1]] elif(type_analysis==2): data.softname=self.getCorrespondingSoft(computer,dbmanage,rand_inf) data.norm_score=computer.norm_score[tab[0]:tab[1]] data.interactions=computer.interactions[tab[0]:tab[1]] #regression elif(type_analysis==4): data.unique_sRNAidinint=computer.unique_sRNAidinint[tab[0]:tab[1]] data.norm_score=computer.norm_score data.sRNAid_tab=computer.sRNAid_tab data.pValue_type=computer.pValue_type else: raise NotImplementedError("") return data