def stockerPiece(self): print("[-->] On veut stocker") # Vérification if self.traite == True: # Stockage dans l'entrepôt print("[-->] On stocke") Message.send("fileEntrepot",self.nom,self.resultatCourant)
def test_messages_to_python_with_json_message(self): message_count = 3 # JSON formatted message NOT created by celery q = self.channel._new_queue(self.queue_name) message = '{"foo":"bar"}' for i in range(message_count): m = Message() m.set_body(message) q.write(m) # Get the messages now messages = q.get_messages(num_messages=message_count) # Now convert them to payloads payloads = self.channel._messages_to_python( messages, self.queue_name, ) # We got the same number of payloads back, right? self.assertEquals(len(payloads), message_count) # Make sure they're payload-style objects, and body is the same for p in payloads: self.assertTrue('properties' in p) self.assertEqual(p['body'], message)
def openProcessWithTitleCheck(processName, title, message, args): if isWindowExist(title): os.popen("wmctrl -R '" + title + "'") else: if Message != "": Message.hint(message) subprocess.Popen([processName, args])
def send_msg(self, target, data): """ Sends a message to a computer @target: The ip address of the computer we are sending the message to. This should be a string @data: The data we are sending, usually the string representation of JSON. """ # Get IP Address to populate message sender field my_addr = NetworkUtilities.get_my_ip() # Create a new message object msg = Message(my_addr, target, data) msg = msg.get_json() # Create a new connection to the server s = socket(AF_INET, SOCK_STREAM) s.connect((self.host, self.port)) s.send(msg) # Get response from server response = s.recv(512) print "Response from server : " + response s.close()
def envoyerPiece(self): numeroMachine = random.randint(0,1); if numeroMachine == 0: typeMachine = "mA" else: typeMachine = "mB" #print("fileMachine ; "+typeMachine+" ; "+self.type) Message.send("fileMachine",typeMachine,self.type)
def Accept( q, socket, port, id ): conn, addr = socket.accept() message = Message.fromRaw( conn.recv(1024) ) if message.type == MessageType.AUTH: response = Message( MessageType.CONNECT, { "port" : port, "id" : id, "name" : message.get("name") } ) q.put( response ) conn.send( response.raw() ) conn.close()
def openProcess(processName, title, message, argument): if getPid(processName) == "": command = processName + " " + argument subprocess.Popen(processName) # subprocess.call(command, shell=True) # subprocess.Popen([processName, argument], creationflags=DETACHED_PROCESS) if Message != "": Message.hint(message) else: os.popen("wmctrl -R '" + title + "'")
def OnBeforeRemove(self, arg, extra): idx = extra["idx"] takeData = Archive("Take").getValues(idx, "Parent4,CreateBy,Name") if takeData["CreateBy"] != session["UserID"]: msg = u"[%s] : 작업물이 삭제되었습니다." % takeData["Name"] # 컨퍼머 한테도 가도록 Message.sendMessage(takeData["CreateBy"], msg, "<a href='/task/view/%d'>%s</a>" % (takeData["Parent4"], msg) ) deleteChildren( idx ) return arg
def broadcast(self, message_text): #, pos, neg): if self.producer is None: print "Cannot send because self.producer is None" return False m = Message("twitter-volume", message_text) #m.add_field("pos_sent", str(pos)) #m.add_field("neg_sent", str(neg)) if self.producer.send(m.str()): print "[%d] Transmission successful" % m.get_time() else: print "[%d] Transmission failed" % m.get_time()
def display_start_tournament(msg): """ :param msg: message to be displayed """ indent_cushion() print(' Tournament Start! ') indent_cushion() m = Message.get_players(msg) print('\nPlayers: ' + m) #assuming for the time being that info will hold the specified game m = Message.get_info(msg) print('\nGame: ' + m)
def processusMachine(nom, listePiecesTraitables, listeAutresMachines, nb): print("LISTE DES MESSAGES INITIALE") Message.afficherListeMessages() machine = Machine(nom, listePiecesTraitables, listeAutresMachines) i = 0 while i<nb: machine.fonctionner() i = i + 1 print(" "); print("LISTE DES MESSAGES FINALE") Message.afficherListeMessages() #processusMachine("mA",["pA", "pB"],["mB"])
def _sendRelayMessage(self, sender, receivedMessageBody, RecipientJidHandleGroups): messageBody = self._MessageBuilder.getRelayMessageBody( sender, receivedMessageBody) RelayMessage = Message.Message(RecipientJidHandleGroups, messageBody) self._ItBot.sendMessage(RelayMessage)
def subscribe(self, topics=None): """Subscribe to topic(s)""" # check if ACKed if not self.connack_rec: return 1 # if no topics, exit if topics == None: return 1 # check if topic is list or string if isinstance(topics, list): # check if we're already subscribed to any of the requested topics for topic in topics: if topic in self.topics: # remove from req if we are subbed already topics.remove(topic) elif isinstance(topics, str): # don't sub if already subbed if topics in self.topics: return topics = [topics] # store the request self.sub_req = topics # compose message msg = {"header": "SUB", "topics": topics} # create frame frame = Message.SubscribeFrame(json.dumps(msg)) # send frame self.send_q.put(frame.encode())
def Error(self, Type): import Message self.window = QtWidgets.QDialog() self.ui = Message.Ui_Message() self.ui.setupUi(self.window, Type) self.window.show()
def queueInput(self, client): _input = '' while 1: try: _input = client.recvfrom(1024) # Stage 1 (Decrypt) _input = cryptography.DecodeAES(_input) if _input == None: raise socket.error(9) # Stage 2 (Check Delim) if hashlib.sha384(_input[0:self.DELIMLENGTH]).hexdigest( ) == self.delim: # delim equals if _input[self.DELIMLENGTH:]: request = Message.Message(_input[self.DELIMLENGTH:], client.getClearance(), 5) client.addRequest(request) else: pass else: client.sendto('You are unauthorized. Connection aborted.' ) # INTRUDER ALERT client.close() break except socket.error as msg: if msg[0] in [10053, 10054, 9]: # if socket error raised print 'Client %s has disconnected.' % (client.getAddr()) client.close() break self.delClient(client) client.updateLife(False)
def buildModelFromMessageScanResponseDto(self, messageScanDto, conversationKey) : errorList = messageScanDto['errorList'] soup = SoupUtil.getSoupFromHtml(messageScanDto['html']) ownerInfo = SoupUtil.getText( SoupUtil.getValue( SoupUtil.findByPartialAttributeValue(soup, 'div', 'class', 'copyable-text'), 'data-pre-plain-text' ) ) ownerKey = ownerInfo.split(']')[-1].strip() ownerKey = ownerKey if not ownerKey.endswith(':') else ownerKey[:-1] now = DateTimeHelper.dateTimeNow() postedAt = ownerInfo.split(']')[0].split('[')[-1].strip().split() postedAt = f'{StringHelper.join(postedAt[-1].split("/")[::-1], character="-")} {postedAt[0]}:{str(now).split(":")[-1]}' return Message.Message( key = messageScanDto['key'], conversationKey = conversationKey, ownerKey = ownerKey, postedAt = postedAt, ownerInfo = ownerInfo, scannedAt = now, text = SoupUtil.getText(SoupUtil.findByPartialAttributeValue(soup, 'span', 'class', 'selectable-text copyable-text')), originalAsText = SoupUtil.getText(soup), originalAsHtml = messageScanDto['html'], isPoolerMessage = 'message-out' in SoupUtil.getValue(SoupUtil.findTag(soup, 'div'), 'class'), poolingStatus = PoolingStatus.SUCCESS, errorCount = len(errorList), errorListAsJson = Serializer.jsonifyIt(errorList) )
def SendMessage(self, msgKind, Params): m = Message.Message() m.Id = self.Id m.Order = msgKind m.Params = Params str = m.Serialize() self.Send(str)
def btnSearch_pushed(self): #Clearing the list self.searchList.clear() #Retrieving all visitors from the database visitors = g_database.GetAllEntries() #Converting the users entry to text term = self.searchTerm.text() #converting the term to lower to allow for user input error term = term.lower() termFound = False for visitor in visitors: #Obtaing the surname from the database surname = visitor[2] #converting the surname to lower to allow for user input error surname = surname.lower() #Checking the search term matches the term in the database and the visitor isnt signed out if term == surname and visitor[7] == "N/A": #Creating a full name name = "" #Adding the forename and a space to the string name= name + (visitor[1]) + " " #Adding a surname name = name + (visitor[2]) #Adding the full name to the list self.searchList.addItem(name) termFound = True #If the term isnt found if termFound == False: #Calling the error window, passing in the message to display self.message=Message(self,"No entries found, please search again") #Showing the window self.message.show() #Raising the window the front of the screen self.message.raise_()
def send_initial_messages(self): #TODO: This function needs to create and send the initial messages from this switch. # Messages are sent via the superclass method send_message(Message msg) - see Message.py. # Use self.send_message(msg) to send this. DO NOT use self.topology.send_message(msg) for neighbor in self.links: self.send_message( Message(self.switchID, 0, self.switchID, neighbor, False))
def send_initial_messages(self): for linkID in self.links: # Message(root, distance, origin, destination, pathThrough) message = Message(self.switchID, 0, self.switchID, linkID, False) self.send_message(message) return
def receive_message(self): global public_keys #it will receive all kinds of messages and will display the results to the user while True: input_message,addr=self.sock.recvfrom(1024) user=self.resolve_ip_port(addr) # TODO # decryption input_message=Message.UnMessage_no_encryption(input_message) if input_message.get_type() == Message.LIST: user_to_delete=input_message.get_message() self.delete_user(user_to_delete) #threading.Thread(target=self.user_to_ips).start() have to call this in srp elif input_message.get_type() == Message.MESSAGE: print "<"+user+" sent a message at "+input_message.get_time()+"> "+input_message.get_message() elif input_message.get_type() == Message.ESTAB_KEY: try: threading.Thread(target=self.tcp_establish_key_sender,args=(addr[0],input_message.get_message(),input_message.get_username())).start() except Exception as e: print 'Error while creating threads :', e elif input_message.get_type() == Message.PUB_KEY: public_keys[input_message.get_username()]= input_message.get_message()['pub_key'] elif input_message.get_type() == Message.UPDATE_LIST: self.online_users = input_message.msg self.online_users['server_9090'] = ['127.0.0.1', 9090] else: print "Message received in an unknown format"
def main(arguments): messager = Message.Messager() delay = float(sys.argv[1]) fault_delay = float(sys.argv[2]) current_delay = delay lastIp = getIp() if lastIp != None: logger.info('Got IP of %s' % (lastIp)) else: logger.info("Decreasing delay until connection is successful") current_delay = fault_delay while True: logger.info('Checking for IP again in %s hours' % (current_delay)) time.sleep(current_delay*3600) currentIp = getIp() if currentIp == None: # decrease the delay if wifi has cut out logger.info("Decreasing delay until connection is successful") current_delay = fault_delay # check for error on requests.. should only execute if wifi is up or requests were good. if lastIp != None and currentIp != None: if lastIp != currentIp: logger.info("IP change detected (%s --> %s). Sending update text." % (lastIp, currentIp)) messager.createSMS("Your ext. IP has changed from %s to --> %s." % (lastIp, currentIp)) else: logger.info("No change in IP.. Last ext. Ip was: %s, current is: %s." % (lastIp, currentIp)) lastIp = currentIp current_delay = delay if lastIp == None and currentIp != None: # update lastIp if none type on initial request lastIp = currentIp
def open_private(self, instance): self.popup = Popup(title="Private Lobby") self.popup.size = (40, 40) content = GridLayout() self.popup.content = content content.cols = 2 content.rows = 3 content.padding = 100 self.name_input = TextInput(multiline=False) self.name_label = Label(text="Name:") content.add_widget(self.name_label) content.add_widget(self.name_input) self.room_id_input = TextInput(multiline=False) self.room_label = Label(text="Room Code:") content.add_widget(self.room_label) content.add_widget(self.room_id_input) content.add_widget(Button(text="Back", on_press=self.popup.dismiss)) # send name and room id to server to join lobby content.add_widget( Button(text="Join Private Lobby", on_press=lambda event: send_msg( self.client_socket, Message(TAG='LOBBYREQUEST', name=self.name_input.text, roomid=self.room_id_input.text)))) self.popup.open()
def menuItemClicked(self, menuItemCaption, selectedMessages): self.hiccup.reload_on_change() self.logger.debug("menuItemClicked : %s" % menuItemCaption) messages = [] for messageInfo in selectedMessages: messageReference = '~' remoteHost = messageInfo.getHost() remotePort = messageInfo.getPort() serviceIsHttps = True if messageInfo.getProtocol( ) == 'https' else False httpMethod = '' url = '%s://%s%s' % (messageInfo.getUrl().getProtocol(), messageInfo.getUrl().getHost(), messageInfo.getUrl().getPath()) self.logger.debug("menuItemClicked() : %s [%s] %s" % (messageInfo, messageReference, url)) resourceType = '' responseContentType = '' interceptAction = [ '', ] #deal with request messages.append( Message.Message(self.global_config, 'clicked', messageReference, True, remoteHost, remotePort, serviceIsHttps, httpMethod, url, resourceType, '', responseContentType, messageInfo.getRequest(), interceptAction, messageInfo)) #and response messages.append( Message.Message(self.global_config, 'clicked', messageReference, False, remoteHost, remotePort, serviceIsHttps, httpMethod, url, resourceType, messageInfo.getStatusCode(), responseContentType, messageInfo.getResponse(), interceptAction, messageInfo)) self.plugin_manager.process_menuitem_click(menuItemCaption, messages) for message in messages: if message.is_highlighted(): self.logger.debug("need to update highlight for msg : %s" % message) message['messageinfo'].setHighlight(message.get_highlight()) if message.is_commented(): self.logger.debug("need to update comment for msg : %s" % message) message['messageinfo'].setComment(message.get_comment())
def send_initial_messages(self): #TODO: This function needs to create and send the initial messages from this switch. # Messages are sent via the superclass method send_message(Message msg) - see Message.py. # Use self.send_message(msg) to send this. DO NOT use self.topology.send_message(msg) for link in self.links: msg = Message(self.root, 0, self.root, link, False) self.send_message(msg) return
def broadcast(self): contenth = 'holes-' contenth += np.array2string(self.holes_depth, separator=',') contentt = 'tiles-' contentt += np.array2string(self.tiles_no, separator=',') contenta = 'agents-' contenta += str(self.agent_pos) for agent in self.agents: msg = Message('environment', agent, contenth, Message.BROADCAST, 'broadcast') self.sent.put(msg) msg = Message('environment', agent, contentt, Message.BROADCAST, 'broadcast') self.sent.put(msg) msg = Message('environment', agent, contenta, Message.BROADCAST, 'broadcast') self.sent.put(msg)
def handleMessage(rawMsg): recvJson = json.loads(rawMsg) recvMsg = Message(requestID=recvJson["request-id"], senderAddress=recvJson["sender"], instruction=recvJson["instruction"], sudoku=parseSudoku(recvJson["sudoku"])) if recvMsg.instruction == "ping": print("PING") recvMsg.instruction = "pong" myBridge.send(recvMsg) print("PONG") elif recvMsg.instruction.startswith("solved"): print("SOLVED") myHandler.handle(recvMsg) elif recvMsg.instruction.startswith("generate"): print("GENERATE") myHandler.handle(recvMsg) else: print(recvMsg.instruction)
def bond_node_feat(graph, node): # return bond types bonds = node.GetBondNeighbors() nf = Message.Vector(len(graph.atoms), "", 0, "", node) for b in bonds: if b.source == node: nf.max( Message.Vector(len(graph.atoms), "", b.target.id - 1, str(b.type), b.target)) elif b.target == node: nf.max( Message.Vector(len(graph.atoms), "", b.source.id - 1, str(b.type), b.source)) return nf
def OnBeforeRemove(self, arg, extra): idx = extra["idx"] # 알림 처리 r1 = self.getValues(idx, "Name,Parent3,AssignUser") tName = r1["Name"] aUser = r1["AssignUser"] shotidx = r1["Parent3"] if (aUser): msg = u"[%s] : 배정 되었던 작업이 삭제 되었습니다." % (tName) Message.sendMessage(aUser, msg, "<a href='/shot/view/%d'>%s</a>" % (shotidx,msg) ) deleteChildren( idx ) return arg
def send_initial_messages(self): # Messages are sent via the superclass method send_message(Message msg) for neighbor in self.links: msg = Message(self.switchID, 0, self.switchID, neighbor, False) self.send_message(msg) return
def _sendConfirmationMessage(self, sender): confirmationMessageBody = self._MessageBuilder.getImmediateSenderConfirmationMessageBody( ) ConfirmationMessage = Message.Message( [JidHandleGroup([JidHandle.JidHandle('', sender)])], confirmationMessageBody) self._ItBot.sendMessage(ConfirmationMessage)
def OnAfterModify(self, arg, extra): idx = extra["idx"] gOut = arg["_out_"] diffData = gOut["diffData"] taskData = gOut["taskData"] sName = taskData["Shot.Name"] tName = taskData["Name"] # 배정에서 변경이 이루어짐 if "AssignUser" in diffData and type(diffData["AssignUser"]) is tuple: assignUser = diffData["AssignUser"] #ex. (None,id) # 신규 배정 if (assignUser[0] == None) and (assignUser[1] != None): # 메세지 발송 msg = u"[%s/%s] : %s님에 의해 작업에 배정되었습니다." % (sName, tName, session["UserName"]) Message.sendMessage(assignUser[1], msg, "<a href='/task/view/%s'>%s</a>" % (idx,msg) ) # 배정 해제 elif (assignUser[0] != None) and (assignUser[1] == None): # 메세지 발송 msg = u"[%s/%s] : %s님에 의해 작업배정이 해제되었습니다." % (sName, tName, session["UserName"]) Message.sendMessage(assignUser[1], msg, "<a href='/task/view/%s'>%s</a>" % (idx,msg) ) # 배정자 교체 elif (assignUser[0] != None) and (assignUser[1] != None): # 메세지 발송, 둘다 msg = u"[%s/%s] : %s(%s)님으로 작업배정자가 변경되었습니다." % (sName, tName, arg["AssignUser"], arg["AssignUser2"] ) Message.sendMessage(assignUser[0], msg, "<a href='/task/view/%s'>%s</a>" % (idx,msg) ) msg = u"[%s/%s] : %s님의 작업배정이 %s님으로 변경되었습니다." % (sName, tName, assignUser[0], assignUser[1]) Message.sendMessage(assignUser[1], msg, "<a href='/task/view/%s'>%s</a>" % (idx,msg) ) #알수 없는 상황! else: pass # 그외 변경 알림 # 히스토리 기록 # 이게 오케이가 되면 자동으로 연결된 다른 애가 자동시작? -> 일단 대기 # 시퀀스 변경시 새로운 시퀀스 리카운팅 및 작업 변경 ---------------- if "Parent2" in arg: newSeq = arg["Parent2"] # 하위 연계 변경 처리 ------------------------------------ RDB = Archive("Take").Search(columns="Take.IDX", where="Take.Parent4 == %s" %(idx) ) if (RDB[0] > 0): for row in RDB[1]: idx = str(row["Take_IDX"]) Archive("Take").Edit( idx, Parent2=newSeq ) return arg
def process_message(self, message): # if they go through you add them to your active links if message.pathThrough: if message.origin not in self.activeLinks: self.activeLinks.append(message.origin) # if they don't go through you and you don't go through them delete them from your active links elif message.pathThrough == False and message.origin != self.pathThrough and message.origin in self.activeLinks: self.activeLinks.remove(message.origin) # if the message has a new root if message.root < self.root: self.root = message.root self.distance = message.distance + 1 self.pathThrough = message.origin if self.pathThrough not in self.activeLinks: self.activeLinks.append(self.pathThrough) for linkID in self.links: message = Message(self.root, self.distance, self.switchID, linkID, self.pathThrough == linkID) self.send_message(message) # if the message has the same root but a shorter distance if message.root == self.root and message.distance + 1 < self.distance: self.distance = message.distance + 1 newPathThrough = message.origin for linkID in self.links: message = Message(self.root, self.distance, self.switchID, linkID, newPathThrough == linkID) self.send_message(message) self.activeLinks.remove(self.pathThrough) self.pathThrough = newPathThrough if newPathThrough not in self.activeLinks: self.activeLinks.append(newPathThrough) # message has the same root and same distance but the sender has a smaller switchID than current path if message.root == self.root and message.distance + 1 == self.distance and self.pathThrough > message.origin: newPathThrough = message.origin for linkID in self.links: message = Message(self.root, self.distance, self.switchID, linkID, newPathThrough == linkID) self.send_message(message) self.activeLinks.remove(self.pathThrough) self.pathThrough = newPathThrough if newPathThrough not in self.activeLinks: self.activeLinks.append(newPathThrough) return
def maketurn(self, turn): # print(str(turn[0])+" "+str(turn[1])) print(str(self.board.board[turn[0]][turn[1]].color)) if (self.board.board[turn[0]][turn[1]].selected): return self.server.select(self.room, turn[0], turn[1]) #self.board.board[][].selected = True winner = None if (self.board.board[turn[0]][turn[1]].color == -2): winner = ((self.board.turn + 1) % 2) Win = True for i in range(self.board.dim): for j in range(self.board.dim): if (self.board.board[i][j].selected == False and self.board.board[i][j].color == self.client.team): Win = False break if (Win): winner = self.client.team if (self.board.board[turn[0]][turn[1]].color != self.client.team): self.server.turn(self.room) codemaster_name = "" for recipient in self.client_list: recipient.boardClone.turn = (recipient.boardClone.turn + 1) % 2 if recipient.client.is_codemaster and recipient.client.team != self.client.team: recipient.clued = False codemaster_name = recipient.client.username msg = Message(TAG="PROMPTCLUE", board=self.boardClone.turn, text_message=codemaster_name) self.broadcast(msg, False) self.boardClone.board[turn[0]][turn[1]].color = self.board.board[ turn[0]][turn[1]].color self.boardClone.board[turn[0]][turn[1]].selected = True msg = Message(TAG="BOARDUPDATE", board=self.boardClone, text_message=winner) self.broadcast(msg, False) if (winner != None): for c in self.client_list: c.leave()
def send_initial_messages(self): # 1. for loop over self.links # 2. create datagram # 3. send_message call for neighbor in self.links: datagram = Message(self.switchID, 0, self.switchID, neighbor) #print datagram #print "\n%d sent a datagram to %d" % (self.switchID, neighbor) self.topology.send_message(datagram)
def lookup(self): s = socket.socket() conn = self.dc_list[self.dc_Id] msg = Message('Lookup', None) send = pickle.dumps(msg,0) s.connect(conn) s.send(send) rcv = s.recv(4096) msg= pickle.loads(rcv) log=msg.getPayload() print("Local datacenter: ") log.displayPosts() s.close()
def send_initial_messages(self): #TODO: This function needs to create and send the initial messages from this switch. # Messages are sent via the superclass method send_message(Message msg) - see Message.py. # Use self.send_message(msg) to send this. DO NOT use self.topology.send_message(msg) for ID in self.links: msg = Message(self.switchID, self.distance, self.switchID, ID, self.pathThrough) self.send_message(msg) return
def on_pushButton_clicked_4(self): print '4' # 初始化回传数据变量 # 还需要初始化布局 self.freq_list = [] self.bins = [] # 指令生成和发送 freq_start = self.lineEdit.text() + 'e6' freq_end = self.lineEdit_2.text() + 'e6' point_num = self.lineEdit_4.text() if not (freq_start.isEmpty() or freq_end.isEmpty() or point_num.isEmpty()): self.scan_recv = scan_thread.Recv(self.q, self.sub_socket) self.scan_send = scan_thread.Send(freq_start, freq_end, point_num, self.pub_socket) self.scan_recv.start() self.scan_send.run() loading = Message.Loading(self.q) loading.setWindowModality(Qt.ApplicationModal) loading.show() gui = QApplication.processEvents # self.loading.setWindowModality(Qt.ApplicationModal) while self.q.empty(): gui() else: print self.q.qsize() self.bins = self.q.get() print "self.bins type", type(self.bins) if self.bins == "HeSaidStop": loading.close() self.scan_recv.terminate() else: # 回传接收、绘图 loading.close() self.freq_list = self.q.get() self.bins = [c - 11 for c in self.bins] # ratio = int(point_num)/len(self.freq_list) # self.freq_list = self.down_sample(self.freq_list, ratio) # self.bins = self.down_sample(self.bins, ratio) print len(self.bins) print len(self.freq_list) #####置入绘图#### if self.picFlag: self.verticalLayout.removeWidget(self.getPosition) sip.delete(self.getPosition) self.getPosition = getPos.getPos( self.freq_list, self.bins, self.picQ) self.verticalLayout.addWidget(self.getPosition) self.picFlag = 1 else: self.getPosition = getPos.getPos( self.freq_list, self.bins, self.picQ) self.verticalLayout.addWidget(self.getPosition) self.picFlag = 1 else: QMessageBox.warning(self, _fromUtf8('错误'), _fromUtf8("请输入正确参数!"), QMessageBox.Yes)
def lookup(self): s = socket.socket() conn = self.dc_list[self.dc_Id] msg = Message('Lookup', None) send = pickle.dumps(msg, 0) s.connect(conn) s.send(send) rcv = s.recv(4096) msg = pickle.loads(rcv) log = msg.getPayload() print("Local datacenter: ") log.displayPosts() s.close()
def handleCalculation(self): while True: print '\nWe have not coded any options to handle calculations' response = Message.getResponse( '\nEnter 1 to perform another action with this calculation. \nEnter anything else to get go back to the beginning. \n' ) if response == 1: continue break
def send_initial_messages(self): #TODO: This function needs to create and send the initial messages from this switch. # Messages are sent via the superclass method send_message(Message msg) - see Message.py. # Use self.send_message(msg) to send this. DO NOT use self.topology.send_message(msg) for neighborID in self.neighbors: message = Message(self.root, self.distance, self.switchID, neighborID, False) self.send_message(message) return
def run(self): while not self.event.is_set(): try: self.s.connect(('localhost', 55000)) while 1: m = Message.Message(raw_input("message:")) self.s.send(pickle.dumps(m)) except socket.error: time.sleep(1)
def __init__(self, ID): self.ID = ID self.messager = Message.MessageConstructor(self.ID) self.StopRequest = False self.solution = 600 self.con = Connectivity.Connectivity(self) self.status = "Online" self.currentValue = "" self.publishingChannel = "puzzles/" + self.ID + "/values"
def stop(self): for agent in self.agents: msg = Message('environment', 'agent', 'stop', Message.INFORM, f'stop-{agent}') self.sent.put(msg) print("[ENV] Stopped") self.done.value = 1 while True: time.sleep(10000)
def __and_message_builder_returns_a_requester_confirmation_message(self): expectedMessageBody = "Your message was received and is being looked at by" with Spy() as MessageBuilder: MessageBuilder.getRequestConfirmedMessageBody( any()) >> expectedMessageBody self.__MessageBuilder = MessageBuilder self.__ExpectedMessage = Message.Message( self.__ExpectedJidHandleGroups, expectedMessageBody)
def Network_startgame(self, data): player_character = data['character'] player_cards = data['cards'] success,cards = Message.create_message("start") print "player_cards: ", player_cards print "start success?: ", success if success: connection.Send({"action":"success","ID":self.gameid}) else: connection.Send({"action":"fail","ID":self.gameid})
def OnAfterInsert_TakeReply(self, arg, extra): idx = extra["idx"] pidx = arg["ParentIDX"] takeData = Archive("Take").getValues(pidx, "CreateBy,Name") linkto = "/take/view/%s" % (pidx) if takeData["CreateBy"] != arg["CreateBy"]: msg = u"[%s] : 작업물에 피드백이 작성되었습니다." % takeData["Name"] Message.sendMessage(takeData["CreateBy"], msg, "<a href='/take/view/%s'>%s</a>" % ( pidx, msg) ) else: msg = u"[%s] : 피드백에 대한 회신이 작성되었습니다." % takeData["Name"] sQuery = "Select distinct CreateBy From TakeReply where ParentIDX = :pidx and CreateBy != :wid" wUsers = [r[0] for r in Archive.RunQuery(sQuery, pidx=pidx, wid=arg["CreateBy"])] for user1 in wUsers: Message.sendMessage(user1, msg, "<a href='/take/view/%d'>%s</a>" % (pidx, msg) ) return arg
def display_start_match(msg): """ :param msg: message to be displayed """ indent_cushion() print(' Match Start! ') indent_cushion() m = Message.get_players(msg) print('\nPlayers: ' + m)
def lookupLog(self): s = socket.socket() dcNum = input("Enter datacenter number: ") dcNum=int(dcNum) conn = self.dc_list[dcNum] msg = Message('LookupLog', None) send = pickle.dumps(msg,0) s.connect(conn) s.send(send) rcv = s.recv(4096) msg= pickle.loads(rcv) log=msg.getPayload() print("Datacenter: "+str(dcNum)) log.display() s.close()
def updateTargets(self, timestamp): # send request to HMINT for targets available as of self.localTime print 'CAOC: Sending target request for time %d to HMINT' % timestamp sys.stdout.flush() requestData = TargetRequest(timestamp) msg = Message(4, requestData, LogicalProcess.CAOC_ID, LogicalProcess.HMINT_ID, timestamp) self.sendMessage(msg) # wait for response responseData = None while True: print 'CAOC: Waiting for target response from HMINT' sys.stdout.flush() time.sleep(1) if(self.Loopcont.getCon()==0): break msgs = self.inputQueue.getAllMessages() for msg in msgs: msg.printData(1) if msg.msgType == 5: print 'CAOC: Received target response for time %d from HMINT' % self.localTime sys.stdout.flush() responseData = msg.data self.inputQueue.removeByID(msg.id) if msg.color == LPGVTData.WHITE: self.gvtData.counts[self.LPID] -= 1 if(debug==1): print 'LP %d recvd WHITE msg, rcvd count is now %d' % (self.LPID, self.gvtData.counts[self.LPID]) break if not(responseData is None): break # add targets if(self.Loopcont.getCon()==0): return for target in responseData.targetData: print 'CAOC: Adding target to priority queue:', target self.addTarget(target) sys.stdout.flush()
def resp_username_taken(self, msg): resp = Message() resp.response = 'login' resp.error = 'Name already taken!' resp.username = msg.username resp.serialize() self.connection.sendall(resp)
def resp_username_illegal(self, msg): resp = Message() resp.response = 'login' resp.error = 'Invalid username!' resp.username = msg.username resp.serialize() self.connection.sendall(resp)
def handle(self): # Get a reference to the socket object self.connection = self.request # Get the remote ip adress of the socket self.ip = self.client_address[0] # Get the remote port number of the socket self.port = self.client_address[1] print 'Client connected @' + self.ip + ':' + str(self.port) while 1: # Wait for data from the client data = self.connection.recv(1024).strip() # Check if the data exists # (recv could have returned due to a disconnect) if data: msg = Message() msg.parse(data) handle_request(msg) else: lock.acquire() self.server.remove_client(self, self.nickname) lock.release() print 'Client disconnected!'
def OnAfterModify(self, arg, extra): #[TODO] 최종 변경자 적용 idx = extra["idx"] # 테이크 승인시 알림 처리 if "StatCode" in arg: takeData = self.getValues(idx, "Take_Stat.Name,StatCode,Parent4,Name,CreateBy,Shot.Name") statName = takeData["Take_Stat.Name"] takeName = takeData["Name"] creUser = takeData["CreateBy"] shotName = takeData["Shot.Name"] msg = u"[%s/%s] : 작업물이 <b>%s</b> 상태로 변경 되었습니다." % (shotName, takeName, statName) Message.sendMessage(creUser, msg, "<a href='/take/view/%s'>%s</a>" % (idx, msg) ) # 연차적 상태변환 if takeData["StatCode"] == "OK": dSave = {"IDX" : takeData["Parent4"], "StatCode" : "DON"} Archive("Task").New(**dSave) return arg
def display_end_tournament(msg): """ :param msg: message to be displayed """ indent_cushion() print(' Tournament End! ') indent_cushion() #assuming for the time being that info will hold the winner of the tournament m = Message.get_info(msg) print('\nWinner: ' + m) indent_cushion() indent_cushion() print('\n') indent_cushion() indent_cushion()
def resp_login_success(self, msg): self.username = msg.username #update the servers list of clients lock.acquire() self.server.add_client(self, self.username) history = self.server.get_messages() lock.release() #send response to client resp = Message() resp.response = 'login' resp.username = msg.username resp.messages = history resp.serialize() self.connection.sendall(resp)
def display_end_match(msg): """ :param msg: message to be displayed """ indent_cushion() print(' Match End! ') indent_cushion() m = Message.get_info(msg) #r is the winner #winnings is the number of times that r won if m[1] > m[2]: #player 1 won r = 'Player 1 ' winnings = m[1] else: #player 2 won r = 'Player 2 ' winnings = m[2] print('Winner: ' + r + '( ' + winnings + ' out of ' + (m[1] + m[2]) + ')')
def display_end_round(msg): """ :param msg: message to be displayed """ print('\nRound Results: ') m = Message.get_info(msg) #r is the winner of the round if m[2] == 0: r = 'Tied' elif m[2] == 1: #player 1 won r = 'Player 1 ' elif m[2] == 1: #player 2 won r = 'Player 2 ' print('Winner: ' + r) #find the moves that were played during this round moves = m[1] a = get_move(moves[1]) b = get_move(moves[2]) print(' Moves made: Player 1: ' + a + ' Player 2: ' + b)
def testHandleMessage(self, msg): # determine message type and process accordingly if msg.msgType==1: # TBD pass elif msg.msgType==2: # Start the add target process with the target data of the message self.testAddTarget(msg.data) elif msg.msgType==3: # Update drone status list self.drones[msg.data[0]]=[msg.data[1],msg.data[2]] # Check which target assignment heruristic is in use if self.heuristic==1: # If the drone is idle and there are target assignments in the queue, assign that drone a target if (self.drones[msg.data[0]][0]=="Idle") and (len(self.priorityQueue)!=0): newTgtData=self.priorityQueue.pop() newTgtMsg=Message(2,newTgtData,self.id,msg.data[0],self.localTime) #self.sendMessage(newTgtMsg) if(debug==1): print 'CAOC sending message: ' newTgtMsg.printData(1) self.drones[msg.data[0]][0]="Busy" # Check which target assignment heruristic is in use elif self.heuristic==2 or self.heuristic==3: # If the drone is idle and there are target assignments in the queue, assign that drone the nearest target if (self.drones[msg.data[0]][0]=="Idle") and (len(self.priorityQueue)!=0): droneLocation=self.drones[msg.data[0]][1] #x,y coords droneX=self.drones[msg.data[0]][1].xpos droneY=self.drones[msg.data[0]][1].ypos indexCloseTgt=0 minDist=999999 for i in range(len(self.priorityQueue)): tgtX=self.priorityQueue[i][6].xpos #x coord tgtY=self.priorityQueue[i][6].ypos #y coord dist=sqrt((tgtX-droneX)**2+(tgtY-droneY)**2) if dist<minDist: minDist=dist indexCloseTgt=i newTgtData=self.priorityQueue.pop(indexCloseTgt) newTgtMsg=Message(2,newTgtData,self.id,msg.data[0],self.localTime) #self.sendMessage(newTgtMsg) if(debug==1): print 'CAOC sending message: ' newTgtMsg.printData(1) self.drones[msg.data[0]][0]="Busy"
def findRoot(serviceGmail, serviceUser): # Edited by FH: uses the user root = [] user = "******" # Use the user who authorized the call userData = serviceUser.people().get(userId='me').execute() query = 'in:sent' try: userEmail = userData['emails'][0]['value'] root.append(userEmail) query = 'in:sent' + ' -' + userEmail except: pass # max maxResults = 10 # response = Message.ListMessagesMatchingQuery(service, user, query) response = serviceGmail.users().messages().list(userId=user, q=query, maxResults=1).execute() numberOfMessages = response['resultSizeEstimate'] while numberOfMessages: messageID = response['messages'][0]['id'] # extract the vFrom msg = Message.GetMessage(serviceGmail, user, messageID) for i in range(len(msg['payload']['headers'])): name = msg['payload']['headers'][i]['name'] value = msg['payload']['headers'][i]['value'] if name == 'From': vFrom = Message.extractEmails(value) if vFrom[0] not in root: root.append(vFrom[0]) print root query = query + ' -' + vFrom[0] response = serviceGmail.users().messages().list(userId=user, q=query).execute() numberOfMessages = response['resultSizeEstimate'] return root