def verifyNum(): try: errorlabel.place_forget() key = decompress(fiveDigit.get()) '''if len(key) != 5: #MUST BE FIVE # Supported @ compression raise TypeError key = int(key) hostname = unencrypt(key)''' try: global conObject conObject = Client(key) #key and onDisconnect conObject.favdir = favdir conObject.PROGCLASS = ProgHandler #c.onDisconnect = handleDC conObject.start() #c.onProgress = updateProgress; except Exception as ex: pr("Couldn't start client: "+str(ex)) errorlabel.config(text="The number \""+fiveDigit.get()+"\"\n is not a valid host!") errorlabel.place(relx="0.0",rely="0.3") else: numFrame.place_forget() dropLabel.place(relx="0.05",rely="0.27") # PUT THIS THERE WHEN CONNECTED except ValueError: #(ValueError,TypeError): errorlabel.config(text="The input \""+fiveDigit.get() +"\"\nis not a five digit number.") errorlabel.place(relx="0.0",rely="0.3")
def stt_google_wav(filename): #Convert to flac FLAC_CONV = 'flac -s -f ' os.system(FLAC_CONV+filename+'.wav') f = open(filename+'.flac','rb') flac_cont = f.read() f.close() #post it lang_code='fr-FR' googl_speech_url = 'https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&pfilter=2&lang=%s&maxresults=6'%(lang_code) hrs = {"User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7",'Content-type': 'audio/x-flac; rate=16000'} req = urllib.request.Request(googl_speech_url, data=flac_cont, headers=hrs) p = urllib.request.urlopen(req) rep="" try: res = eval(p.read())['hypotheses'] rep=res[0] rep=rep.get('utterance') except: rep="pas compris" if rep=="": rep="pas compris" os.remove("output.wav") os.remove("output.flac") print("rep="+str(rep)) if re.search("lulu",str(rep)): Client.sendMsg("T",rep) return "ok"
def init(isclient, serverip, name, screen, clock): screen.fill((0, 0, 0)) pygame.display.update() if isclient: try: host, port = serverip.split(":") except ValueError: host = serverip port = 12341 Client.connect(host) Client.ready(name) else: try: host, port = serverip.split(":") except ValueError: host = "" port = 12341 Server = server() while True: if not isclient: if Server.isdone(): break for thing in Server.connected: print(thing.name)
def run(self): """Main""" global SON global TLP while not self._stopevent.isSet(): data = input(">") if data == "quit": TLP.stop() self.stop() elif data == "Tais toi!": SON = False elif data == "Parle!": SON = True elif re.search("je.*envoie.*fichier", data): regex = re.search(r"[A-Za-z]*.\.[A-Za-z]*", data) fileName = regex.group(0) data2, infos = FileManager.sendFichier(0, fileName) if infos[1] == 0: Client.sendFile(data2, fileName) else: choix = input(data2) data2, infos = FileManager.sendFichier(1, choix, infos) elif len(data): Client.sendMsg("T", str(data)) else: continue
def setTile(self,x, y, tile): if x < 0 or y < 0 or x > self.width or y > self.height: return self.tiles[x+(y*self.width)] = tile.id if gui.isMultiplayer: Client.setTile(tile.id,x,y) self.hasChanged = True
def openList(self, root = None): url = self.buildUrl()+self.itemsSubPath if url[-1] == '/': url = url[:-1] self.server = self.getResource(url) try: self.entries, self.entryIds = self.server.zoa.items() except xmlrpclib.Fault, error: #print str(error) # see if zoa object is installed try: Client.call('http://%s/zoa'%self.buildUrl(), self.properties['username'], self.properties['passwd'], function='version') except Client.NotFound: if wx.MessageBox( 'The zoa object not found in the root of your Zope tree.\n\n' 'Do you want to install it?', 'Install zoa', wx.YES_NO | wx.ICON_QUESTION) == wx.YES: import ZoaClient conninfo = ('http://%s'%self.buildUrl(), self.properties['username'], self.properties['passwd']) ZoaClient.installFromFS(conninfo, os.path.join(Preferences.pyPath, 'ZopeLib', 'zoa', )) # try again, if this fails the real error should break thru self.entries, self.entryIds = self.server.zoa.items() else: err = error.faultString raise zopeHtmlErr2Strs(err)
def tick(self): global x,y super(Animal,self).tick() xa = 0 ya = 0 self.centreX= self.x+31 self.centreY= self.y+63 xx = self.centreX >>5 yy = self.centreY >>5 if self.ticks%random.randint(1,100)==0: xa = random.randint(-4,4) else: xa = 0 if xa != 0 or ya != 0: self.isMoving = not self.move(xa, ya) if Client.isHost == True and gui.isMultiplayer==True: Client.moveEntity(self.id,self.x,self.y,self.movingDir,self.isSwimming) else: self.isMoving = False if self.getTileUnder().getId() == Tile.water.getId(): self.isSwimming = True else: self.isSwimming = False
def tick(self): global x,y super(Animal.Animal,self).tick() self.breedCoolDown -=1 self.deathTimer -=1 if self.deathTimer <0:self.die() self.centreX= self.x+16 self.centreY= self.y+16 xx = self.centreX >>5 yy = self.centreY >>5 if self.entityCollidedWith != None: try:self.mate(self.level,self.entityCollidedWith) except:print "That can't mate with a duck!" #print self,self.entityCollidedWith self.entityCollidedWith = None if self.ticks%random.randint(1,500)==0: self.xa = random.randint(-1,1) self.ya = random.randint(-1,1) if self.xa != 0 or self.ya != 0: self.isMoving = not self.move(self.xa,self.ya) if Client.isHost == True and gui.isMultiplayer == True: Client.moveEntity(self.id,self.x,self.y,self.movingDir,self.isSwimming) else: self.isMoving = False if self.getTileUnder().getId() == Tile.water.getId(): self.isSwimming = True else: self.isSwimming = False
def tick(self): super(Player,self).tick() self.placeCooldown -=1 self.xa = 0 self.ya = 0 self.centreX= self.x+32 self.centreY= self.y+62 xx = self.centreX >>5 yy = self.centreY >>5 soundFXs = Sounds.Audio(False) if Keyboard.keys['w']: self.ya=-1 if Keyboard.keys['s']: self.ya=1 if Keyboard.keys['a']: self.xa=-1 if Keyboard.keys['d']: self.xa=1 if self.xa != 0 or self.ya != 0: self.isMoving = not self.move(self.xa, self.ya) VRClient.move(self.x,self.y) if gui.isMultiplayer == True: Client.move(self.x,self.y,self.movingDir,self.isSwimming) #soundFXs.Plysound(True,False,False,False,False) else: self.isMoving = False soundFXs.Plysound(False,False,False,False,False) if self.getTileUnder().getId() == Tile.water.getId()or self.getTileUnder().getId() == Tile.larva.getId() or self.getTileUnder().getId() == Tile.quicksand.getId(): self.isSwimming = True else: self.isSwimming = False if self.getTileUnder().getId() == Tile.larva.getId()or self.getTileUnder().getId() == Tile.quicksand.getId(): if self.health < 0: self.health = 0 self.health = self.health - 1 if self.health <= 0: gui.gameOver = True gui.defeat = True if self.movingDir == 0:self.selectedTile=[xx,yy+1]#up if self.movingDir == 1:self.selectedTile=[xx,yy-3]#down if self.movingDir == 2:self.selectedTile=[xx-1,yy-1]#left if self.movingDir == 3:self.selectedTile=[xx+1,yy-1]#right if self.selectedTile[0]<<5 != self.inHand.x or self.selectedTile[1]<<5!=self.inHand.y: self.inHand.x = self.selectedTile[0]<<5 self.inHand.y = self.selectedTile[1]<<5 self.inHand.CanPlace() else: self.inHand.x = self.selectedTile[0]<<5 self.inHand.y = self.selectedTile[1]<<5 if Keyboard.keys['e'] and self.placeCooldown <0: if self.inHand.placeInLevel():self.placeCooldown = 20
class PyChatGUI(QDialog, Ui_Dialog): send_message_signal = pyqtSignal(str) def __init__(self, parent=None, socket_=None, ip=None): QDialog.__init__(self) # try: if not socket_: print ip self.socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket_.connect((ip, 9000)) else: self.socket_ = socket_ #Set up the client thread self.client = Client(self, self.socket_) self.client.receive_message_signal.connect(self.receive_message) self.client.start() self.parent = parent self.parent.trayIcon.messageClicked.connect(self.showDialog) self.setupUi(self) self.setVisible(True) self.sendButton.clicked.connect(self.send_message) def showDialog(self): self.setVisible(True) def sendMessage(self): """Emit the message to be sent over the network""" self.textBrowser.append('me: ' + self.lineEdit.text()) self.send_message_signal.emit(self.lineEdit.text()) self.lineEdit.setText('') self.lineEdit.setFocus() def receiveMessage(self, msg): """Append the message to the current dialog window""" try: name = self.parent.get_connected_pc_name(self.socket_) except Exception as e: print e print 'Closing sockets...' self.socket_.close() self.parent.server.close() return if not self.isVisible(): self.parent.trayIcon.showMessage('New message', 'You have a new message from ' + name) self.textBrowser.append(name + ': ' + unicode(msg)) self.lineEdit.setText('') self.lineEdit.setFocus() def closeEvent(self, event): self.setVisible(False) self.socket_.close() event.ignore()
def loadLevelFromFile(self,path): if Client.isHost == True and gui.isMultiplayer==True: self.addTiles(path) Client.sendTiles(self.tiles) elif gui.isMultiplayer==True: while len(self.tiles)<2:#wait for tiles from host #print "Waiting for tiles.." pass else: self.addTiles(path)
def start(self): try: ss = socket(AF_INET,SOCK_STREAM) ss.bind(('',9082)) ss.listen(1000) while True: connection,address = ss.accept() clientInstance = Client(attachingChatServer=self,connSocket=connection,lock=self.lock) clientInstance.start() except IOError,(errno, strerror): print "I/O error({0}): {1}".format(errno, strerror)
def __init__(self,level, x, y): super(Animal,self).__init__(level,x,y) self.x = x self.y = y self.id = len(level.entities) self.isSwimming = False self.isMoving = False self.img = pygame.image.load("animals/crab.png") self.basicFont = pygame.font.SysFont(None, 32) if Client.isHost == True: Client.sendEntity("Crab",x,y)
def run(self): global son while not self._stopevent.isSet(): type,received = Client.receiveMsg() if type=="N": #print(received) Client.notify(received) else: print("-->%s" % received) if son: adire=received[:-14] Audio.parle(adire) time.sleep(0.01)
def __init__(self, ip_addr, port): self.TCPsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.TCPsock.bind((ip_addr, port)) self.node_list = [] self.clients = [] #self.connectedList =[] self.TCPsock.listen(1) conn, addr = self.TCPsock.accept() print "server accepted connection from ..\n" data_string = conn.recv(1024) data = pickle.loads(data_string) self.node_list = data print "printing list: \n" for x in self.node_list: print "ip:" print x.ip_addr print "\t" print "Port:" print x.port print "\n" i = 0 for x in self.node_list: if (x.port == port) : continue #c = Client.client(x.ip_addr, x.port, self.connectedList) c = Client.client(x.ip_addr, x.port) self.clients.append(c) self.clients[i].start() i = i + 1
def __init__(self, host, port, name, manual): self.client = Client(host, port, name, manual) pygame.init() # the GUI should reference the client, but never modify it # self.bg = pygame.image.load(os.path.join('data', 'map.png')) self.screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption("Warlords") pygame.mouse.set_visible(1) # make icon invisible icon = pygame.Surface((1, 1)) icon.set_alpha(0) pygame.display.set_icon(icon) self.clock = pygame.time.Clock() self.font = pygame.font.SysFont(None, 16) self.font2 = pygame.font.SysFont(None, 64) self.font3 = pygame.font.SysFont(None, 32) self.chatTextBox = Input(x=5, y=460, font=self.font, maxlength=63, color=(0, 0, 0), prompt="Chat: ") self.playTextBox = Input(x=210, y=400, font=self.font3, maxlength=20, color=(255, 0, 0), prompt="Input Play: ") self.swapTextBox = Input( x=210, y=430, font=self.font3, maxlength=2, color=(255, 0, 0), prompt="Input Card to Swap: " )
def actionPerformed(self,e): print e.getActionCommand() comm=e.getActionCommand() if comm=='Connect': rsp=Client.login(frame.getServerAddress(),frame.getUserName(),'9999') frame.addMsg(rsp) if rsp=='success': e.getSource().setEnabled(False) Client.requestUserList(frame.getServerAddress()) for u in Client.userlist.keys(): frame.addUser(u) elif comm=='Send': print frame.getSelectedUser() Client.sendmsg(frame.getMessage(),frame.getSelectedUser()) elif comm=='Exit': frame.dispose()
def OnConnect(self, event=None): if not self.status: if not self.me or self.me == '*': common.showerror(self, tr("Username should not be empty or '*'")) self.txtName.SetFocus() return ip = self.txtIP.GetValue() if not ip: common.showerror(self, tr("Host address cannot be empty!")) self.txtIP.SetFocus() return port = int(self.txtPort.GetValue()) self.pref.pairprog_host = ip self.pref.pairprog_port = port self.pref.pairprog_username = self.me self.pref.save() # try: self.client = Client.start_client(ip, port, self.clientcommands) if self.client: self.client.call('join', self.me) self.change_status('connectserver') self.callplugin('start', self, 'client') # except: # common.warn(tr("Connect to server error!")) # error.traceback() else: self.client.close() self.client = None self.change_status('disconnectserver') self.callplugin('stop', self, 'client')
def run(self): global son while not self._stopevent.isSet(): typ,received = Client.receiveMsg() if typ=="N": Client.notify(received) elif typ=="F": r=received.split(";") FileManager.convertFileReceive(r[0],r[1]) Client.notify("notif;Transfert;Fichier "+r[1]+" bien reçu;4") else: print("\n-->%s" % received) if son: adire=received[:-14] Audio.parle(adire) time.sleep(0.01)
def __init__(self, linklayer, transportlayer, config, stage2 = "", duckencoder = None): # state value to inform sub threads of running state self.running = False self.stage2=stage2 self.config = config self.client = Client() # object to monitor state of remote client self.client.registerCallbackOnConnectChange(self.onClientConnectStateChange) #self.control_sysinfo_response = BlockingQueue("CONTROL_SERVER_SYSINFO_RESPONSE") self.server_thread_in = Thread(target = self.__input_handler, name = "P4wnP1 Server Input Loop", args = ( )) self.server_thread_out = Thread(target = self.__output_handler, name = "P4wnP1 Server Output Loop", args = ( )) self._next_client_method_id = 1 self.tl = transportlayer self.ll = linklayer self.__pending_server_methods = {} self.duckencoder = duckencoder self.mousescriptparser = MouseScriptParser() # register Listener for LinkLayer signals to upper layers (to receive LinkLayer connection events) dispatcher.connect(self.signal_handler_transport_layer, sender="TransportLayerUp") self.client_connected_commands = ["ls", "pwd", "cd", "shell", "CreateProc", "interact", "download", "upload", "echotest", "GetClientProcs", "KillClient", "KillProc"] self.setPrompt(False, False) cmd.Cmd.__init__(self) self.intro = '''=================================
def process(process_args): print 'process: {0}'.format(process_args) if process_args.list: print "do list" client = Client.get_client(process_args.client) list_vms(client) else: print "do something else"
def run(self): """main""" global SON while not self._stopevent.isSet(): typ, received = Client.receiveMsg() if typ == "N": rec = Client.notify(received) if rec == "ko": print("\n-->%s" % received) elif typ == "F": rec = received.split(";") FileManager.convertFileReceive(rec[0], rec[1]) rec = Client.notify("notif;Transfert;Fichier "+rec[1]+" bien reçu;4") if rec == "ko": print("\n-->Fichier "+rec[1]+" bien reçu") else: print("\n-->%s" % received)
def main(argumentos): mensaje = { "accion" : "recibir", "identificador" : argumentos[1], "llavePrivada" : argumentos[2], "participante" : argumentos[3] if len(argumentos) > 2 else "" } return Client.sendData(mensaje)
def main(): ADDR = getArg( "a", "127.0.0.1", "Address" ) PORT = getArg( "p", 5005, "Port" ) options = { "name":getArg( "n", "User", "Name" ) } # Create client CLIENT = Client( ADDR, PORT, options ) # Connect to server # This will enter the client main loop try: CLIENT.connect() except: pass CLIENT.close()
def __init__(self, color): self.butterflies = [] self.screen = pygame.display.get_surface() self.backgroundImage, self.backgroundRect = loadPNG("background.png") self.buttonSound = pygame.mixer.Sound("resources/sound/button.wav") self.buttonSound.set_volume(float(Resources.getOptionValue("sound"))/100) self.active = True self.level = Map(True) self.toolbar = GameToolbar() self.client = Client('localhost') self.client.connect() self.client.recieve() self.client.send(b"connexion avec serveur : OK") #MAP STRING RECIEVE mapStr = self.client.recieve(4096) mapStr = struct.unpack(str(len(mapStr)) + "s", mapStr)[0] #LOAD MAP FROM STRING self.level.saveFromStr("tempClient", mapStr) self.level.load("tempClient") #CREATE CLIENT RABBIT self.regis = Rabbit(1, "regis" , color, self.level.objectList, self.level.objectSpritesList) #SERVER RABBIT COLOR RECIEVE serverCol = self.client.recieve() serverCol = struct.unpack("iii", serverCol) #CLIENT RABBIT COLOR SEND self.client.send(struct.pack("iii", self.regis.color[0], self.regis.color[1], self.regis.color[2])) #CREATE SERVER RABBIT self.john = Rabbit(2, "john" , serverCol, self.level.objectList, self.level.objectSpritesList, True) self.regis.appendRabbit(self.john) self.john.appendRabbit(self.regis) self.pauseMenu = PauseGameMenu() # for l in range(0, 6): # while True: # randPos = random.randint(0, 16) # if not self.level.isInBlock(self.level.objectList[randPos].getX() + 10, self.level.objectList[randPos].getY() - 26): # break # butterfly = Butterfly(self.level.objectList[randPos].getX() + 10, self.level.objectList[randPos].getY() - 26, (255, 10, 100), self.level.objectList, self.level.objectSpritesList) # self.butterflies.append(butterfly) pygame.display.flip()
def __init__(self,level, x, y,r,g,b): super(Animal.Animal,self).__init__(level,x,y) self.x = x self.y = y self.id = len(level.entities) self.isSwimming = False self.isMoving = False self.img = [pygame.image.load("animals/duckfront.png"),pygame.transform.flip(pygame.image.load("animals/duckfront.png"),False,True),pygame.transform.rotate(pygame.image.load("animals/duckfront.png"),-90),pygame.transform.rotate(pygame.image.load("animals/duckfront.png"),90)] self.xa =0 self.ya =0 self.red = r self.green = g self.blue = b self.breedCoolDown = random.randint(500,5000) self.deathTimer = random.randint(2000,20000) self.limitedToOneTile = True if Client.isHost == True: Client.sendEntity("Duck",x,y)
def openLogin(self): if self.login_socket.bytesAvailable() > 0: message = self.login_socket.read(self.login_socket.bytesAvailable()) self.xmlInputSource.setData(message) #print 'DEBUG DATA', self.xmlInputSource.data() # Parse xml file if self.reader.parse(self.xmlInputSource) == False: message = str('XML parse error:' % self.handler.errorString()) self.textEdit.append(message) self.closeLogin(message) return False if self.handler.type == 'login': #print 'DEBUG user', self.handler.user, ' password', self.handler.password # check if user exists if self.userNamePassword.__contains__(str(self.handler.user)) == False: self.closeLogin('user dont exists') return # check that password is correct if self.userNamePassword[self.handler.user] != self.handler.password: self.closeLogin('wrong password') return # check if user is already connected for c in self.client_list: if c.username() == self.handler.user: self.closeLogin('user already exists') return # NEW CLIENT ACCEPTED message = str("%s logged in" % self.handler.user) self.textEdit.append(message) self.sendSystemMessage(message) c = Client(self.handler.user, self.userNamePassword[self.handler.user], self.login_socket) c.socket().disconnected.connect(self.closeConnection) c.socket().write(str('<chat><content user=\"server\" type=\"login\"></content><message message=\"success\"></message></chat>')) self.client_list.append(c) # set the login socket back to negative self.login_socket = int(-1)
def MyThread(protocol,st_IP,ed_IP,overallDic,start,end): print 'st_IP:',st_IP,'ed_ip:',ed_IP tmp_cond = Client(protocol.upper(),st_IP,ed_IP,NETWORK_TIME_OUT); if tmp_cond == -1: #tmp_cond = {NETWORK_BANDWITH:'0 (Mbs)',NETWORK_DELAY:'0 (ms)',NETWORK_JITTER:'0 (ms)',NETWORK_LOSS:'0 (%)',NETWORK_CONGESTION:'NO',NETWORK_AVAIL:'NO,起始结点故障'} #tmp_cond = {NETWORK_BANDWITH:TAG_UNREACHABLE,NETWORK_DELAY:TAG_UNREACHABLE,NETWORK_JITTER:TAG_UNREACHABLE,NETWORK_LOSS:TAG_UNREACHABLE,NETWORK_CONGESTION:TAG_UNREACHABLE,NETWORK_AVAIL:'起始结点故障'} tmp_cond = {NETWORK_AVAIL:'起始结点故障'} ###end client######3 if tmp_cond[NETWORK_AVAIL] == 'NO': #tmp_cond = {NETWORK_BANDWITH:'0 (Mbs)',NETWORK_DELAY:'0 (ms)',NETWORK_JITTER:'0 (ms)',NETWORK_LOSS:'0 (%)',NETWORK_CONGESTION:'NO',NETWORK_AVAIL:'NO,目标结点不可达'} #tmp_cond = {NETWORK_BANDWITH:TAG_UNREACHABLE,NETWORK_DELAY:TAG_UNREACHABLE,NETWORK_JITTER:TAG_UNREACHABLE,NETWORK_LOSS:TAG_UNREACHABLE,NETWORK_CONGESTION:TAG_UNREACHABLE,NETWORK_AVAIL:'目标结点不可达'} tmp_cond = {NETWORK_AVAIL:'目标结点不可达'} #do socket func in here #tmpNode = {itemB.nodeName:tmp_cond[]} if tmp_cond.has_key(NETWORK_BANDWITH): overallDic[NETWORK_BANDWITH][start.nodeName][end.nodeName] = tmp_cond[NETWORK_BANDWITH] else: overallDic[NETWORK_BANDWITH][start.nodeName][end.nodeName] = '*' #'0 (Mbs)' if tmp_cond.has_key(NETWORK_DELAY): overallDic[NETWORK_DELAY][start.nodeName][end.nodeName] = tmp_cond[NETWORK_DELAY] else: overallDic[NETWORK_DELAY][start.nodeName][end.nodeName] = '*' #'0 (ms)' if tmp_cond.has_key(NETWORK_JITTER): overallDic[NETWORK_JITTER][start.nodeName][end.nodeName] = tmp_cond[NETWORK_JITTER] else: overallDic[NETWORK_JITTER][start.nodeName][end.nodeName] = '*' #'0 (ms)' if tmp_cond.has_key(NETWORK_CONGESTION): overallDic[NETWORK_CONGESTION][start.nodeName][end.nodeName] = tmp_cond[NETWORK_CONGESTION] else: overallDic[NETWORK_CONGESTION][start.nodeName][end.nodeName] = '*' #'NO' if tmp_cond.has_key(NETWORK_LOSS): loss = tmp_cond[NETWORK_LOSS] loss = loss.split() tmpLoss = float(loss[0]) #liar liar while (tmpLoss > 1): tmpLoss = tmpLoss/10 tmpLoss = round(tmpLoss,2) overallDic[NETWORK_LOSS][start.nodeName][end.nodeName] = str(tmpLoss) + " %" #判断,如果丢包率过高,则认为网络当前拥塞 #if tmp_cond[NETWORK_LOSS] >= TAG_CONGESTION: overallDic[NETWORK_CONGESTION][start.nodeName][end.nodeName] = isCongestion(tmp_cond[NETWORK_LOSS]) else: overallDic[NETWORK_LOSS][start.nodeName][end.nodeName] = '*' #'0 (%)' if tmp_cond.has_key(NETWORK_AVAIL): overallDic[NETWORK_AVAIL][start.nodeName][end.nodeName] = tmp_cond[NETWORK_AVAIL] else: overallDic[NETWORK_AVAIL][start.nodeName][end.nodeName] = 'NO'
def test_show_account_with_a_invalid_account(self): client = Client.get_client('mustafa') # from the lion-king try: Account.show_account(client) except SoftLayer.SoftLayerAPIError as slAPIe: pass except BaseException as be: self.assertEquals(be.message, "bad client") else: self.fail("expected a SoftLayer.SoftLayerAPIError")
def connection(): Client.connect() identify=0 essai=0 while identify==0 and essai < 3: pseudo=raw_input("Entrer votre pseudonyme: ") password=getpass.getpass("Entrer le mot de passe: ") Client.sendMsg("L",pseudo+";,;"+password) rep=Client.receiveMsg() if(rep[1][9:]=="1"): identify=1 break else: if(essai<2): print("Vous avez fais une erreur\nVeuillez recommencer") if(essai==2): print("Trop d'erreurs, au revoir") quit() essai=essai+1 return identify
def testHashes(contractID, desiredBlockHash, desiredTxHash): client = c.Client(contractID, Host.url) assert (client.result) firstBlock = client.findFirstContractBlock() hashes = client.getHashes(firstBlock) assert (hashes == (desiredBlockHash, desiredTxHash))
import Client from twisted.internet import reactor port = 5070 host = "127.0.0.1" peers = [(host, 5050), (host, 5090)] db_url = "../databases/db2.txt" deb_url = "/home/raluca/Desktop/BitcoinWannabe/databases/db2.txt" node1 = Client.Client(host, port, db_url) reactor.listenUDP(port, node1) reactor.run()
import Client user = Client.Client("http://api.vk.com/method", "users.get") user.params = "user_ids=" + input('Введите username или vk_id пользователя: ') resp_user = user.execute() id = user.find_id(resp_user.json()) print("Ваш id: ", id) friends = Client.Client("http://api.vk.com/method", "friends.get") friends.params = "user_id=" + id + "&fields=bdate" resp_friends = friends.execute() friends.build_gist(resp_friends.json())
if __name__ == '__main__': import Client Client.main()
def setUp(self): self.client = Client.get_client('tsuralik') self.account = Account
n15 = gt.Gateway('10.228.204.9', 0.15, datetime.datetime.strptime('2018-03-15 18:59:15', '%Y-%m-%d %H:%M:%S'), status=False, sender=None) listGW = [ node1, node2, node3, node4, node6, node7, node8, node9, node10, node11, node12, node13, node14, node15 ] #listGw = [node6, node7] listActual = [n1, n2, n3, n4, n6, n7, n8, n9, n10, n11, n12, n13, n14, n15] #listActual = [n6,n7] neighbour1 = cl.Client('10.228.207.66', [], [], None) neighbour2 = cl.Client('10.139.40.87', [], [], None) neighbour3 = cl.Client('10.228.205.132', [], [], None) neighbour4 = cl.Client('10.1.15.70', [], [], None) neighbour5 = cl.Client('10.1.13.106', [], [], None) neighbour6 = cl.Client('10.1.9.132', [], [], None) neighbour7 = cl.Client('10.228.205.132', [], [], None) listNbs = [neighbour1, neighbour2, neighbour3] #listNbs = [neighbour1, neighbour2, neighbour3, neighbour4, neighbour5] #listNbs = [neighbour1, neighbour2, neighbour3, neighbour4, neighbour5, neighbour6, neighbour7] #listNbs = [neighbour2, neighbour1] neighbour1 = cl.Client('10.228.207.65', [], [], None) neighbour2 = cl.Client('10.228.207.66', [], [], None) neighbour3 = cl.Client('10.139.40.87', [], [], None)
from _thread import start_new_thread ser = serial.Serial ("/dev/ttyUSB0") ser.timeout = 0.9 ser.baudrate = 115200 sio = io.TextIOWrapper(io.BufferedRWPair(ser,ser)) #SEND ALIV AS KOORDINATOR STATE def sendAlive(self): while self.state == "COOR": message = Message.Message("ALIV","0","0","0",self.addr,"ffff","I am the captian!") message.send(self.sio,"ffff") print("Meesge"+message.getMessage()) time.sleep(5) test = client.Client("COOR",ser,"",[]) test.config() test.setAddrModul("0000") def loop(): while 1: if ser.inWaiting(): read = sio.readline() #if read != "": print(read) test.sendAlive() #test.sendCoordinatorDisc() #test.sendAddrRequest() start_new_thread(loop(),())
#!/usr/bin/env python # -*- coding: utf-8 -*- import signal from Client import * if __name__ == "__main__": c = Client() #signal.signal(signal.SIGINT, c.shutdown) #c.start()
def get_map_total(Title): # Getting the Server and Client's data names_cl, countries_cl, lats_cl, lons_cl = C.get_data_clients() names_ser, countries_ser, lats_ser, lons_ser, costs_ser = S.get_data_servers( ) # How much to zoom from coordinates (in degrees) zoom_scale = 0 # Setup of the bounding box for the zoom and bounds of the map if Title == "Clients": bbox = [np.min(lats_cl)-zoom_scale,np.max(lats_cl)+zoom_scale,\ np.min(lons_cl)-zoom_scale,np.max(lons_cl)+zoom_scale] else: bbox = [np.min(lats_ser)-zoom_scale,np.max(lats_ser)+zoom_scale,\ np.min(lons_ser)-zoom_scale,np.max(lons_ser)+zoom_scale] #Generates the base of the map by using arcgis map images fig = plt.figure(figsize=(12, 7), edgecolor='b') m = Basemap(projection='cyl', resolution=None, llcrnrlat=-90, urcrnrlat=90, llcrnrlon=-180, urcrnrlon=180) m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels=1500, verbose=True) #Prits servers or clients and uses different colors for different continents if Title == "Clients": for i in range(len(lats_cl)): x, y = m(lons_cl[i], lats_cl[i]) if countries_cl[i] == "NA": m.plot(x, y, 'r*', markersize=1) if countries_cl[i] == "SA": m.plot(x, y, 'y*', markersize=1) if countries_cl[i] == "EU": m.plot(x, y, 'c*', markersize=1) if countries_cl[i] == "AS": m.plot(x, y, 'g*', markersize=1) if countries_cl[i] == "OC": m.plot(x, y, 'w*', markersize=1) if countries_cl[i] == "AF": m.plot(x, y, 'm*', markersize=1) else: for i in range(len(lats_ser)): x, y = m(lons_ser[i], lats_ser[i]) if countries_ser[i] == "NA": m.plot(x, y, 'r*', markersize=4) if countries_ser[i] == "SA": m.plot(x, y, 'y*', markersize=4) if countries_ser[i] == "EU": m.plot(x, y, 'c*', markersize=4) if countries_ser[i] == "AS": m.plot(x, y, 'g*', markersize=4) if countries_ser[i] == "OC": m.plot(x, y, 'w*', markersize=4) if countries_ser[i] == "AF": m.plot(x, y, 'm*', markersize=4) #Adds titles and saves the figure plt.title(Title + " Distribution") plt.savefig('./Outputs/' + Title + '.pdf', format='pdf', dpi=1000) plt.show()
from Client import * if __name__ == "__main__": client = Client() client.run()
#!/usr/bin/env python # -*- coding: utf-8 -*- import Client c = Client.Client_Class() print(c.get_ans("http://www.ariel.ac.il/", "דיזיין")) print(c.get_ans("http://www.ariel.ac.il/", "מידע אישי")) print(c.get_ans("http://www.ariel.ac.il/", "מינהלה"))
for i in range(len(o)): if (o[i] > t[i]): return ours elif (t[i] > o[i]): return theirs g.masterID = master(g.ID, g.otherID) print 'Master BD_ADDR is: ', g.masterID def do_sockets(): while (True): data = g.conn.recv_data() print "Recieved some Data" temp = BitArray(uint=data[1], length=26) g.clock, plaintext = temp, Bits(bytes=data[3]) rev = BitArray(g.clock) rev.reverse() print "clock: ", g.clock keystream, cipheredTxt = StateMachine.encipher( g.masterID, g.kcPrime, rev, plaintext) g.send_log('true', g.ID == g.masterID, keystream, plaintext, cipheredTxt) thread.start_new_thread(do_sockets, ()) print 'started sockets thread' Client.MyWebServer().start() #thread.start_new_thread(Client.start_server(), ())
future_date = now + \ timedelta(days=self.account.days) + timedelta(hours=16) second_date = datetime( future_date.year, future_date.month, future_date.day, 16, 0) print("Date after: " + str(second_date)) difference = future_date - now # if time has reached, return false so looping stops if difference.total_seconds() <= 0: return False # if time has not been reached, looping condition stays true return True if __name__ == '__main__': print('[Cactus] Enter Riot account details.') print("=" * 60) account = ac.Account() account.Setup() print("=" * 60) client = cl.Client(account) client.Build() vanguard = Cactus(account, client) vanguard.Run()
def start_clients(user, chat): new_client = Client(user, chat)
def genClientArray(size): clients = [] for index in range(size): clients.append( Client(index)) return clients
import pygame_gui import math import sys import random from Client import * from queue import deque import queue # Pygame Variables size = 10 width = 800 height = 600 # CLient client = None clientObject = Client() connectButtonBoolean = False activeSubscriptions = [] # Initialization pygame.init() display = pygame.display.set_mode((width, height)) manager = pygame_gui.UIManager((width, height)) pygame.display.init() pygame.display.set_caption("Event Service Subscriber") clock = pygame.time.Clock() # Fonts myFont = pygame.font.SysFont("Arial", 20) bigFont = pygame.font.SysFont("Arial", 32)
import Client if __name__ is '__main__': clientInstance = Client.Client("192.168.3.XX") readed = clientInstance.readTemp() print(readed)
def __init__(self, node, difficulty): super(Miner, self).__init__() self.node = node self.client = Client.Client("Miner") self.difficulty = difficulty # number of zeros in the hash
print("connect <server IP> <port>") print("reg <user name> <speed>") print("quit") print("get <server> <port> <filename>") print("list") print("add <filename> <description>") print("--------------------------------------") if __name__ == '__main__': signal.signal(signal.SIGINT, signal_handler) msg = "" port = 1609 server = "localhost" myClient = Client.Client(server) help() while myClient.serverRunning: msg = str(input("enter a command: ")) command = msg.split() if command[0].lower() == "connect" and len(command) == 3: myClient.connectToServer(command[1], command[2]) elif command[0].lower() == "reg" and len(command) == 3: myClient.Register(command[1], command[2]) elif command[0].lower() == "quit": myClient.Quit() break elif command[0].lower() == "get" and len(command) == 4: myClient.Get(command[3], command[1], command[2])
parser.add_argument('--camId', help='set the id of the camera', default=0, type=int) args = parser.parse_args() return args if __name__ == "__main__": # Kinect = False; args = parse_args() client = Client.Client(ConnectionType=args.Service, show=args.Show, write=args.Write, IP=args.HOST, Port=args.PORT, camId=args.camId) ret = client.initConnection() if client.write: imgNr = 0 if (not os.path.isdir('./cam' + str(client.camId))): os.mkdir('./cam' + str(client.camId)) while ret is not None: ret = client.getDataFromServer() if ret is not None: if client.connectionType != 'KinectDepth': ret = client.convertdata2image() else:
def send(self): Client.send_email(self)
# -*- coding:utf-8 -*- import threading import Client import Application if __name__ == '__main__': client1 = Client.Client('1', 10001, 40001) client1.bind_address() threads = [] thread = threading.Thread(target=client1.register) threads.append(thread) thread = threading.Thread(target=client1.get_client_info) threads.append(thread) app = Application.Application(client1.toClient, 'client1') thread = threading.Thread(target=client1.add_peer_to_app, args=(app, )) threads.append(thread) thread = threading.Thread(target=app.receive_message) threads.append(thread) for t in threads: t.setDaemon(True) t.start() app.create_app() app.run() for t in threads: t.join()
def gameLoop(): status = 0 # skip first 20 frames of video capture to allow camera initialization skip_frames = 20 while skip_frames > 0: Camera.get_image_external() skip_frames -= 1 while True: # get and cache current camera frame camFrame = Camera.get_image_external() camFrame = cv2.flip(camFrame, 1) camFrame = cv2.resize(camFrame, (640, 480)) SyncGlobals.setCamFrame(camFrame) # get next game frame from server gameFrame = Client.getNextFrameFromServer() if gameFrame.any(): # cache current game frame SyncGlobals.setGameFrame(gameFrame) # get cached paper position and size pointAsTuple = SyncGlobals.getPointAsTuple() paperSizes = SyncGlobals.getPaperSizes() # paper position recognized if pointAsTuple is not None and paperSizes is not None: # merge game frame into camera frame on top of recognized paper camFrame = PaperHomography.implantFrameOnPaper( camFrame.copy(), gameFrame, paperSizes, pointAsTuple) Camera.show_image("Draw me a way", cv2.flip(camFrame, 1), STATUS_TEXT[status]) # space to continue if cv2.waitKey(1) == 32: # user wants to start playing the game if status == 0: # get cached state of paper scannedInk = SyncGlobals.getScannedInk() if scannedInk is not None: # capture lines from cached state of paper edgy = cv2.resize(scannedInk, (640, 480)) lines = DetectBlackPixels.findBlackLines( cv2.Canny(edgy, 100, 300)) # send recognized lines to game server, but limit to 4 lines num = 0 for line in lines: if line is not []: num += 1 if num < 4: Client.sendLineToServer(line) else: break # start playing the game Client.sendPlayToServer() # user wants to reset the game elif status == 1: Client.sendResetToServer() # advance game state status = (status + 1) % len(STATUS_TEXT) # user wants to quit if cv2.waitKey(1) == 27: Client.sendQuitToServer() break
def test_show_account_with_a_valid_account(self): client = Client.get_client('tsuralik') retVal = Account.show_account(client) self.assertEquals(retVal, None)
def test_bad_account_(self): bad_client = Client.get_client('mustafa') # from the lion-king details = Account.get_details(bad_client) self.assertEquals(details, None)
# def print_all(self): # while True: # for i in self.client.list_of_incoming_messages: # print(i) if __name__ == '__main__': good_clients_server_flag = False ########### Tworzę Clienta - automatycznie tworzy się server klienta #### while not good_clients_server_flag: try: port = input( "Wprowadź numer portu na którym będzie słuchał server znajdujący się u klienta i inne dane " "oddzielone @\nlogin@password@number_of_port\n") tmp = port.split("@") client = Client(tmp[0], tmp[1], int(tmp[2])) good_clients_server_flag = True except OSError: print("Wprowadź numer portu ponownie") ############# tworze wątek do obsługi serwera na kliencie ######### if good_clients_server_flag: try: clients_server = Thread( target=client.clients_server_listen_for_other_users, args=()) clients_server.start() except: print("Error when waiting for new connection") main_application = Client_app(client) # main_application.main_window.mainloop()
import Client as client import ssl ssl.match_hostname = lambda cert, hostname: True btc = client.getKline(1200, "btc_usdt") eos = client.getKline(1200, "eos_usdt") count = 0 for i in btc['data']: index = btc['data'].index(i) if index > 1: eosOpen = eos['data'][index - 1]["open"] eosClose = eos['data'][index - 1]["close"] btcOpen = i["open"] btcClose = i["close"] if eosOpen > eosClose and btcOpen > btcClose: count += 1 gap = eosOpen - eosClose mul = gap / eos['data'][index - 2]["close"] if mul > 0.007: print(eosOpen, eosClose, eos['data'][index - 2]["close"]) count += 1 if eosOpen < eosClose and btcOpen < btcClose: count += 1 gap = eosClose - eosOpen
import Units, pygame, math, sys, json, InputProcessor, Interface, Buildings, Client from Units import Grunt, Sword from Network import Network RES = [(800, 450), (960, 540), (1600, 900)] COL_BG = (132, 112, 103) c = Client(2, False) c.startGame()
def clientQueue(size): clients = LinkedList() for index in range(0, size): clients.push( Node( Client( index))) return clients
def runUp(self): def resetScript(script): if script.elf is not None: script.elf.gameOver = True script.mutex.acquire() script.lastAliveTime = 0 script.mutex.release() script.elf = None return def openWindowAndRun(windowName, script, dm): def isScriptNeedRestart(): print '-- alive time is' + str(time.time() - script.lastAliveTime) if script.elf is not None and script.elf.gameOver is True: resetScript(script) sendToServer(windowName + ': restart for gameOver') return True elif script.lastAliveTime == 0: sendToServer(windowName + ': restart for lastAliveTime is zero') return True elif time.time() - script.lastAliveTime > 25 * 60: sendToServer(windowName + ': restart for script timeout') dm.Capture(0, 0, 800, 600, 'f:/timeoutPic/' + str(time.time()) + '.bmp') resetScript(script) return True else: return False commandFile = open('c:/anjianScript/' + windowName + '.txt', 'r') command = commandFile.readline() commandFile.close() state, chapter, aimEnergy, isRush = command.split(' ') print state, chapter, aimEnergy, isRush if state == "0": if script.lastAliveTime is not 0 and script.elf is not None: script.elf.gameOver = True script.mutex.acquire() script.lastAliveTime = 0 script.mutex.release() sendToServer(windowName + " has stopped.(full)") return True elif state == "1": if isScriptNeedRestart(): # 运行到初始状/态 ret = self.startWindow(windowName, int(chapter)) if ret: print u'窗口启动成功' script.mutex.acquire() script.lastAliveTime = time.time() script.mutex.release() else: print u'窗口启动失败' return False elf = 0 script.dm = dm evalString = 'ExpElf.ExpElf(self.m.dm_' + windowName + ',"' + windowName + '",' + chapter + ',' + aimEnergy + ',isRush = ' + isRush + ',script=script)' print evalString elf = eval(evalString) script.elf = elf t1 = threading.Thread(target=elf.runUp) script.threadEntity = t1 t1.start() return True else: # f = open('d:/lastAliveTimegap.txt','a') # print >>f, time.time() - script.lastAliveTime # f.close() return True client = Client.Client() thread_client = threading.Thread(target=client.sendHeartbeat) thread_client.start() while True: ret = openWindowAndRun("xiaohao", self.xiaohaoScript, self.m.dm_xiaohao) if not ret: continue ret = openWindowAndRun("dahao", self.dahaoScript, self.m.dm_dahao) if not ret: continue sleep(10.0)