host = '' # (必填) 待拉取的服务名的访问域名, 请使用 http// 或者 https:// 开头, 比如 'http://techs.upyun.com' origin_path = '' # (必填) 待拉取的资源路径 (默认会拉取根目录下面的所有目录的文件) # -------------------------------------------- # ----------目标迁移服务名, 操作员信息------------- target_bucket = '' # (必填) 文件迁移的目标服务名 target_username = '' # (必填) 文件迁移的目标服务名的授权操作员名 target_password = '' # (必填) 文件迁移的目标服务名的授权操作员的密码 save_as_prefix = '' # (选填) 目标服务名的保存路径的前置路径 (如果不填写, 默认迁移后的路径和原路径相同) # -------------------------------------------- notify_url = '' # 将回调地址改成自己的服务器地址, 用来接收又拍云 POST 过来的异步拉取结果 # -------------------------------------------- queue = queue.LifoQueue() def push_tasks(url, up): fetch_data = [{ 'url': host + url, # 需要拉取文件的 URL 'random': False, # 是否追加随机数, 默认 false 'overwrite': True, # 是否覆盖,默认 True 'save_as': url }] if not notify_url: print('第 19 行 notify_url 参数不能为空') sys.exit(0) result = up.put_tasks(fetch_data, notify_url, 'spiderman') return result
import queue __author__ = 'Max_Pengjb' start = time.time() # 下面写上代码块 # put 进 get 出 # 队列 que = queue.Queue() que.put(1) que.put(2) a = que.get() print(a) print(que.get()) # 栈,就是个 后进先出 队列 stack = queue.LifoQueue() stack.put(3) stack.put(4) print(stack.get()) print(stack.get()) # queue.PriorityQueue() : 队列,基于优先级 q = queue.PriorityQueue(3) # 优先级,优先级用数字表示,数字越小优先级越高 q.put((10, 'a')) q.put((-1, 'b')) q.put((100, 'c')) print(q.get()) print(q.get()) print(q.get()) # 上面中间写上代码块 end = time.time()
""" Created on Mon Apr 3 12:43:47 2017 @author: thomas """ import asyncio import telnetlib import json import subprocess import queue host = "127.0.0.1" port = 54321 lq = queue.LifoQueue() async def read_msg(): reader, writer = await asyncio.open_connection(host, port) while True: data = await reader.read(2800) if data != b"": decoded = data.decode() #msgs = decoded.split("\n{\"gamestate\"") print(decoded) lq.put_nowait(decoded) #for msg in msgs: # if msg.startswith(":{\"map\":"): # rq.put_nowait(msg)
import queue from time import sleep print("queue....") #Python queue模块的FIFO队列先进先出 #队列长度可为无限或者有限。可通过queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。 q = queue.Queue(maxsize=10) #队列长度可为无限或者有限。可通过queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。 for i in range(10): q.put(i) #调用队列对象的get()方法从队头删除并返回一个项目。 for i in range(10): print(q.get()) sleep(1) print("\nLifoqueue...") #LIFO类似于堆,即先进后出 q = queue.LifoQueue(maxsize=10) for i in range(10): q.put(i) for i in range(10): print(q.get()) sleep(1) print("\n queue function....") q.qsize() q.empty() q.empty() # 在完成一项工作之后,q.task_done() 函数向任务已经完成的队列发送一个信号 q.task_done() #实际上意味着等到队列为空,再执行别的操作 q.join()
filemode='a', format='%(name)s - %(levelname)s - %(message)s') """ SCRIPT VARIABLES """ server_ports = [ 30151, 30152, 30153, 30154, 30155, 30156, 30157, 30158 ] #contains te port of each server the app connectes before-hand end_flag = 1 #Determines when to finish the simulation synch_delay = 1 #time to wait in minutes before running the script in order to synch all the clients simulation_speed = 10 #determines the speed of the vehicle in ms. This value must match with the time.sleep of the movement thread msg = "close_comm" #message sent to server when clossing socket (server must have the same config) """ QUEUE DECLARATION """ q_PoA = queue.LifoQueue() #Queue used to notify the thread_PoA_change q_receive = queue.Queue() #Queue used to notify the thread_receiver """ SETTING THE SYSTEM """ my_car_info = ScenarioReader.car_info(App_ID) my_poa_info = ScenarioReader.poa_info() vehicle_speed = my_car_info.get_vehicle_speed() vehicle_init_pos = my_car_info.get_car_initPosition() max_Distance = my_poa_info.get_coverage_area() number_APs = my_poa_info.get_number_APs() myPoA_manager = PoAManager.PoA_Manager( max_Distance, number_APs) #creates an object of the PoA_Manager class """
def __init__(self, timeout): self.__queue = queue.LifoQueue() self.__timeout = timeout
PROXY_VALIDATE_TIME = 'validateTime' # 代理网页检索起始页 FETCH_START_PAGE = 1 # 代理网页检索最大截至页 FETCH_END_PAGE = 5 # 代理池大小 PROXY_POOL_SIZE = 10 # 代理池扫描更新间隔 PROXY_POOL_SCAN_INTERVAL = 300 # 代理验证线程数 PROXY_VALIDATE_THREAD_NUM = 3 # 待验证的代理信息列表 unchecked_proxy_list = queue.LifoQueue(300) # 可用的代理池 proxy_pool = queue.Queue(100) # 标志量,是否正在扫描代理池 is_scanning = False # 代理服务守护线程 class ProxyDaemonThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): # 初始化配置 self.init()
import queue data_queue = queue.LifoQueue() data_queue.put("funding") data_queue.put(1) print(data_queue.qsize()) print(data_queue.get())
''' 队列:queue:先进先出 lifoqueue:先进后出 priorityqueue:存储数据时可以设置优先级的队列 ''' import queue queue1 = queue.Queue() queue1.put(4) print(queue1.get()) lifo = queue.LifoQueue() lifo.put(1) print(lifo.get()) priority = queue.PriorityQueue() priority.put(3) print(priority.get())
def __init__(self, target_size=10, labels=None): super(BurstyPool, self).__init__(labels=labels) self.target_size = target_size self._database = None self._sessions = queue.LifoQueue(target_size)
import queue #inbuilt stacks and queue q = queue.Queue(maxsize=10) #inbuilt queue q.put(1) q.put(2) q.put(3) q.put(4) print(q.qsize()) while not q.empty(): print(q.get()) q = queue.LifoQueue() #inbuilt stack q.put(1) q.put(2) q.put(3) while not q.empty(): print(q.get())
button10.place(x=450, y=480, width=100, height=100) button11 = ttk.Button(self, text=".", command=lambda: button_click('.')) button11.place(x=250, y=580, width=100, height=100) button11 = ttk.Button(self, text="0", command=lambda: button_click(0)) button11.place(x=350, y=580, width=100, height=100) button11 = ttk.Button(self, text="borrar", command=button_clear) button11.place(x=450, y=580, width=100, height=100) # Create a DAC instance. qmode = queue.LifoQueue() mode = 'Test' qmode.put(mode) DAC = Adafruit_MCP4725.MCP4725(address=0x60, busnum=1) pid = PID(0.55, 1, 0.01) Interfaz = Emulador_UNIGRID() KpLabel = StringVar(Interfaz) KiLabel = StringVar(Interfaz) KdLabel = StringVar(Interfaz) KpLabel.set(pid.getKp()) KiLabel.set(pid.getKi()) KdLabel.set(pid.getKd()) textvarOpenFile = StringVar(Interfaz) textvarOpenFile.set('Kelly G') labelFileOk.configure(textvariable=textvarOpenFile) Interfaz.attributes('-zoomed', True)
# 2. 알아둘 용어 # Enqueue: 큐에 데이터를 넣는 기능 # Dequeue: 큐에 데이터를 꺼내는 기능 import queue data_queue = queue.Queue() data_queue.put("배") data_queue.put("병규") print(data_queue.qsize()) print(data_queue.get()) # 맨 먼저 들어간 데이터 출력하면서 꺼냄 print(data_queue.qsize()) # 3. LifoQueue 마지막에 넣은 것이 먼저 추출 data_lifoqueue = queue.LifoQueue() data_lifoqueue.put("문") data_lifoqueue.put("지수") print(data_lifoqueue.qsize()) print(data_lifoqueue.get()) print(data_lifoqueue.qsize()) # 4. 우선순위 큐 -> 우선순위도 지정해야 함(값이 작은 것이 우선순위가 높은 것) data_PriorityQueue = queue.PriorityQueue() data_PriorityQueue.put((10,"김")) data_PriorityQueue.put((9,"연수")) print(data_PriorityQueue.qsize()) print(data_PriorityQueue.get()) print(data_PriorityQueue.qsize())
graph = { 'A': ['C', 'B'], 'B': ['E', 'D', 'A'], 'C': ['A', 'F'], 'D': ['H', 'G', 'B'], 'E': ['B', 'I'], 'F': ['J', 'C'], 'G': ['L', 'K', 'D'], 'H': ['D'], 'I': ['M', 'E'], 'J': ['F'], 'K': ['G'], 'L': ['G'], 'M': ['I'] } q = q.LifoQueue() def dfs(start, graph, goal): q.put(start) list = [] visited = [start] while not q.empty(): node = q.get() list.append(node) if node == goal: return list neighbors = graph[node] for neighbor in neighbors: if neighbor not in visited: q.put(neighbor)
def __init__(self): self.call_q = queue.LifoQueue() #(stack)
def run(self): input_list = [self.server, sys.stdin] RUNNING = True FIRST = True while RUNNING : input_ready, output_ready, except_ready = select.select(input_list, [], []) for files in input_ready: if files == self.server : client_socket, client_address = self.server.accept() input_list.append(client_socket) self.clients.append(client_socket) player_index = self.clients.index(client_socket) self.reply_with_id(client_socket, player_index) # client_socket.send(str.encode(str(player_index))) time.sleep(0.1) self.broadcast_joined({ 'count_player' : len(self.clients), 'player' : player_index, }) elif files == sys.stdin : to_send = sys.stdin.readline() to_send = to_send.strip() self.clients[0].send(str.encode(to_send)) else : message = files.recv(self.BUFFER_SIZE) message = pickle.loads(message) print(message) if message['status'] == 'QUIT': self.reply_ok(files) input_list.remove(files) self.clients.remove(files) if len(self.clients) == 0: RUNNING = False elif message['status'] == 'UPDATE' : player_id = message['data']['id'] is_play = message['data']['play'] == 'PLAY' if is_play : player_card = self.game_data['player'][player_id]['card_index'] player_choosen_card = message['data']['selected_card'] player_choosen_card_point = message['data']['selected_card_point'] for card in player_choosen_card: player_card.remove(card) self.game_data['player'][player_id]['card_index'] = player_card self.game_data['player'][player_id]['card_count'] = len(player_card) self.game_data['card_index_before'] = self.game_data['card_index_now'] self.game_data['card_point_before'] = self.game_data['card_point_now'] self.game_data['card_index_now'] = player_choosen_card self.game_data['card_point_now'] = player_choosen_card_point self.game_data['turn_player_id'] = self.game_order.get() self.game_order.put(self.game_data['turn_player_id']) if len(player_card) == 0 : winner_data = {} winner_data['player_id'] = player_id self.broadcast_winner(winner_data) RUNNING = False else : game_stack = queue.LifoQueue() while(self.game_order.qsize() != 0): game_stack.put(self.game_order.get()) game_stack.get() game_stack2 = queue.LifoQueue() while(game_stack.qsize() != 0): game_stack2.put(game_stack.get()) self.game_order = queue.Queue() while(game_stack2.qsize() != 0): self.game_order.put(game_stack2.get()) x = self.game_order.get() self.game_order.put(x) active_player = len(list(self.game_order.queue)) if active_player == 1 : last_man = self.game_order.get() self.game_order = queue.Queue() self.game_order.put(last_man) for i in range(last_man + 1, len(self.clients)): self.game_order.put(i) for i in range(0, last_man): self.game_order.put(i) self.game_data['card_index_before'] = [] self.game_data['card_point_before'] = 0 self.game_data['card_index_now'] = [] self.game_data['card_point_now'] = 0 self.game_data['turn_player_id'] = self.game_order.get() self.game_order.put(self.game_data['turn_player_id']) else : self.game_data['turn_player_id'] = x print(list(self.game_order.queue)) self.broadcast_game_data(self.game_data) self.server.close()
deq.append(9) #extend print(deq) print(max(deq)) deq.appendleft(10) #extendleft print(deq) print(deq.popleft()) print(deq) print(deq.pop()) print(deq) #Queue FIFO q = queue.Queue(maxsize=3) print(q.qsize) q.put('a') q.put('b') q.put('c') print(q.get()) print(q.get()) print(q.get()) print(q.empty()) #Stack LIFO S = queue.LifoQueue(maxsize=6) S.put('a') S.put('b') S.put('c') print(S.get()) print(S.get()) print(S.get()) print(S.empty())
import queue q1 = queue.Queue(maxsize=5) q2 = queue.LifoQueue(maxsize=5) for i in range(5): q1.put(i) q2.put(i) while not q1.empty(): print('q1:', q1.get()) while not q2.empty(): print('q2:', q2.get())
def __init__(self): # 类似栈 后入先出 last in first out self.s1 = queue.LifoQueue() self.s2 = queue.LifoQueue()
# LIFO队列先进后出 import queue queuelist = queue.LifoQueue() for i in range(5): if not queuelist.full(): queuelist.put(i) print("put list : %s ,now queue size is %s " % (i, queuelist.qsize())) while not queuelist.empty(): print("put list : %s ,now queue size is %s " % (queuelist.get(), queuelist.qsize()))
#created using Python 3.7.3 import sys import queue filename = "jugglefest.txt" circuits = {} jugglers = queue.LifoQueue() # circuit attributes # parse Circuit's Id including the 'C' prefix # returns String def cid_full(str): start = str.index('C', 1) end = str.index(' ', start) return str[start:end] # parse Circuit's Id excluding the 'C' prefix # returns integer def cId(str): start = str.index('C', 1) + 1 end = str.index(' ', start) return int(str[start:end]) # parse Circuit's Hand-To-Eye Coordination # returns integer def cH(str):
import queue q = queue.Queue(3) q.put('123') q.put('ab') q.put('dd') print(q.get()) print(q.get()) print(q.get()) #-----------------------------------先进后出为堆栈------------------------------------ import queue q = queue.LifoQueue(3) q.put('123') q.put('ab') q.put('dd') print(q.get()) print(q.get()) print(q.get()) #-----------------------------------优先级队列------------------------------------ import queue q = queue.PriorityQueue(3) #put进入一个元组,元组的第一个元素是优先级(通常是数字,也可以是非数字之间的比较),数字越小优先级越高 q.put((20, '12'))
def search(start, board, args): """ Conduct a breadth first search (unless args.random_search is True or args.depth_first is True). """ total_visited = 0 explored = {start.signature()} if args.depth_first or args.random_search: q = queue.LifoQueue() else: q = queue.Queue() q.put(start) backpointers = {} while not q.empty(): t = q.get() total_visited += 1 # Check for a solution if board.targets == set(t.boxes): board.print_current( t, args.text_output, ( datetime.now().strftime('%H:%M:%S'), t.depth, q.qsize(), total_visited, ), args.show_board, ) actions = [] trace_signature = t.signature() while trace_signature != start.signature(): action, previous_signature = backpointers[trace_signature] actions.append(action) trace_signature = previous_signature actions.reverse() print('Solved!') print_solution(args, ''.join(actions)) print() sys.exit() if args.show_board: board.print_current(t, args.text_output, (datetime.now().strftime('%H:%M:%S'), t.depth, q.qsize(), total_visited)) # print('deq:', t) pause(args.interval) elif total_visited % args.print_interval == 0: if args.level: board.print_current( t, args.text_output, (datetime.now().strftime('%H:%M:%S'), t.depth, q.qsize(), total_visited), False, ) print() else: print( 'Time: {} Depth: {:,} Queue: {:,} Visited: {:,}'.format( datetime.now().strftime('%H:%M:%S'), t.depth, q.qsize(), total_visited)) directions = [U, R, D, L] if args.random_search: random.shuffle(directions) for direction in directions: new_position = move(t.person, direction) if board.legal_position(new_position): new_state = None if new_position in t.boxes: across = move(new_position, direction) if board.legal_position(across) and across not in t.boxes: new_boxes = t.boxes[:] new_boxes.remove(new_position) new_boxes.append(across) if board.dead_end(direction, across, new_boxes): continue else: new_state = State(new_position, new_boxes, t.depth + 1) else: new_state = State(new_position, t.boxes, t.depth + 1) if new_state is not None: new_signature = new_state.signature() if new_signature not in explored: explored.add(new_signature) q.put(new_state) backpointers[new_signature] = DIRECTION_NAME[ direction], t.signature() print('No solution found. Check the input file.')
print("Exiting " + self.name) m = 7979490791 mm = 97 F = field.GF(m) n = 4 t = 1 x = 5 #np.random.randint(0,50,40) ipv4 = os.popen('ip addr show eth0').read().split("inet ")[1].split("/")[0] pnr = party_addr.index([ipv4, port]) q = que.Queue() q2 = que.LifoQueue() #Initialization.. #TCP_IP = '192.168.100.246' #TCP_PORT = 62 UDP_PORT2 = 3000 server_info = party_addr[pnr ]#(TCP_IP, TCP_PORT) server2_info = (server_info[0], UDP_PORT2) # Create new threads.. t1_comms = commsThread(1, "Communication Thread", server_info,q) t2_commsSimulink = UDPcommsThread(2, "t2_commsSimulink", server2_info) p = party(F,int(x),n,t,pnr, q, q2) # Start new Threads
import queue, threading, random, time p = queue.Queue(maxsize=2) #先进先出的栈, 最大是2个 w = queue.LifoQueue() # 先进后出的堆 e = queue.PriorityQueue #按优先级来出,等级越低先出来 p.put(10) # 放入数据 p.put(2) #p.put_nowait(1) print(p.full()) # 这里是满的 所以返回true print(p.get()) # 取出数据 print(p.get()) #print(p.get_nowait()) #print(p.get(1,2)) print(p.qsize()) # 此处为0 因为已经取出2个了,里面没有东西了 print(p.empty()) # 判断是否为空,是的话返回true q = queue.Queue(maxsize=99) def put_in_queue(): for i in range(10): i = random.randint(1, 99) #print(i) q.put(i) #time.sleep(1)
# Queues # LIFO, FIFO, Priority import queue as queue print("######## LIFO queue ##########") q = queue.Queue() # FIFO queue for index in range(10): q.put(index) while not q.empty(): print(q.get(), end='**\n') print("######## LIFO queue ##########") lq = queue.LifoQueue() # LIFO queue for index in range(10): lq.put(index) while not lq.empty(): print(lq.get(), end='**\n') print("######### Priority queue#########") pq = queue.PriorityQueue() # Priority queue pq.put((1, 'Data Priority 1')) pq.put((3, 'Data Priority 3')) pq.put((4, 'Data Priority 4')) pq.put((2, 'Data Priority 2')) for i in range(pq.qsize()): print(pq.get()[1], end='**\n')
airports = queue.Queue(-1) sotq = queue.Queue(-1) virus=[[-1 for j in range(M)]for i in range(N)] for i in range(N): #inserting first virus tile in queue and airports in another queue for j in range(M): #and for Sotiris in another queue if grid[i][j] == 'W': myqueue.put([i,j,0,False]) elif grid[i][j] == 'A': airports.put([i,j,0,True]) elif grid[i][j] == 'S': sotq.put([i,j,0,(-2,-2)]) visited = {} #dictionary of tiles and their parents output = queue.LifoQueue(-1) #a LIFO queue for the output while not myqueue.empty() : virus_flood(False) #flood_fill for the Virus sotiris_flood() #begin the flood_fill for Sotiris if (output.qsize()!=0) : print(output.qsize()) while not output.empty() : print (output.get() , sep = "", end="") else : print("IMPOSSIBLE") print("\n")
def clean(self): self.call_q = queue.LifoQueue()
def _search(self, searchType, startingNode, heuristic=""): steps = 1 if searchType == "bfs": openList = queue.Queue() elif searchType == "dfs": openList = queue.LifoQueue() elif searchType == "a*": openList = queue.PriorityQueue() closed = [] # adds first node to open if heuristic == "": openList.put(startingNode) else: openList.put((0, startingNode)) while True: if openList.empty(): print("None") print(steps) return None if heuristic == "": currNode = openList.get() else: currNode = openList.get()[1] currState = currNode.getState() currActions = currState.actions() for i in range(len(currActions)): # print("*------------ Expansion: ", steps) # print("Length of Closed: ", len(closed)) newState = currState.clone() newState.execute(currActions[i]) newNode = Node(newState, currNode, currNode.getDistanceFromStart()) newNode.addDistanceFromStart() if self.inClosed(newNode, closed): # print("already in closed list") continue if heuristic == "": if self.inOpen(newNode, openList): # print("already in closed list") continue else: if self.inOpen(newNode, openList, heuristic): # print("already in open list") continue if heuristic == "": openList.put(newNode) else: heurVal = heuristic( newState) + newNode.getDistanceFromStart() # print("Heur: ", heuristic(newState)) # print("Distance: ", newNode.getDistanceFromStart()) openList.put((heurVal, newNode)) steps += 1 searchPath = self.generatePath(newNode) self.printPath(searchPath) # print("------------*") if newState.is_goal(): print(steps) return newNode closed.append(currNode)
# -*- coding:utf-8 -*- # Author:aling import queue q = queue.Queue() # 先进先出 q.put('abc') q.put('bed') print(q.get(1)) q2 = queue.LifoQueue() # 后进先出 q2.put('abc') q2.put('bed') print(q2.get(1)) q3 = queue.PriorityQueue() # 优先级进出,值越小优先级越高 q3.put((10, 'vip_abc')) q3.put((-1, 'bed')) q3.put((6, 'aling_vip')) q3.put((-5, 'alina_vip')) print(q3.get(1)) print(q3.get(2)) print(q3.get(3))