def register(self): '''init connection and login a exist user''' if not isinstance(self.conn, socket.socket): return False, 'Not Connected to server'.title() conn = self.conn msg = Message(kind=kind_register, sender=self.username, receiver='') try: conn.sendall(msg.inBytes) except socket.error: print( '{}, RegisterError, can not send RegisterReq to server'.format( localtime())) return False, 'RegisterError, can not send RegisterReq to server' data = conn.recv(1024) try: msg = Message.ParseBytes(data) except: print('{}, RegisterError, failed to parse server response'.format( localtime())) return False, 'RegisterError, failed to parse server response' print(msg) if msg.kind == kind_register and msg.token and isinstance( msg.token, str) and msg.info == 'ok': print('{}, RegisterAndLoginSuccess, token is {}'.format( localtime(), msg.token)) self.token = msg.token self.online = True self.conn = conn, 'RegisterAndLoginSuccess' return True self.conn = None self.token = None conn.close() return False, 'Register Failed'
def relative_time(self, date): delta = gmtime() - gmtime(date) if delta <= 1: return lang.html_about_second elif delta <= 45: return lang.html_second % delta elif delta <= 90: return lang.html_about_minute elif delta <= 60 * 45: return lang.html_minute % math.ceil(delta / 60.0) elif delta <= 60 * 60 * 1.5: return lang.html_about_hour elif delta <= 60 * 60 * 20: return lang.html_hour % math.ceil(delta / (60.0 * 60.0)) elif delta <= 60 * 60 * 24 * 1.5: return lang.html_about_day elif delta <= 60 * 60 * 48: return lang.html_yesterday elif delta <= 60 * 60 * 72: return lang.html_day % math.ceil(delta / (60.0 * 60.0 * 24.0)) else: return time.strftime(lang.html_exact, localtime(date))
def heart_beat(self): '''send heart beat package every 5 s''' while self.flag: if self.conn is None: print('{}, NoConnection, heartbeat skip.'.format(localtime())) continue if self.token is None: print('{}, NoToken, heartbeat skip.'.format(localtime())) msg = Message(kind=kind_heartbeat, sender=self.username, receiver='', token=self.token) try: self.q.put_nowait((8, msg)) except socket.error: self.online = False time.sleep(5)
def init_connect(self): conn = socket.socket() try: conn.connect((host, port), ) except socket.error: print('{}, ConnectionError, can not connect to server'.format( localtime())) return False, 'ConnectionError, can not connect to server' data = conn.recv(1024) try: msg = Message.ParseBytes(data) except: print('{}, RegisterError, failed to parse server response'.format( localtime())) return False, 'RegisterError, failed to parse server response' print(msg) self.conn = conn return True, 'Connected'
def absolute_time(self, date, message=False): delta = gmtime() - gmtime(date) date = localtime(date) if delta <= 60 * 60 * 24: return time.strftime(lang.html_time_message if message \ else lang.html_time, date) else: return time.strftime(lang.html_time_day_message if message \ else lang.html_time_day, date)
def send(self): '''send msg in the queue one by one''' while self.flag: if self.token is None or self.conn is None or self.online is False: continue if self.q.empty(): continue if not self.online: self.re_login_with_token() # send re login request continue _, msg = self.q.get() print(_, msg) print(msg.kind) if msg.kind == kind_emotion: self.store_new_messages(msg) try: self.conn.sendall(msg.inBytes) except socket.error: print('{}, FailedToSendMsg: {},{}, {}'.format( localtime(), msg.kind, msg.info, localtime(msg.timestamp))) pass
def login(self): if not isinstance(self.conn, socket.socket): return False, 'Not Connected to server'.title() conn = self.conn # send to server username msg = Message(kind=kind_login, sender=self.username, receiver='') try: conn.sendall(msg.inBytes) except socket.error: print('{}, LoginError, can not send LoginReq to server'.format( localtime())) return False, 'LoginError, can not send LoginReq to server' # receive server response to login req data = conn.recv(1024) # print('receive server response to login req', data) try: msg = Message.ParseBytes(data) except: print('{}, LoginError, failed to parse server response'.format( localtime())) print(str(data, encoding='utf-8')) return False, 'LoginError, failed to parse server response' print(msg) if msg.kind in [kind_login, kind_register] and msg.token and isinstance( msg.token, str) and msg.info == 'ok': print('{}, LoginSuccess, token is {}'.format( localtime(), msg.token)) self.token = msg.token self.online = True self.conn = conn return True, 'LoginSuccess' self.conn = None self.token = None conn.close() return False, msg.info
def receive(self): while self.flag: if self.token is None or self.conn is None: continue try: data = self.conn.recv(1024) except socket.error: continue try: msg = Message.ParseBytes(data) except (TypeError, ValueError): continue if msg.kind == kind_relogin and msg.info == info_ok: print('{}, ReLogin success!'.format(localtime())) self.online = True if msg.kind == kind_heartbeat and msg.info == info_ok: print('{}, HeartBeat from server'.format(localtime())) if msg.kind == kind_get_all_users: self.friends.update(msg.info) if msg.kind == kind_emotion: self.store_new_messages(msg)
def re_login_with_token(self): if self.online is False and self.token: if self.conn is not None: self.init_connect() conn = self.conn msg = Message(kind=kind_relogin, sender=self.username, receiver='', token=self.token) try: conn.sendall(msg.inBytes) except socket.error: print('{}, ReLoginError, can not send ReLoginReq to server'. format(localtime())) return False self.conn = conn return True return False
def handle(self): c = self.request print(localtime(), c) try: message = Message(kind=server_ask_username, sender=server_name, receiver='', info=welcome_msg) c.sendall(message.inBytes) except: c.close() return try: data = c.recv(1024) except: c.close() return try: message = Message.ParseBytes(data) except: self.__send_data_close(c, invalid_msg) return # print(message, users) user_name = message.sender # print('check', message.kind) # 处理用户登陆 if message.kind == 'Login': self.login(c, user_name) # 处理用户注册 elif message.kind == kind_register: self.register(c, user_name) # 处理已登陆用户重联 --- 用户不稳定的网络 elif message.kind == kind_relogin: result = self.re_login_with_token(c, message.sender, message.token) if result is not True: self.__send_data_close(c, invalid_token) return else: if not self.__send_data(conn=c, info='ok', kind=kind_relogin): c.close() return else: self.__send_data_close(c, invalid_msg) return while True: if running is not True: break try: data = c.recv(1024) except: self.logout(user_name) break try: message = Message.ParseBytes(data) except: continue sender = message.sender info = message.info receiver = message.receiver kind = message.kind status = message.status token = message.token if token is None: self.__send_data_close(c, invalid_token) break if token not in token_user_map: self.__send_data_close(c, invalid_token) break # 心跳 if kind == kind_heartbeat: if token in token_user_map \ and token_user_map[token].token == token \ and sender == token_user_map[token].username: self.__send_data(c, 'ok', 'HeartBeat') else: self.__send_data_close(c, invalid_token) break # 用户登出 if kind == kind_exit: self.logout(user_name) break # 获取用户列表和用户状态 if kind == kind_get_all_users: self.__send_data(conn=c, info=json.dumps(self.users_status_batch), kind=kind) continue # 获取某个用户的状态 if kind == kind_get_user_status: self.__send_data(c, self.check_user(info), kind) continue # p2p chat if kind == kind_p2p_chat: receiver = users[receiver] self.__send_data(receiver.conn, info=info, kind=kind) # todo: the partner offline ############################################################### # 用户情绪 ############################################################### if kind == kind_emotion: # emotions.append(message) sender_ = users[sender] if sender_.occupation == 'student': teacher = users['teacher'] self.__send_data( teacher.conn, info={ 'talk': message.info, 'mood': ai_api(message) # 利用ai把学生的发言分析成-1,0, +1中的一个,并发送给教师端 }, kind=kind_emotion, sender=sender ) print(teacher, teacher.conn,) elif sender_.occupation == 'teacher': if not receiver: continue student = users[receiver] self.__send_data( student.conn, info=message.info, kind=kind_emotion, sender=sender )
self.shadow_ratio = self.eclipsed * 100 / self.measure_points total = criteria.Score() total.add(Pass.shadow_crit, self.shadow_ratio) total.add(Pass.max_alt_crit, rad2deg(self.max_alt)) total.add(Pass.max_sun_alt_crit, rad2deg(self.max_sun_alt)) self.score = total.score() def shadow_ratio(self): return if __name__ == '__main__': from data import reto, iss sun = ephem.Sun() observer = reto sat = iss for start, end in risings(observer, sat, ephem.now(), ephem.now() + 14): p = Pass(sat, observer, start, end) if p.score > 70: start = localtime(p.start) end = localtime(p.end) print "%s - %s: sh=%i alt=%i sun=%i score=%i%%" % \ (start.strftime("%Y-%m-%d %H:%M:%S"), end.strftime("%H:%M:%S"), \ p.shadow_ratio, rad2deg(p.max_alt), rad2deg(p.max_sun_alt), p.score)
def train_validate(self, epoch, is_train=True): batch_time = AverageMeter() data_time = AverageMeter() losses = AverageMeter() # switch to train mode if is_train: self.model.train() curr_iter = epoch * len(self.train_loader) data_loader = self.train_loader else: self.model.eval() curr_iter = epoch * len(self.valid_loader) data_loader = self.train_loader end = time.time() dataset_length = len(data_loader) for bid, data in enumerate(data_loader): # measure data loading time data_time.update(time.time() - end) inputs, targets = data if self.args.cuda: inputs, targets = inputs.cuda(), targets.cuda() inputs, targets = Variable(inputs), Variable(targets) # compute output outputs = self.model(inputs) loss, main_loss = self.model_loss(outputs, targets) # compute gradient and do SGD step if is_train: self.optimizer.zero_grad() if self.args.multi_gpu: record_loss = main_loss.data.mean() loss.mean().backward() else: record_loss = main_loss.data loss.backward() # record loss losses.update(record_loss, inputs.size(0)) # torch.nn.utils.clip_grad_norm(model.parameters(), args.clip_gradient) self.optimizer.step() else: if self.args.multi_gpu: record_loss = main_loss.data.mean() else: record_loss = main_loss.data # record loss losses.update(record_loss, inputs.size(0)) # measure elapsed time batch_time.update(time.time() - end) end = time.time() if is_train: log_prefix = '{0}\tEpoch: [{1}] [{2}/{3}]'.format( localtime(), epoch, bid, dataset_length) else: log_prefix = '{0}\tValid: [{1}/{2}]'.format( localtime(), bid, dataset_length) if bid % self.args.log_interval == 0 or bid == (dataset_length - 1): print('{}\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Data {data_time.val:.3f} ({data_time.avg:.3f})\t' 'Loss {loss_val:.4f} ({loss_avg:.4f})\t'.format( log_prefix, batch_time=batch_time, data_time=data_time, loss_val=losses.val, loss_avg=losses.avg, )) if self.args.vis_loss and is_train: self.writer.add_scalar('train', losses.val, curr_iter) elif self.args.vis_loss and not is_train: self.writer.add_scalar('eval', losses.val, curr_iter) if is_train and self.args.lr_scheduler_iter: self.scheduler.step() curr_iter += 1 return losses.avg