def on_client_connect(self, websocket, path): logging.debug("New connection from: {}".format( websocket.remote_address)) id = hash("{}{}".format(websocket.remote_address, datetime.datetime.utcnow().isoformat())) client = Client(id, websocket) if len(self.pending_clients) == (Game.NUM_CLIENTS_TO_GAME - 1): # start the game logging.debug("Start the new game") players = [client] + self.pending_clients self.pending_clients = [] asyncio.ensure_future(Game(players, self.loop).start(), loop=self.loop) logging.debug("New game session was started") else: self.pending_clients.append(client) try: yield from websocket.send(greeting(id)) while True: message = yield from websocket.recv() logging.debug("Client({}) sent an request: {}".format( id, message)) client.received_command(message) except websockets.ConnectionClosed: logging.debug("Client({}) disconnected".format(id)) if client in self.pending_clients: self.pending_clients.remove(client)
def index(): client = Client() nome = request.args.get('nome', '') if nome: clients = client.getByName(nome) else: clients = client.getAll() return render_template('client.html', clients=clients, nome=nome), 200
def redirect_client_fundtransfer(message=None): if request.method == 'GET': return render_template('client_fundtransfer.html', message=message if message is not None else None) else: self_acc = request.form['self_Client_acc'] recieving_acc = request.form['Recieving_Client_acc'] recieving_phone = request.form['Recieving_Client_phone'] Amount = request.form['Recieving_Client_Amount'] Desc = request.form['Recieving_Cient_Description'] Client.transfer_fund(self_acc, recieving_acc, recieving_phone, int(Amount), Desc) return render_template("client_fundtransfer.html")
def client_new(): if request.method == 'POST': db.create_all() data = request.form.to_dict() data['slug'] = Utils.slugify(data['name']) exist = Client.query.filter_by( name=data['name']).first() or Client.query.filter_by( slug=data['slug']).first() or Client.query.filter_by( email=data['email']).first() if (exist): flash('This user already exists!', 'danger') return render_template('client_new.html') else: data = Utils.simplifyClient(data) if (request.files and request.files['image']): data['profile'] = Utils.uploadImage('profiles', newname=data['slug']) client = Client(data) db.session.add(client) db.session.commit() flash('New client profile was created successfully.', 'success') return redirect(url_for('clients')) diets = Diet.query.with_entities(Diet.id, Diet.name).all() return render_template('client_new.html', diets=diets)
def add(): title = 'Cadastrar Usuário' form = ClientForm(request.form) if form.estado.data != 'None': form.estado.choices = [(form.estado.data, estados[form.estado.data])] if form.cidade.data != 'None': form.cidade.choices = [(form.cidade.data, form.cidade.data)] if form.validate_on_submit(): cliente_ = Client() cliente_.getByLogin(form.login.data) if cliente_.id: flash('O login informado já existe na base de dados', 'warning') else: client = Client( form.nome.data, form.endereco.data, form.numero.data, form.observacao.data, form.cep.data, form.bairro.data, form.cidade.data, form.estado.data, form.telefone.data, form.email.data, form.login.data, bcrypt.generate_password_hash(form.senha.data), form.grupo.data, ) ret = client.insert() flash(ret, 'info') return redirect(url_for('client.edit', id=client.id)) return render_template('client_form.html', form=form, title=title), 200
def index(): order = Order() user_id = request.args.get('user', None) client = Client() clients = client.getAll() if session.get('user_grupo', '') != 'user': if user_id: orders = order.getByUser(user_id) else: orders = order.getAll() else: orders = order.getByUser(session.get('user_id', '')) return render_template('order.html', orders=orders, clients=clients, user_id=user_id), 200
def emp_add(): if request.method == 'GET' and session['email'] != None: return render_template('clientRegis.html') else: # _id, password, name, contact_number, gender, email, date_of_birth, date_of_joining = None, money = None, desc = None name = request.form['Client_name'] global tempvalue_reg tempvalue_reg = name password = request.form['Client_pass'] Gender = request.form['Client_gender'] Contact_number = request.form['Client_pno'] _id = request.form['Client_ID'] Date_of_Birth = request.form['Client_DoB'] email = request.form['Client_mail'] client = Client(_id, password, name, Contact_number, Gender, email, Date_of_Birth) client.save_to_mongo() # message = "Successful" return render_template('reg_captcha.html', message="Successfull")
def index(): form = LoginForm(request.form) if form.validate_on_submit(): user = Client() user.getByLogin(form.login.data) if not user.id: flash('Credenciais inválidas') return redirect(url_for('login.index')) if bcrypt.check_password_hash(user.senha, form.password.data): session.clear() session.permanent = True session['user_id'] = user.id session['user_nome'] = user.nome session['user_login'] = user.login session['user_grupo'] = user.grupo return redirect(url_for('home.index')) else: flash('Credenciais inválidas') return render_template('login.html', form=form), 200
def main(): client = Client("Ana", 20, "ana@ana") clientrepository = ClientRepository() account = Account(1234, 20000, client) accountrepository = AccountRepository() clientrepository.save(client) accountrepository.save(account) print("clientes") clientrepository.get() print("cuentas") accountrepository.get()
def delete(id): client = Client() ret = client.get(id) if not client.id: flash(ret, 'info') return redirect(url_for('client.index')) order = Order() has = order.hasByUser(session.get('user_id')) if has: flash( 'O usuário não pode ser deletado pois existe algum pedido relacionado à ele.', 'info') return redirect(url_for('client.index')) if request.method == 'POST': ret = client.delete() flash(ret, 'info') return redirect(url_for('client.index')) title = 'Deseja realmente deletar o usuário ' + client.nome + '?' return render_template('client_delete.html', clientId=id, title=title), 200
def login_client(): name = request.form['Client_name'] password = request.form['Client_pass'] client = Client.from_name(name) global tempvalue tempvalue = name # print(User.login_vaild(email,password)) if client is not None: if client.password == password: session['email'] = client.email return render_template('login_captcha.html', target="blank") else: session['email'] = None return render_template('home.html', target="blank")
def delete_client(): name = request.form['Client_name'] account = request.form['Client_account'] pno = request.form['Client_pno'] client = Client.from_id(name) client.delete_client(name) # print(User.login_vaild(email,password)) if client is not None: if client.account_number == account: client.delete_client(name) session['email'] = client.email return render_template('delete-client.html') else: session['email'] = None return render_template('delete-client.html', message="Failed")
print('Data finished...') # load global model net_glob = CNNCifar(args=args).to(args.device) if args.dataset == 'cifar' else CNNMnist(args=args).to(args.device) net_glob.train() # parameters w_glob = net_glob.state_dict() # test each of clients test_acc = [0 for i in range(args.num_users)] test_loss = [0 for i in range(args.num_users)] for idx in range(args.num_users): # every time start with the same global parameters net_glob.load_state_dict(w_glob) client = Client(args=args, dataset=train_set, idxs=dict_users_train[idx], bs=args.train_bs) w_client = client.local_train(net=copy.deepcopy(net_glob).to(args.device)) client = Client(args=args, dataset=test_set, idxs=dict_users_test[idx], bs=args.test_bs) net_glob.load_state_dict(w_client) test_acc[idx], test_loss[idx] = client.test(net=copy.deepcopy(net_glob)) print('\nAvg test acc = ({:.3f}%), Avg test loss = {:.3f}\n'.format(np.sum(np.array(test_acc)) / args.num_users , np.sum(np.array(test_loss)) / args.num_users)) print('\nMin acc = {:.3f}, max acc = {:.3f}\n'.format(np.min(np.array(test_acc)), np.max(np.array(test_acc)))) plt.figure() plt.plot(range(100), test_acc, 'o') plt.ylabel('Test accuracy') plt.xlabel('Client') plt.savefig('./save/local_train_test.png')
net_glob.train() # parameters w_glob = net_glob.state_dict() loss_train = [] # meta-learning for global initial parameters for epoch in range(args.meta_epochs): loss_locals = [] w_locals = [] m = max(int(args.frac * args.num_users), 1) idxs_users = np.random.choice(range(args.num_users), m, replace=False) for idx in idxs_users: client = Client(args=args, dataset=train_set, idxs=dict_users_train[idx], bs=args.train_bs) w, loss = client.reptile( net=copy.deepcopy(net_glob).to(args.device)) w_locals.append(copy.deepcopy(w)) loss_locals.append(copy.deepcopy(loss)) # update global weights w_glob = FedAvg(w_locals) # copy weight to net_glob net_glob.load_state_dict(w_glob) # print loss loss_avg = sum(loss_locals) / len(loss_locals) if (epoch + 1) % 50 == 0: print('Round {:3d}, Average loss {:.3f}'.format(
def redirect_client_account_summary(message=None): client = Client.from_email(session['email']) print(client) return render_template('client_accountsummary.html', message=message if message is not None else None, client=client)
def edit(id): title = 'Editar Usuário' client = Client() ret = client.get(id) if not client.id: flash(ret, 'info') return redirect(url_for('client.index')) if session.get('user_id', None) != id and session.get('user_grupo', None) != 'admin': flash('Você não tem permissão para este recurso', 'danger') return redirect(url_for('home.index')) if request.form: form = ClientForm() client.nome = form.nome.data client.telefone = form.telefone.data client.endereco = form.endereco.data client.numero = form.numero.data client.cep = form.cep.data client.bairro = form.bairro.data client.observacao = form.observacao.data client.email = form.email.data client.cidade = form.cidade.data client.estado = form.estado.data #client.login = form.login.data client.grupo = form.grupo.data if form.senha.data != '': client.senha = bcrypt.generate_password_hash(form.senha.data) if form.login.data != client.login: cliente_ = Client() cliente_.getByLogin(form.login.data) if cliente_.id: flash('O login informado já existe na base de dados', 'warning') return redirect(url_for('client.edit', id=client.id)) else: client.login = form.login.data else: form = ClientForm() form.login.data = client.login form.grupo.data = client.grupo form.nome.data = client.nome form.telefone.data = client.telefone form.endereco.data = client.endereco form.numero.data = client.numero form.cep.data = client.cep form.bairro.data = client.bairro form.observacao.data = client.observacao form.email.data = client.email if client.estado: form.estado.choices = [(client.estado, estados[client.estado])] if client.cidade: form.cidade.choices = [(client.cidade, client.cidade)] form.senha.validators = [] if form.validate_on_submit(): ret = client.update() flash(ret, 'info') return redirect(url_for('client.edit', id=client.id)) return render_template('client_form.html', form=form, title=title, clientId=id), 200
def admin_view_clients_templateas(message=None): clients = Client.all_clients() return render_template('viewclients.html', message=message if message is not None else None, clients=clients)
def view_clients_templateas(message=None): client = Client.from_email(session['email']) return render_template('client_accountsummary.html', message=message if message is not None else None, client=client)
if s == "exit": print(log.server_closed + get_time()) server.close() os._exit(1) break elif s == "send": # This cmd is just for test sid = input("session_id?") title = input("title?") content = input("content?") img_url = input("img_url?") send_to(sid, Message(title, content, img_url)) elif s == "send2all": title = input("title?") content = input("content?") img_url = input("img_url?") send_to_all(Message(title, content, img_url)) server = PPNServer(HOST, PORT).run() # Run PPN Server if __name__ == "__main__" and server is not None: threading.Thread(target=get_input, args=[]).start() while True: if MAX_CLIENT == -1 or len(common.clients) <= MAX_CLIENT: c, a = server.accept() # A new client connected. session_id = c.recv( 1024).decode() # First sent message from client is session_id common.clients.append(Client( c, a, session_id)) # Add new client to clients list. else: # Max clients reached print(log.max_client + log.triple_dots + "." + get_time())
async def get_by_pk(cls, client_pk: int) -> Optional["Client"]: row = await cls.pool.fetch(cls.SELECT_BY_ID, client_pk) print(row) return Client(*(row[0])) if row else None