def testHandlersDeleteNonIntID(self): for e in self._handlerCollection: if 0 <= 1 < len(e) and e[1] == 'requiresIDInConstructor': inst = e[0](Client(), 999) else: inst = e[0](Client()) self.assertRaises(SDKInvalidArgException, inst.delete, '')
def addNewUser(self): """ the client comes into the system as a Bernoulli(p) process """ if self.continuous_class: if np.random.rand() < self.Lambda/self.num_avg_task: num_task = np.random.geometric(p=1/self.num_avg_task) reward_vec = np.random.rand(2) # assume server 1 has the higher payoff among the two reward_vec = reward_vec if reward_vec[0] > reward_vec[1] else np.flip(reward_vec) self.clients[self.client_tag] = Client(self.client_tag, num_task, self.num_server, reward_vec) self.client_tag += 1 self.num_clients += 1 self.num_client_in += 1 if self.verbose: print("Add (client, # task, time) = ({}, {}, {}) ".format(self.client_tag, num_task, self.time_slot)) else: for c_label, rate in enumerate(self.lambda_i): # if np.random.rand() < rate: if self.user_in_rate[c_label, self.time_slot] < rate: self.num_total_class_client[c_label] += 1 num_task = np.random.geometric(p=1/self.num_avg_task) reward_vec = self.reward_matrix[c_label, :] self.clients[self.client_tag] = Client(c_label, num_task, self.num_server, reward_vec) self.client_tag += 1 self.num_clients += 1 self.num_client_in += 1 self.num_class_client[c_label] += 1 if self.verbose: print("Add (client, # task, time) = ({}, {}, {}) ".format(self.client_tag, num_task, self.time_slot))
def __init__(self): # init Client self.client = Client("marco", "localhost", 59001) self.client.listen() self.client2 = Client("MARCO BIS", "localhost", 59001) self.client2.listen() # définir une clock self.clock = pygame.time.Clock() self.FPS = 60 # générer la fenetre du jeu pygame.display.set_caption("World War Worms") self.screen = pygame.display.set_mode((1080, 720)) # Charger l'arrière plan self.background = pygame.image.load('assets/background.jpg') # importer charger notre bannière self.banner = pygame.image.load('assets/banner.png') self.banner = pygame.transform.scale(self.banner, (500, 500)) self.banner_rect = self.banner.get_rect() self.banner_rect.x = math.ceil(self.screen.get_width() / 4) # importer charger notre bouton pour lancer la partie self.play_button = pygame.image.load('assets/button.png') self.play_button = pygame.transform.scale(self.play_button, (400, 150)) self.play_button_rect = self.play_button.get_rect() self.play_button_rect.x = math.ceil(self.screen.get_width() / 3.33) self.play_button_rect.y = math.ceil(self.screen.get_height() / 2) self.game = Game(self.client, self.client2)
def testHandlersCreateEmptyFields(self): for e in self._handlerCollection: if 0 <= 1 < len(e) and e[1] == 'requiresIDInConstructor': inst = e[0](Client(), 999) else: inst = e[0](Client()) self.assertRaises(SDKInvalidArgException, inst.create, {})
def testHandlersAllNonArrFilters(self): for e in self._handlerCollection: if 0 <= 1 < len(e) and e[1] == 'requiresIDInConstructor': inst = e[0](Client(), 999) else: inst = e[0](Client()) self.assertRaises(SDKInvalidArgException, inst.all, '')
def crearEntitat(self, time): prob = randint(1, 100) if prob < self.probcapdubte: return Client(randint(0, 1), time) elif prob < self.probpocsdubtes: return Client(randint(2, 3), time) else: return Client(randint(4, 5), time)
def testEntityListBadRespMissingCollection(self): req = APIRequest(Client(), '/any/method', 'GET') req.call = MagicMock(return_value={ 'data': '{"meta": {"pagination": {}}}', 'status': 200 }) self.assertRaisesRegex(SDKUnexpectedResponseException, 'collection', EntityList, Client(), req, 'X')
def start_client(self): if ((self.name_label != None) and (self.password_label != None) and (self.connection_label != None)): self.client = Client(self, self.name_label.get(), self.password_label.get(), '127.0.0.1', int(self.connection_label.get())) else: self.client = Client(self) self.client.chat()
def test_send_money_between_clients(self): bank = Bank("TEST") client1 = Client("TEST") client2 = Client("TEST2") bank.add_client(client1) bank.add_client(client2) bank.deposit(client1, 100) bank.send_money_between_clients(client1, client2, 100) self.assertEqual(100, client2.money)
def launchBBB(): original = client("Original") # This is the source of all money!!! # make the first transaction to this account # just a few other clients client_1 = Client("mannsi") client_2 = Client("caro") client_3 = Client("chuck_norris") client_4 = Client("Alpha")
def __init__(self): self.Alice = Client() self.Alice.open_connection() self.Bob = Client() self.Bob.open_connection() self.Eve = Client() self.Eve.open_connection() self.alice_stolen_password = ""
def testNetwork(): # This is the setup we have below with the port number that # each host listens on. Note that we specify both the port that # the host listens on and the port and IP of the next server in the chain # # Client -> FrontServer -> MiddleServer -> SpreadingServer -> DeadDrop # port 7776 port 7777 port 7778 port 7779 port 7780 # Client 2 # port 7775 # We can do any kind of test we want in here... initial_port = 7640 c = Client('localhost', initial_port + 1, initial_port, clientId=1) c_partner = Client('localhost', initial_port + 1, initial_port - 1, clientId=2) front = FrontServer('localhost', initial_port + 2, initial_port + 1) middle = MiddleServer('localhost', initial_port + 3, initial_port + 2) spreading = SpreadingServer([('localhost', initial_port + 4)], initial_port + 3) dead = DeadDrop(initial_port + 4) # Set the keys in the client ppk_frontServer = front.getPublicKey() ppk_middleServer = middle.getPublicKey() ppk_spreadingServer = spreading.getPublicKey() ppk_deadDropServer = dead.getPublicKey() c.chainServersPublicKeys = [ ppk_frontServer, ppk_middleServer, ppk_spreadingServer ] c.deadDropServersPublicKeys = [ppk_deadDropServer] c.partnerPublicKey = c_partner.publicKey # Configure your partner c_partner.partnerPublicKey = c.publicKey c_partner.chainServersPublicKeys = [ ppk_frontServer, ppk_middleServer, ppk_spreadingServer ] c_partner.deadDropServersPublicKeys = [ppk_deadDropServer] # Prepare the message c.newMessage("Hello Torzela!") c_partner.newMessage("Hello friend!") c.newMessage("Second round!") c.newMessage("Round three baby!") # When the next round starts, the Front Server will notify the client, # who will send the message "Hello Torzela". Right now, the message will go # through the network until it reaches the Dead Drop Server, then # it will just be sent back, so we should get "Hello Torzela!" here time.sleep(50000)
def main(): client = Client() client.connect() main_thread=threading.Thread(target=thread_pool) main_thread.daemon = True main_thread.start() client.start()
def __init__(self, epochs=20000, verbose=1, topK=20, lr=0.001, cilp_norm=0.5, data_name='ml-1m', model_name='neumf'): self.epochs = epochs self.verbose = verbose self.topK = topK self.C = cilp_norm self.lr = lr #dataset t1 = time() dataset = Dataset("./Data/" + data_name) self.num_users, self.num_items = dataset.get_train_data_shape() self.test_datas = dataset.load_test_file() self.test_negatives = dataset.load_negative_file() print("Server Load data done [%.1f s]. #user=%d, #item=%d, #test=%d" % (time() - t1, self.num_users, self.num_items, len( self.test_datas))) #model if model_name == "gmf": self.model = get_compiled_gmf_model(self.num_users, self.num_items) elif model_name == "mlp": self.model = get_compiled_mlp_model(self.num_users, self.num_items) elif model_name == "neumf": self.model = get_compiled_neumf_model(self.num_users, self.num_items) #init clients self.client = Client()
def main(): init_args() # initialize and parse the passed arguments signal.signal(signal.SIGINT, signal_handler) # Handle CTRL+C server = Server(c.OUTPUT_LOCATION).start() # Start the server # Main loop while True: scheduler = Scheduler( c.PLAYOUT_FILE) # Create a schedule using full playout file for i in scheduler.blocklist: # Play each block in the schedule for j in i.playlist: # Play each file in the block retries = 0 client = Client(j, server) ret = client.play() while ret != 0 and retries < c.MAX_SAME_FILE_RETRIES: Logger.LOGGER.log( Logger.TYPE_ERROR, "FFMPEG Return Code {}, trying again".format(ret)) ret = client.play() retries += 1 if retries >= c.MAX_SAME_FILE_RETRIES: # (if a file fails to play several times consecutively, shut down) Logger.LOGGER.log( Logger.TYPE_ERROR, "FFMPEG Return Code {}, giving up!".format(ret)) Logger.LOGGER.log( Logger.TYPE_CRIT, "{} Retries reached, exiting program!".format( c.MAX_SAME_FILE_RETRIES)) kill_process("ffmpeg") sys.exit(0)
def main(argv): type = '' path = '' port = 9000 bufferSize = 1 blockSize = 100 ip = '127.0.0.1' threadNum = 2 try: ''' -t or --type 表示类型(必须) 值:server/client -p or --path 表示文件路径(必须) 值:server端为文件路径 client端为目录 -i or --ip 表示服务器地址(客户端时必须) 值:默认本机127.0.0.1 -P or --port 表示程序要使用的端口号(可选) 值:默认9000 -T or --threadnum 表示客户端同时接收的线程数(可选) 值:默认为2 -b or --buffer 表示网络传输时的缓冲区大小(可选) 值:默认1M -n or --blocksize 表示文件的分块大小(可选) 值:默认100M ''' opts, args = getopt.getopt(argv, 't:p:P:i:T:b:n:', [ 'type=', 'path=', 'port=', 'ip=', 'threadnum=', 'buffer=', 'blocksize=' ]) except: printHelpInfo() sys.exit(-1) try: for opt, arg in opts: if opt in ('-t', '--type'): type = arg elif opt in ('-p', '--path'): path = arg if platform.system() == 'Windows': path = path.replace('\\', os.sep) else: path = path.replace('/', os.sep) if path == '': printHelpInfo() exit(-1) elif opt in ('-P', '--port'): port = int(arg) elif opt in ('-i', '--ip'): if type == 'client': ip = arg elif opt in ('-T', '--threadnum'): threadNum = int(arg) elif opt in ('-b', '--buffer'): bufferSize = int(arg) elif opt in ('-n', '--blocksize'): blockSize = int(arg) except: printHelpInfo() exit(-1) if type == 'server': s = Server(path, port, bufferSize, blockSize) s.serverTransferFileProcess() elif type == 'client': c = Client(path, ip, bufferSize, threadNum) c.receiveFileProcess() else: printHelpInfo()
def run(self): """Open a socket and adds clients to the queue.""" self.open_socket() input = [self.server, sys.stdin] running = 1 while running: # Select returns a subset of the lists that are passed to it. The # lists that are returned are lists of elements that are ready. inputready, outputready, exceptready = select.select(input, [], []) for s in inputready: if s == self.server: # A readable server socket is ready to receive a connnection. self.client, self.address = self.server.accept() print('---------\n', self.address, '\n---------\n') # Initialize a new client thread. # I'm just passing the whole object here cux WTF. c = Client(self) # Run the thread. c.start() # Add the client to the queue. self.threads.append(c) elif s == sys.stdin: # Wait until each client thread terminates junk = sys.stdin.readline() running = 0 self.server.close() for c in self.threads: print("Left it.") c.join()
def loadInitDataFromServer(self): # test try: self.client = Client() except: print("Cannot connect to server :<") os._exit(0x01) # hello self.draw() try: self.client.send(b'00', b'') while True: msg = self.client.receive() if msg[0] == 0x01: # whoami self.setPlayer(msg) elif msg[0] == 0x02: # map self.setMap(msg) elif msg[0] == 0x03: # endpoint self.setEndPoint(msg) elif msg[0] == 0x04: # players self.setOtherPlayers(msg) elif msg[0] == 0x05: # start self.running = True break else: raise Exception() except: print("Fail to load initial data from server") os._exit(0x02)
def login(username, password): select_sql = "SELECT wrong_passes FROM clients WHERE username = ?" cursor.execute(select_sql, (username, )) num_wrong_passes = cursor.fetchone() if num_wrong_passes == 5: update_sql = "UPDATE clients SET fifth_wrong_pass = ? WHERE username = ?" cursor.execute(update_sql, (datetime.now(), username)) conn.commit() num_wrong_passes = 0 return False select_time = "SELECT fifth_wrong_pass FROM clients WHERE username = ?" cursor.execute(select_time, (username, )) fifth_time = cursor.fetchone() if num_wrong_passes == 0 and (datetime.now() - fifth_time) < timedelta(minutes=5): return False else: hashed_pass = hash_password(password) select_query = "SELECT id, username, balance, message FROM clients WHERE username = ? AND password = ? LIMIT 1" cursor.execute(select_query, (username, hashed_pass)) user = cursor.fetchone() if (user): return Client(user[0], user[1], user[2], user[3]) else: num_wrong_passes += 1 update_sql = "UPDATE clients SET wrong_passes = ? WHERE username = ?" cursor.execute(update_sql, (num_wrong_passes, username)) conn.commit() return False
class main(QDialog): client = Client() filename = '' def __init__(self): super(main, self).__init__() loadUi('uploadModule.ui', self) self.setWindowTitle('File uploading!') self.submitButton.clicked.connect(self.on_submitButton_clicked) # self.submitButton.clicked.connect(self.open_selectionModule) @pyqtSlot() def on_submitButton_clicked(self): # set the file path in the lineEdit into filename self.filename = self.filePathInput.text() # self.label_2.setText(self.filename) # call the upload function in an object of Client, and use filename as input arg self.client.upload_file(self.filename) if self.client.output == "File Not Found!": self.label_2.setText(self.client.output) elif self.client.output == "SyntaxError, file path should be C:/Users/data.csv": self.label_2.setText(self.client.output) elif self.client.output == 'Pass': self.newD = SelectionModule() # once the file has been successfully read, create an object of new ui self.newD.show() # show second widget self.hide() # hide the main widget self.newD.track_label.setText(str(self.client.listOfFields))
def main(): # ----Now comes the sockets part---- start_server = input('Host new server (y/n): ') HOST = input('Enter host: ') PORT = input('Enter port: ') if not PORT: PORT = 33000 else: PORT = int(PORT) ADDR = (HOST, PORT) server = None if start_server.lower() == 'y': server = Server(HOST, PORT) server_thread = Thread(target=server.run_server()) server_thread.start() print("GOT HERE") client = Client(ADDR) root = Tk() my_gui = GUI(root, client) receive_thread = Thread(target=my_gui.update_msg) receive_thread.start() root.mainloop() server.shutdown()
def test_connect(self): server = MockServer() server.connect() client = Client() self.assertEqual(client.connect(), True) client.sock.close() server.quit()
def __init__(self, network=False): self._help_win = None self._game_win = None self._client = Client() if network else None root = Tk() root.title("Tic Tac Toe") frame = Frame(root) frame.pack() Button(frame, text='Show Help', command=self._help_callback).pack(fill=X) Button(frame, text='Play Game', command=self._play_callback).pack(fill=X) Button(frame, text='Quit', command=self._quit).pack(fill=X) scroll = Scrollbar(frame) console = Text(frame, height=4, width=50) scroll.pack(side=RIGHT, fill=Y) console.pack(side=LEFT, fill=Y) scroll.config(command=console.yview) console.config(yscrollcommand=scroll.set) self._root = root self._console = console
def main(): aQueue = Queue.Queue() HOST = "0.0.0.0" PORT = 8000 logging.basicConfig(level=logging.DEBUG) AdminThd = Admin(aQueue) AdminThd.daemon = True AdminThd.start() tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcpsock.bind((HOST, PORT)) tcpsock.listen(10) print("En écoute...") while True: (cs, (ip, port)) = tcpsock.accept() cQueue = Queue.Queue() newThread = Client(cQueue, aQueue, ip, port, cs) newThread.daemon = True settings.cThreads.append(newThread) newThread.start() AdminThd.join()
def main(): """A main garante que a classe Client seja utilizada corretamente""" turnoff = False underlying = Client() option = 0 while turnoff == False: if int(option) == 0: print( "Bem vindo ao progama da criptografia\nEscolha suas opcoes:\n") option = input( "1)Adicionar usuario\n2)Remover Usuario\n3)Checar se usuario existe\n4)Fechar\n" ) elif int(option) == 1: userInput = input("Insira o nome do usuario: ") userPassword = input("Insira a senha: ") underlying.addUser(userInput, userPassword) option = 0 elif int(option) == 2: userInput = input("Insira o nome do usuario: ") underlying.removeUser(userInput) option = 0 elif int(option) == 3: userInput = input("Insira o nome do usuario: ") print(underlying.checkUser(userInput)) option = 0 elif int(option) == 4: print("Salvando os dados criptografados...") underlying.terminate() del underlying turnoff = True else: print(print("essa opcao nao existe!")) print("Fechando...") return
async def server_handler(self, ws, path): client = Client(ws) self.CLIENTS[client.connectionId] = ws await client.OnWsConnected() try: async for msg in ws: try: jsonData = json.loads(msg) await client.OnWsReceived(jsonData) except KeyError: appConfig.log.debug("Json from %s is not valid : %s", client.connectionId, msg) except ValueError: appConfig.log.debug( "Message from %s is not valid json string : %s", client.connectionId, msg) finally: await client.OnWsDisconnected() await ws.close() self.CLIENTS.pop(client.connectionId) appConfig.log.debug('disconnect %s', client.connectionId) return ws
def __init__(self, name): self._name = name self._client = Client() self._counter = 0 root = Tk() root.title(self._name) frame = Frame(root) frame.pack() Button(frame, text='Quit', command=self._quit).pack(fill=X) Button(frame, text='Send', command=self._send).pack(fill=X) scroll = Scrollbar(frame) console = Text(frame, height=4, width=50) scroll.pack(side=RIGHT, fill=Y) console.pack(side=LEFT, fill=Y) scroll.config(command=console.yview) console.config(yscrollcommand=scroll.set) self._root = root self._console = console
def login(username, password): hashed_pass = hashlib.sha1(password.encode()).hexdigest() user = cursor.execute( '''SELECT id, username, balance, message FROM clients WHERE username = ? AND password = ?''', (username, hashed_pass)).fetchone() login_attempts = cursor.execute( 'SELECT failed_logins, id FROM clients WHERE username = ?', (username, )).fetchone() if login_attempts is None: login_attempts = 0 if user and login_attempts < 6: return Client(user[0], user[1], user[2], user[3]) else: login_attempts += 1 date_now = datetime.datetime.utcnow() timestamp_now = calendar.timegm(date_now.utctimetuple()) print(timestamp_now) print(login_attempts) id = cursor.execute('SELECT id FROM clients WHERE username = ?', (username, )).fetchone() cursor.execute( 'UPDATE clients SET failed_logins = ?, last_login = ? WHERE id = ?', (login_attempts, timestamp_now, id)) return False # Gr@b@na!!!
def fulfill_data(): dataFile = open('templates/tesm.data', 'r') data = json.load(dataFile) wagons = [] clients = [] for line in data: cl = Client(**line['client']) if cl not in clients: clients.append(cl) cl.save() merc = Ware(**line['ware']) merc.update(**{"name": cl.name}) merc.save() wag = Wagon(**line['wagon']) if wag not in wagons: wag.assignMercancia(merc) wagons.append(wag) else: for wagon in wagons: if wagon == wag: wagon.assignMercancia(merc) for wagon in wagons: wagon.save()
def run(self): try: serversocket = socket.socket( socket.AF_INET6 if self.ipmode == 6 else socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((self.host, self.port)) serversocket.listen(0) except: print("Networking failed.") os._exit(1) while True: connection, address = serversocket.accept() client = Client(self.api, address, self, SocketNetworker(connection)) client.id = len(self.clients) self.clients[client.id] = client client.sender.send({"id": client.id}) updater = ClientUpdater(self.universe, client) threading.Thread(target=client.sender.listen, daemon=True).start() self.universe.updaters.append(updater)