def start_repl(): """ Put the user into an interactive session where we can monitor their output. They exit with control d. cd into the right directory if possible. """ repl.repl()
def test_repl_gcd_example_multiline(capsys): session = """ > (define not (boolean) (if boolean 0 1)) <UserFunction (not boolean)> > (define <> (x y) (not (= x y))) <UserFunction (<> x y)> > (define mod (m n) (- m (* n (/ m n)))) <UserFunction (mod m n)> > (define gcd (m n) ... (begin ... (set r (mod m n)) ... (while (<> r 0) ... (begin ... (set m n) ... (set n r) ... (set r (mod m n)))) ... n)) <UserFunction (gcd m n)> > (gcd 42 56) 14 """ dlg = Dialogue(session) repl(dlg.fake_input) captured = capsys.readouterr() assert dlg.session == captured.out
def main(args): if not args: repl() else: env = env_from_args(args[1:]) with open(args[0]) as source_file: run(source_file, env)
def test_counting(): in_string = """ counter_state = 0 cnt = 0 count ~ (counter_state, cnt=cnt+1, this) counter_state = count (counter_state cnt) counter_state = count counter_state = count (counter_state cnt) (counter_state cnt) counter_state = count (counter_state cnt) """ istream = StringIO.StringIO(in_string) ostream = StringIO.StringIO() estream = StringIO.StringIO() repl.repl(istream, ostream, estream) assert estream.getvalue() == '' olines = ostream.getvalue().split('\n') for i, ln in enumerate(olines): print i, ':', ln assert olines[1] == '1' assert olines[2] == '3' assert olines[3] == '3' assert olines[4] == '4'
def main(): args = docopt(__doc__, version=__version__) args["<user-directory>"] = "D:/kombu" ##################################### if args["<user-directory>"] is None: userdir = setup() else: userdir = UserDir(args["<user-directory>"]) repl(userdir)
def interaction(in_string, expected_output_string, expected_error_string): istream = StringIO.StringIO(in_string) ostream = StringIO.StringIO() estream = StringIO.StringIO() repl.repl(istream, ostream, estream) assert ostream.getvalue() == expected_output_string assert estream.getvalue() == expected_error_string
def add_globals(env): """Add some Scheme standard procedures.""" import scheme.eval env.update(vars(math)) env.update(vars(cmath)) env.update({ 'list-type':list, 'globals':env, 'dict':dict, 'open-output-string': lambda: cStringIO.StringIO(), 'get-output-string': lambda ioObj: ioObj.getvalue(), '%': op.mod, 'procedure?': lambda x: Procedure in providedBy(x), 'set-debug': setDebug, 'throw': throw, 'Exception': Exception, 'type': lambda x: type(x), '**': op.pow, '+': op.add, '-': op.sub, '*': op.mul, '/': op.itruediv, 'not': op.not_, '>': op.gt, '<': op.lt, '>=': op.ge, '<=': op.le, '=': op.eq, 'equal?': op.eq, 'eq?': op.is_, 'length': len, 'cons': cons, 'car': car, 'cdr': lambda x: x[1:], 'append': op.add, 'list': List, 'list?': lambda x: isa(x, list), 'null?': lambda x: x == [], 'boolean?': lambda x: isa(x, bool), 'pair?': is_pair, 'port?': lambda x: isa(x, file), 'apply': schemeApply, 'len?': len, 'map': map, 'in': lambda x, y: x in y, 'bool': bool, 'eval': lambda *x: scheme.eval.Exec(x), 'execfile': scheme.eval.Eval, 'str':str, 'unicode':unicode, 'int':int, 'zip':zip, 'last': last, 'display': lambda x, port=sys.stdout: port.write(x.replace('~n', '\n') if isa(x, (str, unicode)) else str(x))}) from repl import repl import site package_locations = site.getsitepackages() installed = False for pl in package_locations: if __file__.startswith(pl): installed = True break if installed: p = os.path.join(sys.prefix,'share','schemepy','stdlib') else: p = os.path.join(*os.path.split(__file__)[:-2]+('stdlib',)) for scm in os.listdir(p): repl(open(os.path.join(p,scm)), '', None) return env
def test_repl_gcd_example(capsys): session = """ > (define mod (m n) (- m (* n (/ m n)))) <UserFunction (mod m n)> > (define gcd (a b) (if (= b 0) a (gcd b (mod a b)))) <UserFunction (gcd a b)> > (gcd 6 15) 3 """ dlg = Dialogue(session) repl(dlg.fake_input) captured = capsys.readouterr() assert dlg.session == captured.out
def test_repl(): reader = FakeReader("expression1", "expression2", "expression3") evaluator = FakeEvaluator(expression1 = "value1", expression2 = "value2", expression3 = "value3") printer = FakePrinter() result = repl(reader, evaluator, printer) assert(printer.getAllOutput() == "value1value2value3")
def metrics(path_to_config, path_to_json, num_trials): with open(path_to_config, "r") as json_config: player_configs = json.load(json_config) json_update_info = [] results = {} try: for i in tqdm(range(num_trials)): block_print() board = create_custom_board(player_configs) initial_cards = board.get_player_cards() player_types = board.get_player_types() winner = repl(board) winner_index = board.get_index_of_player(winner) json_update_info.append([initial_cards, winner_index, player_types]) if winner_index in results: results[winner_index] += 1 else: results[winner_index] = 1 enable_print() res = [] for idx in results.keys(): print(idx, results[idx], player_types[idx]) res.append((idx, results[idx], player_types[idx])) #update_json(path_to_json, json_update_info) with open("m2_pos_stats.txt", "a+") as f: s = "path_to_config: {}, results: {}\n".format(path_to_config, res) f.write(s) except KeyboardInterrupt: enable_print() print("OKAY") board.display() print(initial_cards) for idx in results.keys(): print(idx, results[idx], player_types[idx])
from brainfuck import Brainfuck from util.logger import setup_logs from repl import repl import argparse, logging arg_parser = argparse.ArgumentParser(prog='bf', description='Brainfuck VM') arg_parser.add_argument('source', nargs='?', help='Source file') arg_parser.add_argument('--input', nargs='*', help='Input text') arg_parser.add_argument('--log', action='store_true', help='Display logs on stdout') args = arg_parser.parse_args() if args.log: setup_logs() input_: str = ' '.join(args.input) if args.input else '' if args.source: logging.info('Loading from source: ' + args.source) brain = Brainfuck() with open(args.source, 'r') as f: result = brain.run(f.read(), input_=input_) print(result) else: logging.info('Setting up REPL...') repl(input_=input_)
import sys from hawkparser import Parser from repl import repl try: code = open(sys.argv[1]).read() Parser(code).parse() except: print('Starting Hawklang REPL...') repl()
def test_repl_quit_other_cases(capsys, session): dlg = Dialogue(session) repl(dlg.fake_input) captured = capsys.readouterr() assert dlg.session == captured.out
import utils if __name__ == '__main__': parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('--scenario', help='Run scenario') group.add_argument('--session', help='Import session') args = parser.parse_args() scenario = Scenario.load(args.scenario) if args.scenario else Scenario() session = Session.load(args.session) if args.session else Session(scenario) if args.scenario: scenario.run(session, repl.exec_cmd) # from pyinstrument import Profiler # profiler = Profiler() # profiler.start() # import yappi # yappi.start() repl.repl(session) # print('========') # profiler.stop() # print(profiler.output_text(unicode=True, color=True, show_all=True)) # yappi.get_func_stats().print_all() # yappi.get_thread_stats().print_all()
help="enter REPL mode") args = argparser.parse_args() if args.file: #read file try: with open(args.file, 'r') as f: code = f.read() except OSError as e: argparser.exit(status=1, message="cant open file '%s': %s\n" % (args.file, e)) elif args.repl: #init repl mode try: os.system('clear') print('Zala 0.1 release') while True: repl.repl() except (KeyboardInterrupt, EOFError): os.system('clear') argparser.exit(status=0, message="Left REPL mode.\n") else: argparser.exit(status=1, message="no options set\n") def main(name, code): fileParse = baseparse.parser.Parser(code, name=name) fileParse.parse() if __name__ == '__main__': main(args.file.split('.')[0], code)
def test8(self): assert(repl.repl("()") == "()")
import getCommandLineFlags import LispFileReader import Evaluator import Printer from repl import repl flags = getCommandLineFlags.getCommandLineFlags() reader = LispFileReader.LispFileReader(flags["filename"]) evaluator = Evaluator.Evaluator() printer = Printer.Printer(flags["mode"]) repl(reader, evaluator, printer)
def run(): args = LMArguments() # Seed RNGs for reproducibility if args.seed > 0: print(f"Random seed set to {args.seed}") random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) if args.cuda: torch.cuda.manual_seed(args.seed) # Configure logging if args.save: logfile = utils.create_exp_dir(args.exp, args.script, overwrite=args.overwrite) else: logfile = None # must init logging before SummaryWriter, otherwise it adds handler to root logger so basicConfig does not work logging.basicConfig( datefmt="%m-%d %H:%M:%S", format="%(asctime)s %(levelname)s %(name)s: %(message)s", level=logging.getLevelName(args.logging_level), filename=logfile, ) # Print out all the arguments set. LOGGER.info("Arguments passed: " + args.to_string(max_width=80)) print(args.exp, flush=True) LOGGER.info(f"Running the model on {'GPU (CUDA)' if args.cuda else 'CPU'}") if args.cuda: props = torch.cuda.get_device_properties(0) LOGGER.info( f"GPU name: {props.name}, CUDA version {props.major}.{props.minor}, " f"available memory: {props.total_memory / 1024 / 1024:.2f}MB.") # Create dataset dataset = create_dataset(args) # Create model model, optimizer = create_model_and_optimizer(args, dataset) # Print model parameter info n_params = sum(p.nelement() for p in model.parameters()) LOGGER.info(f"Model parameters: {n_params}") LOGGER.info(f"Model structure:\n{str(model)}") if args.repl: # REPL mode repl(dataset, model) sys.exit(0) if args.mode == "train": # Training mode try: train_model(model, dataset, optimizer, args, writer=None) except KeyboardInterrupt: LOGGER.info("Training halted.") # load best model best_path, best_epoch = utils.get_best_model(args.exp) model.load_state_dict(torch.load(best_path)['model']) LOGGER.info(f"Loaded best model (epoch {best_epoch})") # Evaluate AND dump the avg logprobs of each word evaluate_model(model, dataset, args, split="train", writer=None) evaluate_model(model, dataset, args, split="valid", writer=None) evaluate_model(model, dataset, args, split="test", writer=None) postprocess_probdump(dataset, args.exp) else: # Evaluation mode for split in ['train', 'valid', 'test']: evaluate_model(model, dataset, args, split=split, writer=None)
print("What flavour do you want?") yield '1', 'Strawberry', strawberry_milkshake yield '2', 'Chocolate', confirm_chocolate def strawberry_milkshake(): global food food = 'strawberry' + food prepare_food() def confirm_chocolate(): print("Are you sure you want a chocolate milkshake? (it's very sweet)") yield 'y', 'yes', chocolate_milkshake yield 'n', 'no', cook def chocolate_milkshake(): global food food = 'chocolate' + food prepare_food() def cook(): print("What do you want to order?") yield '1', 'Sandwich', cook_sandwich yield '2', 'Milkshake', cook_milkshake repl(cook)
def resume(): show_task() repl.repl()
def add_globals(env): """Add some Scheme standard procedures.""" import scheme.eval env.update(vars(math)) env.update(vars(cmath)) env.update({ 'list-type': list, 'globals': env, 'dict': dict, 'open-output-string': lambda: cStringIO.StringIO(), 'get-output-string': lambda ioObj: ioObj.getvalue(), '%': op.mod, 'procedure?': lambda x: Procedure in providedBy(x), 'set-debug': setDebug, 'throw': throw, 'Exception': Exception, 'type': lambda x: type(x), '**': op.pow, '+': op.add, '-': op.sub, '*': op.mul, '/': op.itruediv, 'not': op.not_, '>': op.gt, '<': op.lt, '>=': op.ge, '<=': op.le, '=': op.eq, 'equal?': op.eq, 'eq?': op.is_, 'length': len, 'cons': cons, 'car': car, 'cdr': lambda x: x[1:], 'append': op.add, 'list': List, 'list?': lambda x: isa(x, list), 'null?': lambda x: x == [], 'boolean?': lambda x: isa(x, bool), 'pair?': is_pair, 'port?': lambda x: isa(x, file), 'apply': schemeApply, 'len?': len, 'map': map, 'in': lambda x, y: x in y, 'bool': bool, 'eval': lambda *x: scheme.eval.Exec(x), 'execfile': scheme.eval.Eval, 'str': str, 'unicode': unicode, 'int': int, 'zip': zip, 'last': last, 'display': lambda x, port=sys.stdout: port.write( x.replace('~n', '\n') if isa(x, (str, unicode)) else str(x)) }) from repl import repl import site package_locations = site.getsitepackages() installed = False for pl in package_locations: if __file__.startswith(pl): installed = True break if installed: p = os.path.join(sys.prefix, 'share', 'schemepy', 'stdlib') else: p = os.path.join(*os.path.split(__file__)[:-2] + ('stdlib', )) for scm in os.listdir(p): repl(open(os.path.join(p, scm)), '', None) return env
def test6(self): assert(repl.repl("(/ (- (+ 515 (* -87 311)) 296) 27)") == "-994")
def test7(self): try: self.assertRaises(RuntimeError, repl.repl("(abc 1 2 3)")) except RuntimeError: pass
"Invalid command. Type \"help\" to see list of valid commands." ) command = str(input('>>> ')) args = command.rsplit() command = args[0] if len(args) == 2: arg1 = args[1] elif len(args) == 3: arg1 = args[1] arg2 = args[2] elif len(args) == 4: arg1 = args[1] arg2 = args[2] arg3 = args[3] call = route_commands.route_commands(command, arg1, arg2) output = repl.repl(DATAFRAME, call, command, arg1, arg2) if (call == 6): inner_call = route_commands.route_commands(arg1, arg2, arg3) output = repl.repl(DATAFRAME, inner_call, arg1, arg2, arg3) file_name = str(input('File to write to: ')) logging.info("Writing to file: " + file_name) write_to_file.write(output, file_name) elif (call == 9): accelegator_NLP.read_responses_person(DATAFRAME, FIRST_QUESTION, "all") elif (call == 10): accelegator_NLP.read_responses_person(DATAFRAME, FIRST_QUESTION, arg2) elif (call == 11): accelegator_NLP.read_responses_question(DATAFRAME, FIRST_QUESTION, "all")
# -*- coding:utf-8 -*- # a simple FSA coffee machine simulator class that demonstrates most # of Python's OO concepts and patterns (except encapsulation and destructors, # because encasulation doesn't really work here and there's no need for a # destructor). # # authored by Jules Mazur (julesmazur <at> gmail <dot> com), Jan 21, 2016 import re import sys from repl import repl from tqdm import tqdm from controller import CoffeeMachine import cm_exceptions as ex def quit(): print('') print('Quitting') sys.exit(0) if __name__ == '__main__': c = CoffeeMachine() try: repl(c) except EOFError as e: quit()
def test0(self): assert(repl.repl("(+ 1 2)") == "3")
except bderrno.bdhttp_error: print("\033[91mCouldn't connect to BaiduNetDisk!\033[0m", file = sys.stderr) exit(1) except bderrno.bdlogin_error: print("\033[91mLogin incorrect.\033[0m", file = sys.stderr) exit(2) print('\033[1m\033[93m', end = '') print(r''' __ __ __ __ __ / | / | / |/ | / | $$ |____ ____$$ | ____$$ |$$/ _______ $$ | __ $$ \ / $$ | / $$ |/ | / |$$ | / | $$$$$$$ |/$$$$$$$ |/$$$$$$$ |$$ |/$$$$$$$/ $$ |_/$$/ $$ | $$ |$$ | $$ |$$ | $$ |$$ |$$ \ $$ $$< $$ |__$$ |$$ \__$$ |$$ \__$$ |$$ | $$$$$$ |$$$$$$ \ $$ $$/ $$ $$ |$$ $$ |$$ |/ $$/ $$ | $$ | $$$$$$$/ $$$$$$$/ $$$$$$$/ $$/ $$$$$$$/ $$/ $$/ ''' ) print('\033[0m', end = '') print("Welcome to bddisk-shell, \033[4m" + username + "\033[0m !") try: repl.repl(session, username, bdstoken) except bderrno.bdlogin_error: print("\033[91mLogin state error! Exit now.\033[0m") exit(3) except KeyboardInterrupt: print("Interrupted by user, exit now.")
def test1(self): assert(repl.repl("(+ 5 (* 2 3))") == "11")
def randomPlayout(influence: List[int], bank: List[int], turn: int, num_playouts: int, p_view: PlayerView) -> List[float]: if num_playouts <= 0: return np.zeros(len(influence)) old_out = sys.stdout sys.stdout = open(os.devnull, 'w') #Create new list of random players in same order taken_cards = { CardType.Ambassador: 0, CardType.Assassin: 0, CardType.Captain: 0, CardType.Contessa: 0, CardType.Duke: 0, } claimed_c = np.argsort(p_view.claimed_cards(p_view.players), axis=1) card_types = [c for c in CardType] player_list = [] lost_inf = [] for i in range(len(influence)): #Random player does not use any additional info, no need to copy over anything #replace money and influence to match -> Also fix cards if not known rp = TruthPlayer("P" + str(i)) player_list.append(rp) if influence[i] <= 0: lost_inf.append(rp) rp.influence = influence[i] rp.bank = bank[i] for j in claimed_c[i]: if len(rp.hand) >= rp.influence: break c_type = card_types[j] if taken_cards[c_type] < constants.NUM_COPIES: rp.hand.append(Card(c_type)) taken_cards[c_type] += 1 #Create Deck d = [] for t in CardType: for _ in range(constants.NUM_COPIES - taken_cards[t]): d.append(Card(t)) deck = Deck(d) #determine number of revealed cards and discard that many num_revealed_cards = 2 * len(influence) - sum(influence) deck.shuffle() revealed_cards = deck.draw_cards(num_revealed_cards) playout_board = ContinuationBoard(turn, deck, player_list, revealed_cards, lost_inf) wins = [0] * len(influence) p_names = [p.name for p in playout_board.players] for _ in range(num_playouts): winner = repl(copy(playout_board)) w_idx = p_names.index(winner.name) wins[w_idx] += 1 #Returning whether asker was the winner of random playout wins = np.array(wins) / num_playouts sys.stdout = old_out return wins
def test_repl(capsys, session): dlg = Dialogue(session) repl(dlg.fake_input) captured = capsys.readouterr() assert dlg.session == normalize(captured.out)
import repl import sys if __name__ == '__main__': if len(sys.argv) == 1: repl.repl() elif len(sys.argv) == 2: filename = sys.argv[1] with open(filename, 'r') as f: code = f.read() print repl.repl(code=code)
def test13(self): exp = "()" res = repl.repl("()") assert(res == exp), \ err_str.format(exp, res)
################ Lispy: Scheme Interpreter in Python ## (c) Peter Norvig, 2010; See http://norvig.com/lispy.html ################ Symbol, Env classes if __name__=="__main__": from repl import repl repl()
def test4(self): assert(repl.repl("(/ (- (+ 515 (* 87 311)) 302) 27)") == "1010")
def test2(self): assert(repl.repl("(- (+ 5 (* 2 3)) 3)") == "8")
def test5(self): assert(repl.repl("(* -3 6)") == "-18")
def test_repl_quit(capsys): dlg = Dialogue('> .q\n') repl(dlg.fake_input) captured = capsys.readouterr() assert dlg.session == normalize(captured.out)
def test3(self): assert(repl.repl("(/ (- (+ 5 (* 2 3)) 3) 4)") == "2")