def test_intersect(self): cfg = CFG([Variable("S"), Variable("A")], [Terminal("a"), Terminal("b")], [ CFGRule(Variable("S"), [Variable("A"), Variable("A")]), CFGRule(Variable("S"), [Terminal("a")]), CFGRule(Variable("A"), [Terminal("b")]) ], Variable("S")) regex = RegexTree(Node("a")) fsm = regex.to_fsm() fsm.close() cfg_temp = cfg.intersect(fsm) self.assertFalse(cfg_temp.is_empty()) regex = RegexTree(Node("b")) fsm = regex.to_fsm() fsm.close() cfg_temp = cfg.intersect(fsm) self.assertFalse(cfg_temp.is_empty()) regex = RegexTree(Node("b,b")) fsm = regex.to_fsm() fsm.close() cfg_temp = cfg.intersect(fsm) self.assertFalse(cfg_temp.is_empty()) regex = RegexTree(Node("b,a")) fsm = regex.to_fsm() fsm.close() cfg_temp = cfg.intersect(fsm) self.assertTrue(cfg_temp.is_empty())
def simulate(q): with Terminal(1049) as t1049, Terminal(7) as t7, Terminal( 250) as t250, Terminal(55) as t55, Terminal(304) as t304: tlist = [t7, t55, t250, t304, t1049] while not q.empty(): term = random.choice(tlist) time.sleep(.5) term.simulate_action()
def __init__(self, term_a, term_b): self.term_a = term_a a_key, fake_b_public = mitm_keys(term_a.public) self.term_b = term_b b_key, fake_a_public = mitm_keys(term_b.public) # Setup the fake terminals self.fake_term_b = Terminal(term_b.name, term_b.uri, True) self.fake_term_b.public = fake_b_public self.fake_term_b.token = term_b.token self.fake_term_a = Terminal(term_a.name, term_a.uri, True) self.fake_term_a.public = fake_a_public self.fake_term_a.token = term_a.token self.diffie_hellman_keys = {term_a.uri: a_key, term_b.uri: b_key}
def get_terminal(self): create_terminal = lambda: Terminal.from_char(self._expr[self._i]) is_operator = (lambda: self._expr[self._i] == '+' or self._expr[self._i] == '-' or self._expr[self._i] == '*' or self._expr[self._i] == '/') is_brace = lambda: (self._expr[self._i] == '(' or self._expr[self._i] == ')') while self._i < self._n: if self._expr[self._i].isspace(): self._i += 1 continue elif self._expr[self._i].isdigit(): number, is_float = self.read_number() number = float(number) if is_float else int(number) number = Terminal("NUM", number) self._prev_terminal = number return number elif self._expr[self._i].isalpha(): func = self.read_function() func = Terminal("FUNC", func) self._prev_terminal = func return func elif is_operator(): if self.is_unary_minus(): try: self.check_uminus_syntax() except SyntaxError: raise else: neg = Terminal("NEG") self._prev_terminal = neg self._i += 1 return neg else: op = create_terminal() self._prev_terminal = op self._i += 1 return op elif is_brace(): brace = create_terminal() self._prev_terminal = brace self._i += 1 return brace else: raise SyntaxError("Unknown symbol")
def _parse_prior4(self): self._parse_prior3() while True: if (self._curr_terminal == "ADD"): self._match("ADD") self._parse_prior3() self._prefix.append(Terminal("ADD")) continue elif self._curr_terminal == "SUB": self._match("SUB") self._parse_prior3() self._prefix.append(Terminal("SUB")) continue else: return
def _parse_prior3(self): self._parse_prior2() while True: if (self._curr_terminal == "MUL"): self._match("MUL") self._parse_prior2() self._prefix.append(Terminal("MUL")) continue elif self._curr_terminal == "DIV": self._match("DIV") self._parse_prior2() self._prefix.append(Terminal("DIV")) continue else: return
def test_repr(self): cfg = CFG([Variable("I"), Variable("J")], [Terminal("a"), Terminal("b")], [CFGRule(Variable("I"), [Terminal("a"), Variable("I")])], Variable("I")) r = str(cfg) self.assertIn(str(Variable("I")), r) self.assertIn(str(Variable("J")), r) self.assertIn(str(Terminal("a")), r) self.assertIn(str(Terminal("b")), r) self.assertIn("Variables", r) self.assertIn("Terminals", r) self.assertIn("Productions", r) self.assertIn("Start", r) self.assertEqual(r.count("->"), 1) self.assertEqual(r.count("\n"), 4)
def new_terminal(self, button=None): tab = NotebookTab() tab.set_label("Terminal " + str(self.get_n_pages() + 1)) terminal = Terminal() terminal.connect("selection-changed", self.selection_changed) terminal.connect("window-title-changed", self.tab_title_changed, tab) scrollbar = Gtk.VScrollbar.new(terminal.get_vadjustment()) box = Gtk.HBox() box.pack_start(terminal, True, True, 0) box.pack_start(scrollbar, False, True, 0) index = self.append_page(box, tab) tab.connect("remove-tab", self.remove_tab_from_box, box) terminal.connect("realize", self.terminal_realize_cb, tab, index) terminal.connect("child-exited", self.remove_tab_from_box, box) self.set_tab_reorderable(box, True) self.child_set_property(box, 'tab-expand', True) box.show_all() self.show_all() self.set_current_page(self.get_n_pages() - 1)
def lesson3(): """ draw some lines! """ term = Terminal() term.clear_screen(); sys.stdout.write(term.get_code(term.FOREGROUND_RED)) Line(term, Point(4, 4), Point(term.size.x - 4, term.size.y - 4)).draw('r') sys.stdout.write(term.get_code(term.FOREGROUND_GREEN)) Line(term, Point(term.size.x - 4, 4),\ Point(term.size.x - 20, term.size.y - 4)).draw('r') sys.stdout.write(term.get_bgfg_code(term.BACKGROUND_BLUE, term.FOREGROUND_WHITE)) Line(term, Point(0, 0), Point(0, term.size.y - 2)).draw(' ') Line(term, Point(term.size.x - 1, 0), \ Point(term.size.x - 1, term.size.y - 2)).draw(' ') Line(term, Point(0, 0), Point(term.size.x - 1, 0)).draw(' ') Line(term, Point(0, term.size.y - 2), \ Point(term.size.x - 1, term.size.y - 2)).draw(' ') term.set_cursor_bottom_left() sys.stdout.write(term.get_code(term.RESET)) sys.stdout.write(term.get_code(term.FOREGROUND_GREEN)) print("Python: Line draw demo") sys.stdout.write(term.get_code(term.RESET))
def lesson2(): """ term size """ term = Terminal() sys.stdout.write(term.get_code(term.Code.FOREGROUND_GREEN)) sys.stdout.write("Python: Your terminal size is {}".format(term.size)) sys.stdout.write(term.get_code(term.Code.RESET))
def from_final_state_to_empty_stack(self): states = self.states[:] start_state = PDAState("p_start_f_to_e") final_states = [PDAState("p_final_f_to_e")] states.append(start_state) states.append(final_states[0]) stack_alphabet = self.stack_alphabet[:] input_symbols = self.input_symbols[:] start_symbol = Terminal("X_start_end_f_to_e") stack_alphabet.append(start_symbol) transition_function = self.transition_function[:] transition_function.append( PDATransitionFunction(start_state, "epsilon", start_symbol, self.start_state, [self.start_symbol, start_symbol])) for q in stack_alphabet: transition_function.append( PDATransitionFunction(final_states[0], "epsilon", q, final_states[0], [])) for final in self.final_states: for q in stack_alphabet: transition_function.append( PDATransitionFunction(final, "epsilon", q, final_states[0], [])) return PDA(states, input_symbols, stack_alphabet, transition_function, start_state, start_symbol, final_states)
def addTerminal(self, name='', num=1, termtype=0, position=(0, 0), direction=0, connType=TERM.NONE, discType=TERM.CROSS): """! @if English Define new terminal. @endif @if Slovak Pridanie noveho terminálu komponentu. Vytvorenie noveho terminálu a zaradenie ho do slovnika terminalov, klúčom je číslo terminálu. Vrati referenciu terminalu pre dalsie upravy. @endif """ term = Terminal(self, name, num, termtype, position, direction) self.terminal[num] = term term.termDiscType = discType term.termConnType = connType return term
def on_new(self, command=None, autoopen=False, autoclose=False, callback=None, **kwargs): if not command: command = self.classconfig['shell'] if self.terminals: key = sorted(self.terminals.keys())[-1] + 1 else: key = 0 url = '/ajenti:terminal/%i' % key def _callback(exitcode=None): if callback: callback() if autoclose and exitcode == 0: self.context.endpoint.send_close_tab(url) self.terminals[key] = Terminal(command, autoclose=autoclose, callback=_callback, **kwargs) self.refresh() if autoopen: self.context.endpoint.send_open_tab(url, 'Terminal %i' % key) return key
def create_grid(self): grid = Gtk.Grid() self.add(grid) # from terminal.py class Terminal self.vte = Terminal() notebook, event_exit = self.vte.create_terminal() # For closing application event_exit.connect("button_press_event", self.app_close) grid.add(notebook) # From browser.py class Browser self.webbrowser = Browser() # Creating fist browser page browser = self.webbrowser.create_browser() grid.attach(browser, 1, 0, 1, 1) # From folderview.py class Folderview self.folder = Folderview() # Create Folder view HOME folderview = self.folder.create_foldeview() grid.attach_next_to(folderview, notebook, Gtk.PositionType.BOTTOM, 1, 1) # Filevew section self.file = Fileview() fileview = self.file.create_fileview() grid.attach_next_to(fileview, folderview, Gtk.PositionType.RIGHT, 1, 1)
def _retrieve_log_flat(queue, settings): """ Writes the given *log_filename* to *queue* in a flat format equivalent to:: ./logviewer.py --flat log_filename *settings* - A dict containing the *log_filename*, *colors_css*, and *theme_css* to use when generating the HTML output. """ out_dict = { 'result': "", 'log': "", 'metadata': {}, } # Local variables out = [] spanstrip = re.compile(r'\s+\<\/span\>$') user = settings['user'] users_dir = settings['users_dir'] log_filename = settings['log_filename'] logs_dir = os.path.join(users_dir, "logs") log_path = os.path.join(logs_dir, log_filename) if os.path.exists(log_path): out_dict['metadata'] = get_or_update_metadata(log_path, user) out_dict['metadata']['filename'] = log_filename out_dict['result'] = "Success" from io import BytesIO # Use the terminal emulator to create nice HTML-formatted output from terminal import Terminal term = Terminal(rows=100, cols=300, em_dimensions=0) io_obj = BytesIO() flatten_log(log_path, io_obj) io_obj.seek(0) # Needed to emulate an actual term flattened_log = io_obj.read().replace(b'\n', b'\r\n') # NOTE: Using chunking below to emulate how a stream might actually be # written to the terminal emulator. This is to prevent the emulator # from thinking that any embedded files (like PDFs) are never going to # end. def chunker(s, n): """Produce `n`-character chunks from `s`.""" for start in range(0, len(s), n): yield s[start:start+n] for chunk in chunker(flattened_log, 499): term.write(chunk) scrollback, screen = term.dump_html() # Join them together log_lines = scrollback + screen # rstrip the lines log_lines = [a.rstrip() for a in log_lines] # Fix things like "<span>whatever [lots of whitespace] </span>" for i, line in enumerate(log_lines): out.append(spanstrip.sub("</span>", line)) out_dict['log'] = out term.clear_screen() # Ensure the function below works... term.close_captured_fds() # Force clean up open file descriptors else: out_dict['result'] = _("ERROR: Log not found") message = {'terminal:logging_log_flat': out_dict} queue.put(message)
def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) # Menu self.dark_theme.triggered.connect(self.on_dark_theme) self.theme() # Terminal self.term = Terminal() sys.stdout = self.term self.term.event.connect(self.update_terminal) self.dl = Downloader() Thread(target=self.dl.run, daemon=True).start() # Browse self.lineEdit_file_path.setText(self.dl.output_path) self.lineEdit_file_path.textEdited.connect(self.dl.output) self.lineEdit_file_path.textEdited.connect(self.dl.output) self.browse_button.clicked.connect(self.browse) # Buttons self.firefox_button.clicked.connect(self.dl.from_firefox) self.chrome_button.clicked.connect(self.dl.from_chrome) self.text_button.clicked.connect( self.from_text) # Intercept signal to add str # Logic self.dl.added_row.connect(self.add_row) self.dl.dl_hook.connect(self.update_row) self.dl.removed_row.connect(self.remove_row)
def render_log_frames(golog_path, rows, cols, limit=None): """ Returns the frames of *golog_path* as a list of HTML-encoded strings that can be used with the playback_log.html template. It accomplishes this task by running the frames through the terminal emulator and capturing the HTML output from the `Terminal.dump_html` method. If *limit* is given, only return that number of frames (e.g. for preview) """ out_frames = [] from terminal import Terminal term = Terminal( # 14/7 for the em_height should be OK for most browsers to ensure that # images don't always wind up at the bottom of the screen. rows=rows, cols=cols, em_dimensions={'height':14, 'width':7}) for i, frame in enumerate(get_frames(golog_path)): if limit and i == limit: break if len(frame) > 14: if i == 0 and frame[14:15] == b'{': # This is just the metadata frame. Skip it continue frame_time = int(float(frame[:13])) frame_screen = frame[14:] # Skips the colon # Emulate how a real shell would output newlines: frame_screen = frame_screen.replace(b'\n', b'\r\n') term.write(frame_screen) # Ensure we're not in the middle of capturing a file. Otherwise # it might get cut off and result in no image being shown. if term.capture: continue scrollback, screen = term.dump_html() out_frames.append({'screen': screen, 'time': frame_time}) del term # Ensures any file capture file descriptors are cleaned up return out_frames # Skip the first frame which is the metadata
def __init__(self, mode): if(mode=="cmd"): term = Terminal(); # elif(mode=="server"): # server = server() pass
def setUp(self): term = Terminal(1, 20) self.flight_1 = Flight(DateHour(18, 11, 2016, "12:00"), DateHour(18, 11, 2016, "16:20"), 100, 120, "Sofia", "Madrid", term) self.flight_2 = Flight(DateHour(19, 11, 2016, "15:45"), DateHour(19, 11, 2016, "20:30"), 90, 120, "Sofia", "London", term)
def main(): terminal = Terminal() mode = terminal.mode_selector() if mode == TERMINAL: terminal_mode(terminal) else: window_mode()
def setUp(self): self.flight = Flight(start_time=Date(29, 11, 2016, hour='12:20'), end_time=Date(29, 11, 2016, hour='15:30'), passengers=100, max_passengers=120, from_dest="Sofia", to_dest="London", terminal=Terminal(2, 30), declined=False)
def setUp(self): self.terminal = Terminal() self.flight = Flight() self.flight2 = Flight(start_time=Date(day=29, month=11, year=2016, hour='17:30'), from_dest="Vancouver", to_dest="New York", end_time=Date(day=29, month=11, year=2016, hour='20:40')) self.terminal.add_flight(self.flight) self.terminal.add_flight(self.flight2)
def on_new(self, command=None, autoopen=False, **kwargs): if self.terminals: key = sorted(self.terminals.keys())[-1] + 1 else: key = 0 self.terminals[key] = Terminal(command, **kwargs) self.refresh() if autoopen: self.context.endpoint.send_url('/terminal/%i' % key) return key
def setUp(self): self.airport = Airport() self.flight = Flight() self.flight2 = Flight(start_time=Date(day=29, month=11, year=2016, hour='17:30'), from_dest="Vancouver", to_dest="New York") self.terminal = Terminal() self.airport.add_terminal(self.terminal)
def _retrieve_log_flat(queue, settings): """ Writes the given *log_filename* to *queue* in a flat format equivalent to:: ./logviewer.py --flat log_filename *settings* - A dict containing the *log_filename*, *colors*, and *theme* to use when generating the HTML output. """ out_dict = { 'result': "", 'log': "", 'metadata': {}, } # Local variables out = [] spanstrip = re.compile(r'\s+\<\/span\>$') gateone_dir = settings['gateone_dir'] user = settings['user'] users_dir = settings['users_dir'] container = settings['container'] prefix = settings['prefix'] log_filename = settings['log_filename'] theme = "%s.css" % settings['theme'] colors = "%s.css" % settings['colors'] logs_dir = os.path.join(users_dir, "logs") log_path = os.path.join(logs_dir, log_filename) if os.path.exists(log_path): out_dict['metadata'] = get_or_update_metadata(log_path, user) out_dict['metadata']['filename'] = log_filename out_dict['result'] = "Success" import StringIO # Use the terminal emulator to create nice HTML-formatted output from terminal import Terminal term = Terminal(rows=100, cols=300) io_obj = StringIO.StringIO() flatten_log(log_path, io_obj) io_obj.seek(0) # Needed to emulate an actual term flattened_log = io_obj.read().replace('\n', '\r\n') term.write(flattened_log) scrollback, screen = term.dump_html() # Join them together log_lines = scrollback + screen # rstrip the lines log_lines = [a.rstrip() for a in log_lines] # Fix things like "<span>whatever [lots of whitespace] </span>" for i, line in enumerate(log_lines): out.append(spanstrip.sub("</span>", line)) out_dict['log'] = out else: out_dict['result'] = _("ERROR: Log not found") message = {'logging_log_flat': out_dict} queue.put(message)
def DrawTerminals(self): self.terminal_panels = [] self.terminals = [] for i in range(0, 4): terminal_panel = TerminalPanel(parent=self.white_area) terminal = Terminal(terminal_panel, "USB" + str(i)) terminal_panel.terminal = terminal self.terminals.append(terminal) self.terminal_panels.append(terminal_panel) self.white_area_sizer.Add(terminal_panel, 1, wx.EXPAND)
def start(self): for channel in self.server["channels"]: self.todo.put(channel) with Terminal() as t: try: threads = [Thread(target = self.downloader, args = [i]) for i in range(1, self.threads + 1)] for t in threads: t.start() # Start all the threads for t in threads: t.join() # Wait for all threads to finish except KeyboardInterrupt: self.shouldStop = True Terminal.setStatus(self.terminalLock, self.threads + 5, f"Waiting for threads to finish", Colors.BG_MAGENTA, Colors.FG_MAGENTA)
def on_new(self, command=None, autoopen=False, **kwargs): if not command: command = self.classconfig['shell'] if self.terminals: key = sorted(self.terminals.keys())[-1] + 1 else: key = 0 self.terminals[key] = Terminal(command, **kwargs) self.refresh() if autoopen: self.context.endpoint.send_url('/ajenti:terminal/%i' % key, 'Terminal %i' % key) return key
def __init__(self, other_term): self.other_term = other_term key, eve_public = mitm_keys(other_term.public) self.eve = Terminal('Eve', _BASE + '/eve', True) self.eve.public = eve_public self.eve.token = 'dbb0aef3592e476fa4b84848df032ef6' # some random token self.diffie_hellman_key = key # Exchange keys between Eve and the other terminal if not self.other_term.send_key_of(self.eve): raise Exception('Error while exchange keys between Eve and ' + self.other_term.name) print 'Eve exchanged keys with ' + self.other_term.name + ' successfully :)'
def __init__(self, terminals, query): self.variables = [Variable("S"), Variable("C")] self.terminals = terminals[:] self.productions = [ CFGRule( Variable("S"), [Variable("C"), Terminal(query), Variable("C")]), CFGRule(Variable("C"), [Variable("C"), Variable("C")]), CFGRule(Variable("C"), []) ] for terminal in self.terminals: self.productions.append( CFGRule(Variable("C"), [ Terminal(terminal), Variable("C"), Terminal(inverse(terminal)) ])) self.start = Variable("S") self.__empty = None