def test_canvas_rejects_loop_with_repeated_numbers(): dwg = svgwrite.Drawing("foo") canvas = Canvas(dwg) loop = Loop('acgu', [1, 2, 3, 4], None) loop2 = Loop('acgu', [1, 2, 3, 4], None) with pytest.raises(Exception) as e_info: canvas.add_loop(loop) canvas.add_loop(loop2)
def run(qubit, gf=10.0, pf=128.0): screen = pygame.display.set_mode(g.windowSize) screen.convert() pygame.display.set_caption('Qubit visualization') def graphics_update(): screen.fill(g.CYAN) e.event_log.act(pygame.mouse.get_pos()) qubit.draw(e.camera, g.WHITE, g.BLUE, g.RED, g.FOREST_GREEN, g.CYAN) g.draw(pygame.draw, screen) pygame.display.flip() gr.draw() physics = Loop(pf, time_dependent_func=qubit.step) gr = Graph((0, 1), (-1, 1)) qubit.add_state_graph(gr, .2) stop = False last = time() graphics = Loop(gf, time_independent_func=graphics_update) graphics.init(last) physics.init(last) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == pygame.KEYDOWN: e.event_log.log(event.key) if event.key == 32: stop = True elif event.type == pygame.KEYUP: e.event_log.remove(event.key) elif event.type == pygame.MOUSEBUTTONDOWN: e.event_log.click() elif event.type == pygame.MOUSEBUTTONUP: e.event_log.unclick() dt = time() - last graphics.go(dt) if not stop: physics.act(dt) last += dt pygame.display.quit()
def main(): pygame.mixer.init(44100, -16, 2, 1024) pygame.init() screen = pygame.display.set_mode(DISPLAY) pygame.display.set_caption("py Wheels") bg = Surface((WIN_WIDTH, WIN_HEIGHT)) bg.fill(Color(BACKGROUND_COLOR)) timer = pygame.time.Clock() margin_row = 0 margin_sect = MARGIN * 0.5 list_loops = [] total_dict_loops = {} pygame.mouse.set_cursor(*pygame.cursors.diamond) for row in range(0, COUNT_ROWS): margin_row += MARGIN margin_sect += row * MARGIN * 0.5 loops = [] margin_loop = 0 for col in range(0, COUNT_IN_ROW): margin_loop += MARGIN x = LOOP_RAD + 2 * col * LOOP_RAD + margin_loop + TOTAL_X_MARGIN y = LOOP_RAD + 2 * row * LOOP_RAD + margin_row + TOTAL_Y_MARGIN loop = Loop(LOOP_RAD, x, y) total_dict_loops.update({loop.id: loop}) loops.append(loop) height = (2 * LOOP_RAD) + MARGIN y = row * height + MARGIN * 0.5 + TOTAL_Y_MARGIN width = (2 * LOOP_RAD * COUNT_IN_ROW) + (MARGIN * (COUNT_IN_ROW + 1)) sect = Section(TOTAL_X_MARGIN, y, width, height) list_loops.append([sect, loops]) loop_sync = LoopSync( LOOP_RAD_SYNC, TOTAL_X_MARGIN + (width / 2), MARGIN + height * COUNT_ROWS + LOOP_RAD_SYNC + TOTAL_Y_MARGIN) main_process(screen, bg, list_loops, total_dict_loops, loop_sync, timer)
def __init__(self, addr, coder=None): self.loop = Loop() self.acceptor = Acceptor(addr, self.loop) self.coder = coder self.clients = {} self.acceptor.set_error_callback(self.fatal_error) self.acceptor.set_connect_callback(self.process_new)
def __init__(self, addr, coder=None): self.sock = Socket() self.addr = addr self.loop = Loop() self.ch = Channel(self.sock, self.loop, coder) self.ch.set_read_callback(self.on_msg_in) self.ch.set_write_callback(self.on_msg_sent) self.ch.set_error_callback(self.on_error)
def __init__(self, window, parent=None): super(Display, self).__init__(parent) self.loop = Loop(window) self.setWindow(window) self.startTimer(100)
def __init__(self, addr, retry_times=3): self.sock = Socket() self.fd = self.sock.fd self.addr = addr self.loop = Loop(2) self.loop.set_timeout(2, self.on_timeout) self.times = retry_times self.retry_time = 0 self.stat = 0
def loop(self, sequences=None, outputs=None, non_sequences=None, block=None, **kwargs): """ Start a loop. Usage: ``` with deepy.graph.loop(sequences={"x": x}, outputs={"o": None}) as vars: vars.o = vars.x + 1 loop_outputs = deepy.graph.loop_outputs() result = loop_outputs.o ``` """ from loop import Loop return Loop(sequences, outputs, non_sequences, block, **kwargs)
def parse(dir_name): print("#####PARSING#####") arn_list = [] for filename in os.listdir(dir_name): file = open(dir_name + filename, 'r') print("file: " + dir_name + filename) # On construit l'objet ARN arn = ARN(filename.split("_")[0]) file.readline() file.readline() chain = file.readline().split(" ")[1].rsplit('\t') chain_id = chain[0] chain = chain[1].rsplit('\n')[0] arn.chain = chain arn.chain_id = chain_id file.readline() # On ajoute les interactions et bases a l'ARN arn._set_bases() for line in file: line = line.rsplit('\t') base1 = Base(line[2], int(line[5])) base2 = Base(line[6], int(line[9].rsplit('\n')[0])) interaction = Interaction(base1, line[1], base2) arn._add_interaction(interaction) # On ajoute les boucles a l'ARN expr = "Catalog_results/loop." + arn.name + "*" for loop_file_name in glob.glob(expr): print("|\tloop file: " + loop_file_name) loop_file = open(loop_file_name) loop = Loop(arn.name, arn.chain_id, loop_file.readline().split(":")[1].rsplit('\n')[0]) loop_bases = loop_file.readline().split(": ")[1].split(", ") loop_bases[-1] = loop_bases[-1].rsplit('\n')[0] loop.bases = [Base(b[:1], b[1:]) for b in loop_bases] loop_file.readline() for line in loop_file: line = line.rsplit('\t') base1 = Base(line[0][:1], int(line[0][1:])) base2 = Base(line[2][:1], int(line[2][1:].rsplit('\n')[0])) interaction = Interaction(base1, line[1], base2) print("|\t|\tadding interaction " + str(interaction)) loop.add_interaction(interaction) arn._add_loop(loop) loop_file.close() file.close() arn_list.append(arn) print("#####FINISHED PARSING#####") return arn_list
def gen_random_loops(self, num_loops=7): loop_dim_dist = [6, 6, 7, 7, 8, 9, 10] for i in range(num_loops): rand_corner = (random.randint(0, self.width - 3), random.randint(0, self.height - 3)) rand_width = random.choice(loop_dim_dist) if rand_corner[0] + rand_width >= self.width: rand_width = self.width - rand_corner[0] rand_height = random.choice(loop_dim_dist) if rand_corner[1] + rand_height >= self.height: rand_height = self.height - rand_corner[1] cand = Loop(rand_corner, rand_width, rand_height) self.add_loop(cand) self.append_frame()
def test_sane_loop_order(): # this stem is an impossibility of numbering -- just so that we can add to a canvas. stem = Stem('acguacgu', [[1, 8], [2, 7], [3, 6], [4, 5]]) loop = Loop('acgu', [1, 2, 3, 4], stem) for loop_idx, loop_nt in enumerate(loop.nucleotides.keys()): print loop_idx, loop_nt, loop.nucleotides[loop_nt].name dwg = svgwrite.Drawing("foo") canvas = Canvas(dwg) canvas.add_stem(stem) canvas.add_loop(loop) for loop_idx, loop_nt in enumerate(canvas.loops[0].nucleotides.keys()): print loop_idx, loop_nt, loop.nucleotides[loop_nt].name
def on_pushButton_send_clicked(self): # 若是发送按钮 if self.pushButton_send.text() == '发送': # 按钮名改为停止 self.pushButton_send.setText('停止') # 队列不为空 while not self.queue.empty(): # 读取队列 self.queue.get() # 网站循环发送(时间,队列,数据源类型) self.loop = Loop(self.doubleSpinBox_speed.value(), self.queue, self.comboBox_data.currentText()) # 线程 self.thread = Thread(target=self.loop.run, name='loop_run', args=()) # 启动线程 self.thread.start() # 休眠 sleep(0.1) # 线程不可用 if not self.thread.is_alive(): # 警告框 QMessageBox.warning(self, '余时锐警告', '请检查网络连接', QMessageBox.Yes) # 按钮变回发送 self.pushButton_send.setText('发送') # 若是停止按钮,按钮名改为发送 else: # 按钮改名为发送 self.pushButton_send.setText('发送') # 写队列,等待时间1秒 self.queue.put(1)
def _create_loops(self): points = [] g_cities = nx.DiGraph() for city in self.cities: city = self.cities.get(city) g_cities.add_node('f-' + str(city.id), bipartite=0) g_cities.add_node('t-' + str(city.id), bipartite=1) points.append([city.x, city.y]) points = np.array(points) vor = Voronoi(points, incremental=True) for point in vor.ridge_points: self.cities[point[0]].add_neighbor(self.cities[point[1]]) self.cities[point[1]].add_neighbor(self.cities[point[0]]) g_cities.add_edge('f-' + str(self.cities[point[0]]), 't-' + str(self.cities[point[1]])) g_cities.add_edge('f-' + str(self.cities[point[1]]), 't-' + str(self.cities[point[0]])) temp = bipartite.maximum_matching(g_cities) print(temp) del g_cities islands = nx.DiGraph() i = 0 for key, value in temp.items(): # connect cities ... self.cities[int(key[2:])].connect_to(self.cities[int(value[2:])]) islands.add_edge(self.cities[int(key[2:])], self.cities[int(value[2:])]) i += 1 if (i >= temp.__len__() / 2): break for i, c in enumerate(nx.recursive_simple_cycles(islands)): # for i, c in enumerate(nx.simple_cycles(islands)): loop = Loop(c, i) self._loops.append(loop) self.loops.add(i)
with open('../etc/config.json') as cf: config = json.loads(''.join(cf.readlines())) with open('../etc/users.json') as cf: users = json.loads(''.join(cf.readlines())) return config, users if __name__ == "__main__": # as the method says... config, users = load_configuration() from loop import Loop looper = Loop(config) # importing the handler from handlers import Handler # initializing the handler # includes all callbacks handler = Handler(looper.com, users) # importing the server implmentation from server import HTTPServer # Starting the webserver, passing in all # route definitions http_server = HTTPServer(config, handler.routes)
def __init__(self, addr, coder=None): self.sock = None self.addr = addr self.coder = coder self.loop = Loop() self.ch = None
import socket from urllib.parse import urlparse from loop import Loop loop = Loop() async def connect(host): sock = socket.socket() sock.setblocking(False) await loop.sock_connect(sock, (host, 80)) return sock async def get(host): request = (b"GET / HTTP/1.1\r\n" b"Host: " + host.encode('ascii') + b"\r\n" b"Connection: close\r\n" b"\r\n") sock = await connect(host) await loop.sock_sendall(sock, request) chunks = [] while True: chunks.append(await loop.sock_recv(sock, 4096)) if not chunks[-1]: # Server closed connection break sock.close()
varX = Variable("x") varX.setValue(Mul(Const(2), Const(5))) varY = Variable("y") varY.setValue(Const(3)) expr2 = Sub(Add(Const(1), varY), varX) #-6 print(str(expr2) + " = " + str(expr2.calculate())) expr3 = IfCond( IfCond(expr2, Const(0), Const(1)), Sub(expr2, Const(10)), #-16 Add(expr2, Const(10))) #4 print(str(expr3) + " = " + str(expr3.execute())) #expr4 = varX.setValue(Sub(varX, Const(1))) #print(str(expr4) + " = " + str(varX.getValue())) #expr4 = varX.setValue(Sub(varX, Const(1))) #print(str(expr4) + " = " + str(varX.getValue())) #print(varX) #x #print(varX.setValue(Const(1))) #x = 1 #print(varX.getValue()) #1 expr5 = Loop(IfCond(Const(0), Const(1), Const(2)), varY.setValue(Add(varY, Const(1)))) print(str(expr5) + " = " + str(expr5.execute()))
def startup(sim_pipe): #Sonnesystem python_position = [ #"Sun" [0, 0, 0], #"Mercury" [57_909_175_000, 0, 0], #"Venus" [108_208_930_000, 0, 0], #"Earth" [149_597_890_000, 0, 0], #"Moon" [149_597_890_000, 384_400_000, 0], #"Mars" [227_936_640_000, 0, 0], #"Jupiter" [778_412_020_000, 0, 0], #"Saturn" [1_426_725_400_000, 0, 0], #"Uranus" [2_870_972_200_000, 0, 0], #"Neptune" [4_498_252_900_000, 0, 0] ] python_speed = [ #"Sun" [0, 0, 0], #"Mercury" [0, 47_872, 0], #"Venus" [0, 35_021, 0], #"Earth" [0, 29_786, 0], #"Moon" [-1_022, 0, 0], #"Mars" [0, 24_131, 0], #"Jupiter" [0, 13_069, 0], #"Saturn" [0, 9_672, 0], #"Uranus" [0, 6_835, 0], #"Neptune" [0, 5_477, 0] ] python_masse = [ #"Sun" 1.9889 * 10**30, #"Mercury" 3.3022 * 10**23, #"Venus" 4.8685 * 10**24, #"Earth" 5.97219 * 10**24, #"Moon" 7.34767309 * 10**22, #"Mars" 6.4185 * 10**23, #"Jupiter" 1.8987 * 10**27, #"Saturn" 5.6851 * 10**26, #"Uranus" 8.6849 * 10**25, #"Neptune" 1.0244 * 10**26 ] FACTOR = 0.1 radius = [ 0.25 * FACTOR, 0.02 * FACTOR, 0.06 * FACTOR, 0.06 * FACTOR, 0.01 * FACTOR, 0.03 * FACTOR, 0.18 * FACTOR, 0.15 * FACTOR, 0.1 * FACTOR, 0.1 * FACTOR ] position = np.array(python_position, dtype=np.float64) speed = np.array(python_speed, dtype=np.float64) masse = np.array(python_masse, dtype=np.float64) dt = 60 * 60 * 2 while True: if sim_pipe.poll(): message = sim_pipe.recv() if isinstance(message, str) and message == END_MESSAGE: print('simulation exiting ...') sys.exit(0) for i in range(24 * 7): Loop(dt, position, speed, masse) body_array = np.zeros((len(position), 4), dtype=np.float64) normalization = -11 for body_index in range(len(python_position)): body_array[body_index][ 0] = position[body_index][0] / 4_498_252_900_000 body_array[body_index][ 1] = position[body_index][1] / 4_498_252_900_000 body_array[body_index][ 2] = position[body_index][2] / 4_498_252_900_000 body_array[body_index][3] = radius[body_index] #print(body_array) #time.sleep(1/60) sim_pipe.send(body_array)
def __calculate_iteration_domain(statement, params, matrix, columns): """ Establishes the loops of a given statement from a matrix corresponding to the SCoPLib domain from a .scop file Parameters ---------- statement : the statement to assign the loops params : the list of parameters for the .scop file matrix : the matrix of the SCoPLib domain from a .scop file as a list of lists columns : the number of columns of the matrix Returns ------- None """ number_of_loops = columns - 2 - len(params) loops = [] for tup in matrix: d_loop = dict() d_loop['tup'] = tup d_loop['p_tup'] = list(filter(lambda c: c != '', tup.split(' ')))[:columns] d_loop['is_greater_than'] = int(d_loop['p_tup'][0]) # Last iterator with a coefficient different from 0. # This is the less restrictive loop for which this condition_text can belong num = 0 iterators = d_loop['p_tup'][1:1 + number_of_loops] for i, value in enumerate(iterators[::-1]): if value != '0': num = len(iterators) - i break d_loop['for_loop_num'] = num - 1 loops.append(d_loop) statement_loops = [] for i in range(number_of_loops): loop = Loop() loop.iterator = 'optimization_iterator_' + str(i) statement_loops.append(loop) for d_loop in loops: condition = Condition() coefficients = {} for cond in range(number_of_loops): if int(d_loop['p_tup'][cond + 1]): itera = 'optimization_iterator_' + str(cond) val = int(d_loop['p_tup'][cond + 1]) coefficients[itera] = val for cond, _ in enumerate(params): if int(d_loop['p_tup'][cond + number_of_loops + 1]): par = params[cond] val = int(d_loop['p_tup'][cond + number_of_loops + 1]) coefficients[par] = val condition.coefficients = coefficients condition.term = int(d_loop['p_tup'][-1]) if len(statement_loops) == 0: statement.if_conditions.append(condition) else: statement_loops[d_loop['for_loop_num']].loop_conditions.append( condition) statement.loops = statement_loops
from branch import Branch from ifcond import IfCond from loop import Loop if __name__ == '__main__': cond = 'x > 0' branch = Branch(cond) print(branch.toString()) then_b = 'x++;' else_b = 'x--;' ifcond = IfCond(cond, then_b, else_b) print(ifcond.toString()) body = 'y++;' loop = Loop(cond, body) print(loop.toString())
result += "\n]" return result def __str__(self): return self.format() def __repr__(self): return "CommandSequence(" + str(self) + ")" if __name__ == "__main__": from comment import Comment from loop import Loop from parallel import Parallel print CommandSequence([Loop('x', 1, 10, 0.5)]) print CommandSequence([Loop('x', 1, 10, 0.5, Comment("Hello"))]) print CommandSequence( [Loop('x', 1, 10, 0.5, Comment("Hello"), completion=True)]) print CommandSequence([ Loop('x', 1, 10, 0.5, [Comment("Hello"), Comment("World")], completion=True, timeout=10) ])
# Loops as a list of loopconnection object that contains (list<string> # elements,List<string> strarts, List <ends> ends) dicarr = gateway.entry_point.getLoops() Loops = [] for i in range(0, len(dicarr)): n = dicarr[i] elements = [] starts = [] ends = [] for x in dicarr[i].getElements(): elements.append(x.getLabel()) for x in dicarr[i].getStarts(): starts.append(x.getLabel()) for x in dicarr[i].getEnds(): ends.append(x.getLabel()) l = Loop(dicarr[i].getId(), elements, starts, ends) Loops.append(l) gateway.shutdown() GivenConfidenceLevel = 0 ''' removing folders ''' txtDirectory = "labeledEventLog_txt/" csvDirectory = "labeledEventLog_csv/" xesDirectory = "labeledEventLog_xes/" otherDirectory = "otherEventLog_all/" if os.path.exists(txtDirectory): shutil.rmtree(txtDirectory) if os.path.exists(csvDirectory): shutil.rmtree(csvDirectory) if os.path.exists(xesDirectory): shutil.rmtree(xesDirectory)
from loop import Loop import random def callback(x): x *= x return {"a": random.random()} class Batata: def __init__(self): self.a = 2 arg = Batata() l = Loop() a = l.create_coro(callback, arg) b = l.create_coro(callback, arg) print(l.run([a, b])) print(arg.a)