async def main(): s1 = Sender("Sender 1", 4) s2 = Sender("Sender 2", 4) c = Channel() r1 = Receiver("Receiver 1") r2 = Receiver("Receiver 2") frames1 = [] frames2 = [] for _ in range(11): f = Frame() f.source_address = "Sender 1" f.destination_address = "Receiver 1" f.packFrame() frames1.append(f) for _ in range(11): f = Frame() f.source_address = "Sender 2" f.destination_address = "Receiver 2" f.packFrame() frames2.append(f) t1 = asyncio.create_task(s1.send(frames1, c)) t2 = asyncio.create_task(r1.conn(c)) t3 = asyncio.create_task(s2.send(frames2, c)) t4 = asyncio.create_task(r2.conn(c)) await t1 await t2 await t3 await t4
async def main(): s1 = Sender("Sender 1") r1 = Receiver("Receiver 1") s2 = Sender("Sender 2") r2 = Receiver("Receiver 2") c = Channel() f1 = Frame() f3 = Frame() f5 = Frame() f1.source_address = "Sender 1" f1.destination_address = "Receiver 1" f3.source_address = "Sender 1" f3.destination_address = "Receiver 1" f5.source_address = "Sender 1" f5.destination_address = "Receiver 1" f2 = Frame() f4 = Frame() f2.source_address = "Sender 2" f2.destination_address = "Receiver 2" f4.source_address = "Sender 2" f4.destination_address = "Receiver 2" frames1 = [f1.packFrame(), f3.packFrame(), f5.packFrame()] frames2 = [f2.packFrame(), f4.packFrame()] t1 = asyncio.create_task(s1.send(frames1, c)) t2 = asyncio.create_task(r1.conn(c)) t3 = asyncio.create_task(s2.send(frames2, c)) t4 = asyncio.create_task(r2.conn(c)) await t1 await t2 await t3 await t4
def score(self): def is_last_frame(i): return 9 == i def score_strike(i): return (20 + self.frame10ball3 if is_last_frame(i) else 10 + self.frames[i + 1].first_ball + self.frames[i + 1].second_ball) def score_spare(i): return (10 + self.frame10ball3 if is_last_frame(i) else 10 + self.frames[i + 1].first_ball) for i, frame in enumerate(self.frames): if frame.is_strike(): self.frames[i] = Frame( (frame.first_ball, frame.second_ball, score_strike(i))) elif frame.is_spare(): self.frames[i] = Frame( (frame.first_ball, frame.second_ball, score_spare(i))) else: self.frames[i] = Frame(( frame.first_ball, frame.second_ball, frame.first_ball + frame.second_ball, )) return sum([frame.frame_score for frame in self.frames])
def channel_to_receiver(data): global old_frame global win_not_done global seq_no temp = pickle.loads(data['data']) frame_no = temp.payload['seq_no'] % 4 if win_not_done: print(frame_no, seq_no[frame_no]) if seq_no[frame_no] is None: # TODO Corruption Check if crc_check(temp.payload["data"], temp.crc): print(f"Received from channel : {temp}") old_frame = temp.payload['seq_no'] ack_frame = Frame() seq_no[frame_no] = 1 ack_frame.payload['seq_no'] = temp.payload['seq_no'] ack_frame.payload['nak'] = False sio.emit('receiver-to-channel', {'data': pickle.dumps(ack_frame)}) else: ack_frame = Frame() ack_frame.payload['seq_no'] = temp.payload['seq_no'] ack_frame.payload['nak'] = True sio.emit('receiver-to-channel', {'data': pickle.dumps(ack_frame)}) else: print("Packet Discarded") ack_frame = Frame() ack_frame.payload['seq_no'] = temp.payload['seq_no'] ack_frame.payload['nak'] = False sio.emit('receiver-to-channel', {'data': pickle.dumps(ack_frame)}) if seq_no[0] and seq_no[1] and seq_no[2] and seq_no[3]: print("Window Successful") win_not_done = True seq_no = [None, None, None, None]
def calibrate(self, amount_of_frames): """ Calibrates the camera by snapping x amount of images and rotating them according to the smoothed angle """ calibration_frames = [] angle_array = [None] for i in xrange(0, amount_of_frames, 1): frame, angle_array = self.snap_calibration_frame(angle_array) calibration_frames.append(frame.frame) smoothed_angle, group_size = self.smooth_angle(angle_array, 1.5) if group_size < len(angle_array) - 1: return False total_frame = None for i in xrange(0, amount_of_frames, 1): calibration_frames[i] = calibration_frames[i].rotate_frame( smoothed_angle) canny = self.snap_canny(calibration_frames[i].frame) if i > 0: total_frame += canny.frame else: total_frame = canny.frame total_frame_blurred = Frame(cv2.blur(total_frame, (4, 4), 0)) total_frame_blurred = total_frame_blurred.binary(60, 255) self._reference_canny = Frame(total_frame_blurred) self._reference = Frame(calibration_frames[amount_of_frames - 1].frame) return True
def __init__(self, order, name, a=Frame(True), b=Frame(True)): assert type(order) is int or order is None assert type(name) is str or not name self.name = name self.frame = [copy.deepcopy(a), copy.deepcopy(b)] self.default = [None, None] self.inter = False self.noswap = False self.order = order
def simulator3(RUN_COUNT=100): #f = Frame() f1 = Frame() f2 = Frame() FRAME_TIME = 10 #player1 = Player.create(f, random.randrange(WIDTH), random.randrange(HEIGHT)) #player2 = Player.create(f, random.randrange(WIDTH), random.randrange(HEIGHT)) player1 = Player.create(f1, random.randrange(WIDTH), random.randrange(HEIGHT)) player2 = Player.create(f1, random.randrange(WIDTH), random.randrange(HEIGHT)) #player1.id = 1 #player2.id = 2 #cli1 = Client_player(f, player1, player2, 0) #cli2 = Client_player(f, player2, player1, 50) cli1 = Client_player(f1, player1, player2, p1_latency) cli2 = Client_player(f1, player2, player1, p2_latency) cli1.connectClient(cli2) cli2.connectClient(cli1) #gc = Client(f, player1, player2, 5) #print('f1: {}, f2:{}'.format(f1, f2)) print(player1.id, player2.id) def update(): cli1.update() cli2.update() """ print("player1: (%.1f, %.1f), player2: (%.1f, %.1f)" % ( gc.players[0].x, gc.players[0].y, gc.players[1].x, gc.players[1].y)) """ f1.cvs.after(FRAME_TIME, update) #f2.cvs.after(FRAME_TIME, update) #f.cvs.after(FRAME_TIME, update) f1.cvs.after(RUN_COUNT * FRAME_TIME, f1.quit) #f2.cvs.after(RUN_COUNT * FRAME_TIME, f2.quit) #f.cvs.after(RUN_COUNT * FRAME_TIME, f.quit) update() f1.pack(fill=Tk.BOTH, expand=1) #f2.pack(fill=Tk.BOTH, expand=1) f1.mainloop() #f2.mainloop() #f.pack(fill=Tk.BOTH, expand=1) #f.mainloop() return player1, player2
def __init__(self, img, focal, K): self.poses = [] self.gt = [] self.errors = [] self.gt.append(np.eye(4)) self.scale = 1.0 self.focal = focal self.K = K self.prevFrame = Frame(img, self.focal, self.K) self.curFrame = Frame(img, self.focal, self.K) self.poses.append(self.curFrame.Rt)
def update(self, i, left_img, right_img, timestamp): # Feature extraction takes 0.12s origin = g2o.Isometry3d() left_frame = Frame(i, origin, self.cam, self.params, left_img, timestamp) right_frame = Frame(i, self.cam.compute_right_camera_pose(origin), self.cam, self.params, right_img, timestamp) frame = StereoFrame(left_frame, right_frame) if i == 0: self.initialize(frame) return # All code in this functions below takes 0.05s self.current = frame predicted_pose, _ = self.motion_model.predict_pose(frame.timestamp) frame.update_pose(predicted_pose) # Get mappoints and measurements take 0.013s local_mappoints = self.get_local_map_points(frame) print(local_mappoints) if len(local_mappoints) == 0: print('Nothing in local_mappoints! Exiting.') exit() measurements = frame.match_mappoints(local_mappoints) # local_maplines = self.get_local_map_lines(frame) # line_measurements = frame.match_maplines(local_maplines) # Refined pose takes 0.02s try: pose = self.refine_pose(frame.pose, self.cam, measurements) frame.update_pose(pose) self.motion_model.update_pose(frame.timestamp, pose.position(), pose.orientation()) tracking_is_ok = True except: tracking_is_ok = False print('tracking failed!!!') if tracking_is_ok and self.should_be_keyframe(frame, measurements): # Keyframe creation takes 0.03s self.create_new_keyframe(frame)
class serThread(Thread): serFrame = Frame() serFirstFlag = True writeFlag = False readFlag = False readStr = '' writeStr = '' newFrameFlag = False returnFrame = '' def __init__(self): print('Now Start SerialThread') Thread.__init__(self) def send(self, writeStr): self.writeStr = writeStr self.writeFlag = True # print('ser write') def FileSave(self, filename, content): import io with open(filename, "a+") as myfile: myfile.write(content) def run(self): # port = '/dev/ttyS0' # port = '/dev/ttyUSB0' # port = 'COM5' port = 'COM7' count = 0 with serial.Serial(port, 115200, timeout=0) as ser: print('serial Port:{}'.format(port)) self.serDevice = ser while True: try: time.sleep(0.001) bytesToRead = ser.inWaiting() if bytesToRead: sTemp = str(ser.read(bytesToRead), 'utf-8') self.readStr += sTemp if self.readStr.find('}') != -1: if self.serFrame.parseFrame(self.readStr): self.returnFrame = self.serFrame.frame1 self.readStr = '' self.newFrameFlag = True self.readFlag = True if self.readStr.rfind('\n') != -1: indexStr = self.readStr.rfind('\n') print(self.readStr[:indexStr], end='') self.readStr = self.readStr[indexStr:] except: print('Ser except') if self.writeFlag: ser.write(bytearray(self.writeStr, 'utf-8')) self.writeFlag = False print('End of inThread')
def main(): logging.basicConfig(filename='load_balancer.log', level=logging.INFO) logging.info('Started') #This takes input and validates it params = Params() #This is how you access the required params print params.vip_interface print params.vip_port print params.vip_ip print params.target_ip #do remember that the string eements of the list are in unicode print params.load_balancer_algorithm #After opening the socket, and receiving the entire packet in sampleFrame sampleFrame = '\x00\x02\x157\xa2D\x00\xae\xf3R\xaa\xd1\x08\x00E\x00\x00C\x00\x01\x00\x00@\x06x<\xc0\xa8\x05\x15B#\xfa\x97\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00P\x02 \x00\xbb9\x00\x00GET /index.html HTTP/1.0 \n\n' #Instantiate the frame frame = Frame(sampleFrame) try: s = socket.socket( socket.AF_PACKET , socket.SOCK_RAW , socket.ntohs(0x0003)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except ValueError: print "cant open socket" print 'socket opened' s.bind(("virtual0",0)) print 'socket binded to virtual0' logging.info('Finished')
def capture(video): cap = cv2.VideoCapture(video) frames = [] while True: ret, frame = cap.read() if ret is False: break img = cv2.resize(frame, (W, H)) frame = Frame(img, K) frames.append(frame) if len(frames) < 2: continue f1 = frames[-1] f2 = frames[-2] idx1, idx2, Rt = match_frames(f1, f2, K) f1.pose = np.dot(Rt, f2.pose) print(f1.pose) points4d = triangulate(f1.pose, f2.pose, f1.kps[idx1], f2.kps[idx2]) points4d /= points4d[:, 3:] display_frame(img, f1.kps[idx1], f2.kps[idx2]) cap.release() cv2.destroyAllWindows()
def analyze_signal(data_path): # calibrate zcr treshold Frame.zcr_treshold = calibrate_param(CALIBRATE_PATH) frames_processed = [] y_pred = [] # load data X, y, mapping = load_data(data_path) for(samples, c) in zip(X, y): print("processing") f = Frame(samples, c) f.classify_zcr() frames_processed.append(f) y_pred.append(f.prediction) cm = confusion_matrix(y, y_pred) print(accuracy_score(y, y_pred)) print(cm) plot_res(y, y_pred) signal, noise, fec, msc, over, nds = analyze_objective_params(y, y_pred) print("signal {}, noise {}, fec {}, msc {}, over {}, nds {}".format( signal, noise, fec, msc, over, nds)) return frames_processed
def receive(self, time, frame): """Receives a Frame from a channel. :time: the time that the Frame was received :frame: the frame received :returns: a tuple (ack: Frame, time_replied: int) to acknowledge a received packet """ assert frame is not None # lost frames should be not be given to this method self._current_time = time if not frame.is_error: if frame.seq_no == self._next_expected_frame: # in order frame datagram = frame.unravel() self._deliver(datagram) self._next_expected_frame = (self._next_expected_frame + 1) % self._num_seq_nos ack = Frame(self._next_expected_frame, None, 0) transmission_delay = ack.length / self._link_capacity time_replied = self._current_time + transmission_delay return ack, time_replied
def updateFrame(self): if self.useVideo or (self.files is not None and len(self.files) > 0): copyPoly = [] if self.frame is not None: copyPoly = list(self.frame.polygons) self.frame = Frame(self, self.currImage) if len(self.polygonPool) == 0 or self.useVideo: self.readInPolygons() self.setScreenGeometry() self.show() tempPoly = next((z for z in self.polygonPool if z[0] == self.files[self.currIndex]), []) if tempPoly != []: self.statusBar.showMessage('Polygons loaded from file') self.frame.polygons = list(tempPoly[2]) elif copyPoly != []: self.statusBar.showMessage( 'Polygons copied from previous frame') self.frame.polygons = list(copyPoly) self.polygonCount.setText('{0} polygons in image'.format( len(self.frame.polygons))) else: self.frame = None self.setCentralWidget(self.frame) self.setWindowTitle('Poly Annotator v0.03') pixmap = QPixmap("icon/web.png") self.setWindowIcon(QIcon(pixmap))
def process_frame(img): img = cv2.resize(img, (W, H)) frame = Frame(mapp, img, K) if frame.id == 0: return f1 = mapp.frames[-1] f2 = mapp.frames[-2] idx1, idx2, Rt = match_frames(f1, f2) f1.pose = np.dot(Rt, f2.pose) pts4d = triangulate(f1.pose, f2.pose, f1.pts[idx1], f2.pts[idx2]) pts4d /= pts4d[:, 3:] good_pts4d = (np.abs(pts4d[:, 3]) > 0.005) & (pts4d[:, 2] > 0) pts4d = pts4d[good_pts4d] for i, p in enumerate(pts4d): if not good_pts4d[i]: continue pt = Point(mapp, p) pt.add_observation(f1, idx1[i]) pt.add_observation(f2, idx2[i]) for pt1, pt2 in zip(f1.pts[idx1], f2.pts[idx2]): u1, v1 = denormalize(K, pt1) u2, v2 = denormalize(K, pt2) cv2.circle(img, (u1, v1), color=(0, 255, 0), radius=3) cv2.line(img, (u1, v1), (u2, v2), color=(255, 0, 0)) #display.paint(img) mapp.display()
def channel_to_receiver(data): global old_frame temp = pickle.loads(data['data']) if old_frame != temp.payload['seq_no']: print(f"Received from channel : {temp}") old_frame = temp.payload['seq_no'] ack_frame = Frame() if temp.payload['seq_no'] == 1: ack_frame.payload['seq_no'] = 0 else: ack_frame.payload['seq_no'] = 1 sio.emit('receiver-to-channel', {'data': pickle.dumps(ack_frame)}) else: print("Packet Discarded") ack_frame = Frame() ack_frame.payload['seq_no'] = 0 if old_frame else 1
async def recv(self): val = await asyncio.wait_for(self.in_queue.get(), timeout=5) # print(val.payload["seq_no"]) if not self.buffer: if val.payload['seq_no'] == 0: self.buffer.append(val) else: return print(self.name, " :\thas received frame with seq no.", val.payload['seq_no'], "from", val.source_address) elif self.buffer[-1].payload['seq_no'] == val.payload['seq_no']: print(self.name, " :\thas already received this frame, hence discarded.") elif (self.buffer[-1].payload['seq_no'] + 1) % 4 != val.payload['seq_no']: print(self.name, " :\tLost frame, retransmission required.") return else: print(self.name, " :\thas received frame with seq no.", val.payload['seq_no'], "from", val.source_address) self.buffer.append(val) ack = Frame() ack.setData(f"{bin(self.buffer[-1].payload['seq_no'] + 1)[2:]}") ack.source_address = self.name ack.destination_address = val.source_address print("ack", ack) # if not self.out_queue.empty(): # ? Added # del self.out_queue # ? Added # self.out_queue = Queue() # ? Added await self.out_queue.put(ack)
def sendAFrame(typ, IPA, IPB, Msg, Addr, Prt): sendFTyp = typ sendFIPA = IPA sendFIPB = IPB sendFMsg = Msg newFrame = Frame(sendFTyp, sendFIPA, sendFIPB, sendFMsg) sock.sendto(newFrame.encodeFrame(), (Addr, Prt))
def log_likelihood_exit_pattern(self, i, k): # calculate the log likelihood of frame i under a given pattern k # check if frame i is the only frame in bk if self.z[i] == k and self.partition[k] == 1: log_pzik_likelihood = np.log(self.b[k].GP_prior(self.frames[i])) # print('frame{} in pattern{} GP prior frame_ink likel: {}'.format(i, k, log_pzik_likelihood)) return log_pzik_likelihood else: frame_ink = self.frame_ink(k, i) # approximate the likelihood from the GP field generated by the N_nbr_max nearest observations # the attention is applied here by only considering maximum N_nbr_num nearest neighbors n_nbr = np.min([self.Util.N_nbr_num, len(frame_ink.x)]) points = np.vstack((frame_ink.x, frame_ink.y)).T knn = NearestNeighbors(n_neighbors=n_nbr, p=1) knn.fit(points) querry_point = np.array([self.frames[i].x, self.frames[i].y]).T n_idx = knn.kneighbors(querry_point, return_distance=False) n_idx = np.unique(n_idx) near_frame = Frame(frame_ink.x[n_idx], frame_ink.y[n_idx], frame_ink.vx[n_idx], frame_ink.vy[n_idx]) frame_i = self.frames[i] ux_pos, uy_pos, covx_pos, covy_pos, log_likelihood = self.b[ k].GP_posterior(frame_i, near_frame) # if likelihood == 0: # print('frame{} in pattern{} GP post frame_ink likel: Returning -inf'.format(i, k)) # return float("-inf") # else: if True: # print('frame{} in pattern{} GP post frame_ink likel: {}'.format(i, k, log_likelihood)) return log_likelihood
def __init__(self): """ Create a new mechanical system. """ _System.__init__(self) # _System variables need to be initialized (cleaner here than in C w/ ref counting) self._frames = tuple() self._configs = tuple() self._dyn_configs = tuple() self._kin_configs = tuple() self._potentials = tuple() self._forces = tuple() self._inputs = tuple() self._constraints = tuple() self._masses = tuple() self._hold_structure_changes = 0 self._structure_changed_funcs = [] # Hold off the initial structure update until we have a world # frame. self._hold_structure_changes = 1 self._world_frame = Frame(self, trep.WORLD, None, name="World") self._hold_structure_changes = 0 self._structure_changed()
def process_frame(img): img = cv2.resize(img, (W, H)) frame = Frame(img, k) frames.append(frame) if len(frames) <= 1: return idx1, idx2, Rt = match_frames(frames[-1], frames[-2]) frames[-1].pose = np.dot(Rt, frames[-2].pose) #homogenous 3-D COORDS pts4d = triangulate(frames[-1].pose, frames[-2].pose, frames[-1].pts[idx1], frames[-2].pts[idx2]) pts4d /= pts4d[:, 3:] #reject points behind the camera good_pts4d = (np.abs(pts4d[:, 3]) > 0.005) & (pts4d[:, 2] > 0) for i, p in enumerate(pts4d): if not good_pts4d[i]: continue pt = Point(p) pt.add_observation(frames[-1], idx1[i]) pt.add_observation(frames[-2], idx2[i]) for pt1, pt2 in zip(frames[-1].pts[idx1], frames[-2].pts[idx2]): u1, v1 = denormalize(k, pt1) u2, v2 = denormalize(k, pt2) cv2.circle(img, (u1, v1), color=(0, 255, 0), radius=3) cv2.line(img, (u1, v1), (u2, v2), color=(255, 0, 0)) disp.paint(img)
def sendSocket(arr): myFrame = Frame() # host='192.166.1.2' #my Computer Address host = '127.0.0.1' #my Computer Address port = 40007 print('hostName:{}, port:{}'.format(host, port)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) barr = bytearray(arr, 'utf-8') s.send(barr) print('Sent:{}'.format(arr)) # s.send(b'Hello, python Server') data = s.recv(1024) print('Received:{}'.format(str(data))) s.close() myFrame.parseFrame(str(data)) global receiveFlag global returnMac global returnPowerOrStatus receiveFlag = True returnMac = myFrame.returnMac returnPowerOrStatus = myFrame.returnPowerOrStatus
def load_image_file(self, direction, weapon, images, images_path, images_size): #加载图片文件夹 images[self.settings.hero_direction[direction]].append([]) for i in range(0, images_size): num = str(i) if images_size >= 10 and i < 10: num = '0' + str(i) png_image_path = 'images/' + str(weapon) + '_' + direction + '_' + images_path + '/' + images_path + num + '.png' image = pygame.image.load(png_image_path) # image = image.convert_alpha() # 想要修改透明度,必须改变图片通道 # transparent(image) # 背景透明化 # pygame.image.save(image, png_image_path) # # self.image_to_frame[image] = Frame(image, self.settings) # 描绘人物外框,并对人物图片进行修改 # pygame.image.save(image, png_image_path) # 保存图片 # frame = Frame(image, self.settings) # frame_path = "frames/frame/"+str(self.frame_num) + ".txt" frame_rect_path = "frames/frame_rect/" + str(self.frame_num) + ".txt" self.frame_num += 1 # with open(frame_path,'w') as file_obj: # 将人物外框事先保存在json文件中 # file_obj.write(json.dumps(frame.frame)) # 这样就不用每次开启的时候都要描绘外框 # with open(frame_rect_path,'w') as file_obj: # 减少开启的时间 # file_obj.write(json.dumps(frame.frame_rect)) # with open(frame_path,'r') as file_obj: frame_frame = json.loads(file_obj.read()) with open(frame_rect_path,'r') as file_obj: frame_frame_rect = json.loads(file_obj.read()) self.image_to_frame[image] = Frame(image, self.settings, True, frame_frame, frame_frame_rect) images[self.settings.hero_direction[direction]][weapon].append(image)
def main(): pygame.init() size = width, height = 2000, 1000 background = 196, 240, 255 frame = Frame(width=width, height=height) screen = pygame.display.set_mode(size) while 1: # handle events for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): sys.exit() if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: frame.impulse() if event.type == pygame.USEREVENT and event.collision: print("oops...") sys.exit() # step simulation frame.tick() # check state if frame.collides(): pygame.event.post( pygame.event.Event(pygame.USEREVENT, collision=True)) # refresh screen screen.fill(background) frame.paint(screen) pygame.display.flip()
def createPointInformationPacket(self): """function to build a point information request packet using speak 6 header""" header = LocalHeader(packetID.spkd_ID_POINT_INFO_REQUEST) header.setParameter("destinationTask", 0x04) header.setParameter("sourceChannelAddress", 0xFD) #values sent by consys for header replicated here header.setParameter("sourceTask", 0x92) header.IgnoreReserved(True) content = PointInformationContent() packet = Packet(header, content) frame = Frame(packet, FLG) transfer = SerialDataTransfer("COM20") reader = DataReader(transfer) reader.Start() #executes read thread to process incoming response after sent request transfer.Write(frame.getByteArray()) print(frame.getByteArray()) print("Point Information Reply\n") read(reader, transfer)
def run(ast, args=['<progname>'], check_types=False): ast = rewrite(ast, replace_nodes) log.final_ast("the final AST is:\n", ast) frame = Frame() ast.eval(frame) log.topframe("the top frame is\n", frame) if 'main' not in frame: print("no main function defined, exiting") return 0 # type inference if check_types: with frame as newframe: newframe['argc'] = Int(len(args)) newframe['argv'] = Array(map(Str, args)) main = newframe['main'] main.infer_type(newframe) assert main.type.ret == Int, \ "main() should return Int but got %s" % main.type.ret with frame as newframe: newframe['argc'] = Int(len(args)) newframe['argv'] = Array(map(Str, args)) r = newframe['main'].Call(newframe) if isinstance(r, Int): return r.to_int() else: return 0
def run(self): while True: print("Listening for frames 👂") received_frame = Frame(self.conn) print("Received frame 📥") if received_frame.opcode == 8: print("Connection Close Frame received 👋") break if received_frame.opcode == 9: print("Ping Frame received 🏓") # after a Ping Frame we have to return a Pong Frame to indicate the connection is still working pong_frame = Frame.encode_pong_frame() print("Returning Pong Frame {} 🏓".format(pong_frame)) self.conn.send(pong_frame) if received_frame.opcode == 10: print("Pong Frame received 🏓") else: print("With payload {} 💣".format(received_frame.payload)) ListenThread.last_message = received_frame.payload return_frame = Frame.encode_frame( "Thank you for your message: {}".format( received_frame.payload)) self.conn.send(return_frame) self.conn.close() print("Connection closed 👋") self.is_running = False
def assign_button(self, nums): self.button_frame_list = [] self.button_done_list, self.button_cancel_list = [], [] for idx in range(nums): button_frame = Frame(master=self.master, width=22, height=1, side=tkinter.TOP) self.button_frame_list.append(button_frame) self.button_done_list.append( ButtonDone(id=idx, master=button_frame.frame, text='{}.done'.format(idx + 1), text_box=self, window=self.window)) self.button_cancel_list.append( ButtonCancel(id=idx, master=button_frame.frame, text='{}.cancel'.format(idx + 1), text_box=self, window=self.window)) self.button_add = ButtonAdd(master=self.master, text_box=self, window=self.window)
def newFrame(): sendFrame = Frame(seq=next_frame_to_send) # 记录序列号 sendFrame.genData() # 生成随机数据 sendFrame.buildMainPart() # 合成核心部分 sendFrame.generateCRC() # 生成校验和 sendFrame.addHeadTail() # 添加帧头尾 return sendFrame