def import_(element, states): """ Import other .tl file(s) and evaluate them. The extension can be omitted. Usage: ($import [path <PATH1> <PATH2> <PATH..>]) or ($import [path <PATH1>] [path <PATH2>] [path <PATH..>]) """ for path_literal in _get_path_from_attrs(element): path = path_literal.value export = {} _EXPORTED.append(export) if not path.endswith('.tl'): path += '.tl' try: with open(path) as file: interpret(path, file, states.output, states.stdout) for keyword, callback in export.items(): try: states.add_element(keyword, callback) except KeyError: raise except FileNotFoundError: raise FileNotFound(path_literal.report) _EXPORTED.pop()
def repl(): """Start the interactive Read-Eval-Print-Loop""" print print " " + faded(" \`. T ") print " Welcome to " + faded(" .--------------.___________) \ | T ") print " the DIY-lisp " + faded(" |//////////////|___________[ ] ! T | ") print " REPL " + faded(" `--------------' ) ( | ! ") print " " + faded(" '-' ! ") print faded(" use ^D to exit") print env = Environment() interpret_file(join(dirname(relpath(__file__)), '..', 'stdlib.diy'), env) while True: try: source = read_expression() print interpret(source, env) except LispError, e: print colored("!", "red"), print faded(str(e.__class__.__name__) + ":"), print str(e) except QuitError, e: print colored("!", "red"), print faded(str(e.__class__.__name__) + ":"), print str(e) sys.exit(0)
def parse_file(filename): "Interpret a .moo source file" try: with open(filename, 'r') as sourcefile: source = "(begin %s)" % "".join(sourcefile.readlines()) print interpret(source, default_environment) except LispError, e: print e
def main(): b = l.lex("helloworld.yo") # for y in b: # print(y) x = a.parse(b) # for y in x: # print(y) i.interpret(x)
def load(source): try: source = open(source) for line in source: if not re.match(r'^(#.*)?$', line): interpret(line) source.close() print 'Loaded.' except IOError as e: print 'Error during loading file: %s' % e
def test_factorial_program(self): env = default_environment interpret(""" (define fact (lambda (n) (if (<= n 1) 1 (* n (fact (- n 1)))))) """, env) assert_equals(120, interpret("(fact 5)", env))
def run(): sys.stdout = OutCatcher() #sys.stderr = ErrCatcher() if program: try: interpreter.interpret(program, args.file.name) except interpreter.InterpreterException as e: e.print_traceback() update() clear()
def run_file(filename): with open(filename) as f: s = ' '.join(f) tokens = tokenizer.tokenize(s) compiler_state = compiler.init_state() codes, var_count, last_ret = compiler.compile(compiler_state, tokens) interpreter_state = interpreter.init_state() interpreter.interpret(interpreter_state, codes, var_count, last_ret)
def process(program, test_case_num): pid = str(uuid.uuid1()) if not isinstance(program, Program): program = Program.deserialize(program) program_length = program.length program_trace = {str(n): [] for n in range(program_length+1)} sampled_test_cases = random.sample(program.test_cases, test_case_num) for tid, test_case in enumerate(sampled_test_cases): memory = Memory() inputs = test_case.inputs for i in inputs: entry = MemoryEntry( name=i["variable_name"], value=i["value"], data_type=i["data_type"], opt=None ) memory.write(i["variable_name"], entry) expressions = program.expressions() idx = 0 while idx < len(expressions): expression = expressions[idx] curr_trace = str(program_length - idx) program_trace[curr_trace].append({ "test_case_id": tid, "step": int(curr_trace), "output": test_case.output, "func": expression[1], "args": expression[2:], "memory": memory.serialize() }) interpreter.interpret(memory, expression) idx += 1 program_trace["0"].append({ "test_case_id": tid, "step": 0, "output": test_case.output, "func": None, "args": [], "memory": memory.serialize() }) result = dict() for key, value in program_trace.items(): result[key] = { "program_id": pid, "program_length": program.length, "detail": value } return result
def startJVM(args): cp = classpath.Parse(args.Xjre, args.classpath) print(f"classpath:{cp}, class{args.Class}, args: {args}") classLoader = heap.NewClassLoader(cp, args.verboseClassFlag) className = args.Class.replace(".", "/") #cf = loadClass(className, cp) mainClass = classLoader.LoadClass(className) mainMethod = mainClass.GetMainMethod() if mainMethod != None: interpret(mainMethod, args.verboseInstFlag) else: print(f"Main method not found in class {args.Class}")
def run_repl(): compiler_state = compiler.init_state() interpreter_state = interpreter.init_state() print("Starting Forth REPL...") while True: s = input('> ') if s == 'QUIT': break tokens = tokenizer.tokenize(s) codes, var_count, last_ret = compiler.compile(compiler_state, tokens) interpreter.interpret(interpreter_state, codes, var_count, last_ret)
def main(): file_path = "./example_file/example01" with open(file_path, "r") as f: code_str = f.read() lex = Lexer(code_str) tokens = lex.do_lex() # print(tokens) parser = Parser(tokens) ast_vec = parser.do_parse() from interpreter import interpret interpret(ast_vec)
def keyPressEvent(self, event): if type(event) == QKeyEvent: if universal.getInputMode(): if event.key() == Qt.Key_Backspace: universal.backspaceTL() elif event.key() == Qt.Key_Return or event.key( ) == Qt.Key_Enter: interpreter.interpret(universal.getContentTL()) else: universal.appendToLog(event.text()) self.repaint() event.accept() else: event.ignore()
def repl(): """Start the interactive Read-Eval-Print-Loop """ print print " " + grey(" ^__^ ") print " welcome to " + grey(" (oo)\_______ ") print " the MOO-lisp " + grey(" (__)\ )\/\ ") print " REPL " + grey(" ||----w | ") print " " + grey(" || || ") print env = copy.deepcopy(default_environment) try: while True: try: source = read_expression() if source.strip() == "(help)": with open('moolisp/usage.txt', 'r') as f: print "".join(f.readlines()) else: result = interpret(source, env) if result is not None: print to_string(result) except LispError, e: print colored("! ", "red") + str(e) except (EOFError, KeyboardInterrupt): print colored("\nBye! o/", "grey")
def repl(): """Start the interactive Read-Eval-Print-Loop""" print(" " + faded(" \`. T ")) print(" Welcome to " + faded(" .--------------.___________) \ | T ")) print(" the Slow Loris " + faded(" |//////////////|___________[ ] ! T | ")) print(" REPL " + faded(" `--------------' ) ( | ! ")) print(" " + faded(" '-' ! ")) print(faded(" use ^D to exit\n")) env = Environment() interpret_file( join(dirname(relpath(__file__)), '..', 'stdlib', 'stdlib.sl'), env) while True: try: source = read_expression() result = interpret(source, env) if result != '': print(result) except LispError, e: print( colored("! ", "red") + faded(str(e.__class__.__name__) + ":") + str(e)) except KeyboardInterrupt: msg = "Interupted. " + faded("(Use ^D to exit)") print("\n" + colored("! ", "red") + msg)
def run(self): global timeout while run: self.run_event.wait() global observers # print "UDP Broadcast Listener starting listening routine..." global sock, wait if not sock: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('', UDP_PORT)) sock.settimeout(timeout) # reset variables rec = None address = None try: rec, address = sock.recvfrom(4048) except: # print "Timeout catched..." pass if rec and address: # print "Incoming data from ", str(address) if not address[0] in netutil.ip4_addresses(): # print "Incoming data not from own broadcast --> processing..." result, response = interpreter.interpret(rec) if result == INTERPRETER_SERVER_REQUEST: print "RaspMedia player found: ", str(address) if response[1] == TYPE_RASPMEDIA_PLAYER: wx.CallAfter(Publisher.sendMessage, 'host_found', host=address, playerName=str(response[0]), freeSpace=response[3]) elif result == INTERPRETER_FILELIST_REQUEST: wx.CallAfter(Publisher.sendMessage, 'remote_files', serverAddr=address, files=response) elif result == CONFIG_REQUEST: wx.CallAfter(Publisher.sendMessage, 'config', config=response) elif result == GROUP_CONFIG_REQUEST: wx.CallAfter(Publisher.sendMessage, 'group_config', group_config=response, playerIP=address[0]) elif result == PLAYER_UPDATE_ERROR: wx.CallAfter(Publisher.sendMessage, 'update_failed') elif result == PLAYER_BOOT_COMPLETE: wx.CallAfter(Publisher.sendMessage, 'boot_complete') stopListening() elif result == GROUP_CONFIG_ADD_ACTION: wx.CallAfter(Publisher.sendMessage, 'action_saved') elif result == GROUP_CONFIG_ACTION_DELETE: wx.CallAfter(Publisher.sendMessage, 'action_deleted') elif result == DISK_INFO_REQUEST: wx.CallAfter(Publisher.sendMessage, 'disk_info', diskInfo=response)
def getODES(model): """ getODES(file) will read a cellerator arrow text file run the interpreter and return the differential equations as a newline delimited string. """ return interpreter.interpret(model)
def do_take(self, rest): if not rest: self.character.brain.to_client.append("OK, but take what?") else: this_parse = interpret(True, rest) the_object = self.character.find(this_parse) if the_object: if the_object == self.character: self.character.brain.to_client.append( "Let's not explore that \ little conundrum, eh?" ) elif the_object.takable is True: the_object.move_to(self.character, self.character.inventory) self.character.brain.to_client.append("You take " + the_object.short_description + ".") this_message = self.character.name + " picks up " + the_object.short_description + "." SimpleStim(STIM_VISUAL, this_message, False, [self.character.room()], [self.character]) elif the_object.takable is False: self.character.brain.to_client.append( "You're unable to take \ that." ) else: self.character.brain.to_client.append( "I can't find the thing you'd \ like to take." )
def do_hit(self, rest): if not rest: self.character.brain.to_client.append("OK, but hit what?") else: this_parse = interpret(True, rest) the_object = self.character.find(this_parse, self.character.room().contents) if the_object: if the_object.__class__.__name__ == "SimpleCharacter" or the_object.__class__.__name__ == "SimpleMob": the_object.move_to(self.character.room(), self.character.room().contents) self.character.brain.to_client.append("You hit " + the_object.short_description + ".") this_message = self.character.name + " smacks " + the_object.short_description + "." SimpleStim(STIM_VISUAL, this_message, False, [self.character.room()], [self.character, the_object]) this_message = self.character.name + " hits you." SimpleStim(STIM_DAMAGE, this_message, 1, [the_object], []) else: self.character.brain.to_client.append("You hit " + the_object.short_description + ".") this_message = self.character.name + " smacks " + the_object.short_description + "." SimpleStim(STIM_VISUAL, this_message, False, [self.character.room()], [self.character]) else: self.character.brain.to_client.append("I can't find the thing you'd like to hit.")
def draw(self,generations,chunk_size): iterable = interpret(self.turtle,self.generate(generations),self.angle) l=[] for e in iterable: l.append(e) if len(l)==chunk_size: yield l l=[] if l: yield l
def run(): global dictionary, code # console.start() code = textPad.get("1.0",tk.END+'-1c') # print code filename = 'test.vote' newfile = open(filename,'w') newfile.write(code ) newfile.close() dictionary = get_tokens(filename) if (dictionary): try: start() except ParserError as e: error(e,code) return interpret() print 'done'
def run(): program = request.get_data().decode('utf-8') try: return str(interpret(program)), 200 except InvalidStatementException: return "Invalid statements", 400 except NoReturnExceptioon: return "Should contain at least 1 return statements", 400 except VariableNotDefined: return "Invalid variable", 400
def draw(self, generations, chunk_size): iterable = interpret(self.turtle, self.generate(generations), self.angle) l = [] for e in iterable: l.append(e) if len(l) == chunk_size: yield l l = [] if l: yield l
def PrintODES(model): """ printODES(file) will read a cellerator arrow text file run the interpreter to convert the list of arrows to a systems of differential equations, and will print out the differential equations. To get the ODES as a string rather than printing the use the fuction getODES(file) instead of printODES.""" s = interpreter.interpret(model) print s
def PrintODES(model): """ printODES(file) will read a cellerator arrow text file run the interpreter to convert the list of arrows to a systems of differential equations, and will print out the differential equations. To get the ODES as a string rather than printing the use the fuction getODES(file) instead of printODES.""" s=interpreter.interpret(model) print s
def run(): global dictionary, code # console.start() code = textPad.get("1.0", tk.END + '-1c') # print code filename = 'test.vote' newfile = open(filename, 'w') newfile.write(code) newfile.close() dictionary = get_tokens(filename) if (dictionary): try: start() except ParserError as e: error(e, code) return interpret() print 'done'
def startListening(): global sock global wait if not sock: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('', 60007)) wait = True while wait: #result = select.select([sock],[],[]) #print "Result from select - processing..." #rec, address = result[0][0].recvfrom(1024) rec, address = sock.recvfrom(1024) if interpreter.interpret(rec) == INTERPRETER_SERVER_REQUEST: print "Server request response - length: ", len(rec) print ":".join("{:02x}".format(ord(c)) for c in rec) print "Server address: ", str(address) print "" elif interpreter.interpret(rec) == INTERPRETER_FILELIST_REQUEST: print "File list received!"
def main(state): try: intprt = interpreter.interpret(**state) except interpreter.InterpreterException as err: return {'plan': [str(err)]} helpers.log(str(intprt)) helpers.log(str(state['stacks'])) plan, heur = planner(intprt, **state) return {'int': intprt, 'plan': plan, 'nodes_expanded': [heur]}
def repl(prompt='lis.py> '): "A prompt-read-eval-print loop." while True: try: val = interpret(raw_input(prompt), GLOBAL_ENV) except (EOFError, SystemExit): break except (Exception, KeyboardInterrupt) as e: print e else: if val is not None: print to_string(val)
def run(self): global timeout while run: self.run_event.wait() global observers # print "UDP Broadcast Listener starting listening routine..." global sock, wait if not sock: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("", UDP_PORT)) sock.settimeout(timeout) # reset variables rec = None address = None try: rec, address = sock.recvfrom(4048) except: # print "Timeout catched..." pass if rec and address: # print "Incoming data from ", str(address) if not address[0] in netutil.ip4_addresses(): # print "Incoming data not from own broadcast --> processing..." result, response = interpreter.interpret(rec) if result == INTERPRETER_SERVER_REQUEST: print "RaspMedia player found: ", str(address) if response[1] == TYPE_RASPMEDIA_PLAYER: wx.CallAfter( Publisher.sendMessage, "host_found", host=address, playerName=str(response[0]), freeSpace=response[3], ) elif result == INTERPRETER_FILELIST_REQUEST: wx.CallAfter(Publisher.sendMessage, "remote_files", serverAddr=address, files=response) elif result == CONFIG_REQUEST: wx.CallAfter(Publisher.sendMessage, "config", config=response) elif result == GROUP_CONFIG_REQUEST: wx.CallAfter(Publisher.sendMessage, "group_config", group_config=response, playerIP=address[0]) elif result == PLAYER_UPDATE_ERROR: wx.CallAfter(Publisher.sendMessage, "update_failed") elif result == PLAYER_BOOT_COMPLETE: wx.CallAfter(Publisher.sendMessage, "boot_complete") stopListening() elif result == GROUP_CONFIG_ADD_ACTION: wx.CallAfter(Publisher.sendMessage, "action_saved") elif result == GROUP_CONFIG_ACTION_DELETE: wx.CallAfter(Publisher.sendMessage, "action_deleted") elif result == DISK_INFO_REQUEST: wx.CallAfter(Publisher.sendMessage, "disk_info", diskInfo=response)
def command(text, user): user = user origcmd = text text = text.lower() action = text.replace("(command)", "") execute = interpreter.interpret(action) execute = execute.replace("$INSERTVALUEHERE", "user") try: exec(execute) # print(execute) for debugging only except: exec('print(\"Malformed Request from: \"+user[0]+\" reads:\")') print(origcmd)
def repl(): """Start the interactive Read-Eval-Print-Loop""" print print " " + faded(" ^__^ ") print " welcome to " + faded(" (oo)\_______ ") print " the MOO-lisp " + faded(" (__)\ )\/\ ") print " REPL " + faded(" ||----w | ") print " " + faded(" || || ") print faded(" use ^D to exit") print env = default_env() while True: try: source = read_expression() print interpret(source, env) except LispError, e: print colored("!", "red"), print faded(str(e.__class__.__name__) + ":"), print str(e) except KeyboardInterrupt: msg = "Interupted. " + faded("(Use ^D to exit)") print "\n" + colored("! ", "red") + msg
def compile(source): # Initialize scanner scanner_init(source) # Initialize compiler compiler = Compiler() compiler_init(compiler) # Start Compiling advance() # Loop until source end while (not match(TOKEN_END) and not parser.had_error): statement() # Emit OP_EXIT emit_byte(OP_EXIT) # Interpret chunk if (not parser.had_error): interpreter_init(current_chunk()) interpret()
def repl(): """Start the interactive Read-Eval-Print-Loop""" print print " " + faded(" \`. T ") print " Welcome to " + faded(" .--------------.___________) \ | T ") print " the DIY-lisp " + faded(" |//////////////|___________[ ] ! T | ") print " REPL " + faded(" `--------------' ) ( | ! ") print " " + faded(" '-' ! ") print faded(" use ^D to exit") print env = Environment() while True: try: source = read_expression() print interpret(source, env) except LispError, e: print colored("!", "red"), print faded(str(e.__class__.__name__) + ":"), print str(e) except KeyboardInterrupt: msg = "Interupted. " + faded("(Use ^D to exit)") print "\n" + colored("! ", "red") + msg
def run(self): global timeout while run: self.run_event.wait() global observers # print "UDP Broadcast Listener starting listening routine..." global sock, wait if not sock: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("", UDP_PORT)) sock.settimeout(timeout) # reset variables rec = None address = None # print "INSIDE BROADCASTLISTENER:" # print "Waiting for incoming data..." try: rec, address = sock.recvfrom(4048) except: # print "Timeout catched..." pass if rec and address: # print "Incoming data from ", str(address) if not address[0] in netutil.ip4_addresses(): # print "Incoming data not from own broadcast --> processing..." result, response = interpreter.interpret(rec) if result == INTERPRETER_SERVER_REQUEST: print "Server request response - length: ", len(rec) # print ":".join("{:02x}".format(ord(c)) for c in rec) print "Server address: ", str(address) print "" if response[1] == TYPE_RASPMEDIA_PLAYER: wx.CallAfter(Publisher.sendMessage, "host_found", host=address, playerName=str(response[0])) elif result == INTERPRETER_FILELIST_REQUEST: # print "File list received!" # print response wx.CallAfter(Publisher.sendMessage, "remote_files", serverAddr=address, files=response) elif result == CONFIG_REQUEST: # print "Config data received:" wx.CallAfter(Publisher.sendMessage, "config", config=response) # print response elif result == PLAYER_UPDATE_ERROR: # print "Player update failed: " + response wx.CallAfter(Publisher.sendMessage, "update_failed") elif result == PLAYER_BOOT_COMPLETE: # print "Player BOOT_COMPLETE" wx.CallAfter(Publisher.sendMessage, "boot_complete") stopListening()
def check(prog, ins, outs): mins = ins ins = list(ins) nout = b"" def puts(s): nonlocal nout nout += s def getc(): nonlocal ins if len(ins) > 0: res = ins[0] ins = ins[1:] return res else: return -1 def ungetc(c): nonlocal ins ins = [c] + ins interpreter.puts = puts interpreter.getc = getc interpreter.ungetc = ungetc program, rem = interpreter.parse(interpreter.tokenize(prog)) if len(rem) != 0: eexit('parse failure: token remains', rem) interpreter.interpret(program) if nout != outs: sys.stderr.buffer.write( b'test failed\nprogram: %s\ninput: %s\noutput: %s\nexpect: %s\n' % (bytes(map(ord, prog)), mins, nout, outs)) exit(-1)
def start_program(): if request.method == 'POST': initial_word = json.loads(request.form['message'])['initial_word'] program_lines = json.loads(request.form['message'])['program'] team = json.loads(request.form['message'])['team'] task = json.loads(request.form['message'])['task'] program = [] for l in program_lines: program.append((l['in'], l['out'], l['stop'])) # jsonify(interpret(initial_word, program, True)) # store_solution('test-team', 'test-task', program_lines) return render_template('index.html', response = interpret(initial_word, program, True)) else: return "Oops"
def do_drop(self, rest): if not rest: self.character.brain.to_client.append("OK, but drop what?") else: this_parse = interpret(True, rest) the_object = self.character.find(this_parse, self.character.inventory) if the_object: the_object.move_to(self.character.room(), self.character.room().contents) self.character.brain.to_client.append("You drop " + the_object.short_description + ".") this_message = self.character.name + " sets down " + the_object.short_description + "." SimpleStim(STIM_VISUAL, this_message, False, [self.character.room()], [self.character]) else: self.character.brain.to_client.append("I can't find the thing you'd like to drop.")
def test(filename, expected_output): print "### Interpreting", filename interpreted_ast_output = interpreter.interpret(os.path.join(EXAMPLES, filename)) tokens = tuple(lexer.tokenize(os.path.join(EXAMPLES, filename))) defs, state = Parser(*tokens).parse() gctx, errors = context_check(defs) print "### Testing compiled instructions:" interpreted_instructions_output = uebb.interpret(coder.compile_program(gctx)) if interpreted_ast_output != expected_output: raise RuntimeError("Interpreted output %d was incorrect, was expecting %d" % (interpreted_ast_output, expected_output)) if interpreted_instructions_output != expected_output: raise RuntimeError("Compiled output %d was incorrect, was expecting %d" % (interpreted_instructions_output, expected_output)) print print
def _explain(self, result): """ Explain the output. :param result: out, err given by _on_exit() """ if self.d is None: log.msg("WARNING : Nowhere to put results.", system=LOGTAG) return d = self.d self.d = None out, err = result try: ans = interpreter.interpret(out, err) d.callback(ans) except (Exception), e: log.msg('ERROR : %s' % e, system=LOGTAG) self._failed(exception.InterpretError())
def repl(): """Start the interactive Read-Eval-Print-Loop""" print(" " + faded(" \`. T ")) print(" Welcome to " + faded(" .--------------.___________) \ | T ")) print(" the Slow Loris " + faded(" |//////////////|___________[ ] ! T | ")) print(" REPL " + faded(" `--------------' ) ( | ! ")) print(" " + faded(" '-' ! ")) print(faded(" use ^D to exit\n")) env = Environment() interpret_file(join(dirname(relpath(__file__)), '..', 'stdlib', 'stdlib.sl'), env) while True: try: source = read_expression() result = interpret(source, env) if result != '': print(result) except LispError, e: print(colored("! ", "red") + faded(str(e.__class__.__name__) + ":") + str(e)) except KeyboardInterrupt: msg = "Interupted. " + faded("(Use ^D to exit)") print("\n" + colored("! ", "red") + msg)
def email_handler(event, should_reply=True): LOG.info('event=email_handler_invoked, event=%s', event) ses_message_id = event["Records"][0]["ses"]["mail"]["messageId"] request_email = retreive_email_from_s3(ses_message_id) request_body = request_email.get_body(preferencelist='plain').get_content() if not is_request_email_from_inreach(request_email): LOG.warning('event=email_not_from_inreach, from=%s', request_email['From']) return response_segments = interpret(request_body, joined=False) inreach_response = create_inreach_response(request_email, response_segments) if should_reply: send_inreach_response(inreach_response) LOG.info('event=email_handler_success, body=%s', response_segments) return inreach_response
def do_look(self, rest): if rest == "": self.character.brain.to_client.append(self.character.room().description) contents_description = "You see here: " for content in self.character.room().contents: if not content == self.character: contents_description += content.short_description + ", " if not len(contents_description) == 14: contents_description = contents_description[0 : len(contents_description) - 2] + "." self.character.brain.to_client.append(contents_description) exits_description = "Exits lead: " for an_exit in self.character.room().exits: exits_description += an_exit[0] + ", " if len(exits_description) == 12: exits_description = "You see no exits." # Could do this a little nicer. else: exits_description = exits_description[0 : len(exits_description) - 2] + "." self.character.brain.to_client.append(exits_description) else: this_parse = interpret(True, rest) the_object = self.character.find(this_parse) if the_object: self.character.brain.to_client.append(the_object.short_description) else: self.character.brain.to_client.append( "I can't find the thing you'd \ like to look at." )
def handle(self): data = self.request[0] inData = self.request[0].strip() cSocket = self.request[1] curThread = threading.current_thread() result, msg = interpreter.interpret(data) if result == SERVER_REQUEST: print "{} on {} wrote:".format(self.client_address[0], curThread.name) print "\nServer request received - sending response...\n" responseData = messages.getMessage(SERVER_REQUEST_ACKNOWLEDGE, ["-i", str(TYPE_RASPMEDIA_PLAYER), "-i", "0","-s", str(configtool.readConfig()['player_name'])]) addr = (self.client_address[0], UDP_PORT) #print "Response delay..." #time.sleep(1) print "Sending response to:" print (addr) if cSocket.sendto(responseData, addr): print "Response sent!" else: print "Sending response failed!" elif result == FILELIST_REQUEST: files = mediaplayer.getMediaFileList() print files args = ['-i', str(len(files))] for file in files: args.append('-s') args.append(file) responseData = messages.getMessage(FILELIST_RESPONSE,args) if cSocket.sendto(responseData, (self.client_address[0], UDP_PORT)): print "Filelist sent!" elif result == CONFIG_REQUEST: responseData = messages.getConfigMessage() if cSocket.sendto(responseData, (self.client_address[0], UDP_PORT)): print "Config sent!" elif result == PLAYER_UPDATE_ERROR: responseData = messages.getMessage(PLAYER_UPDATE_ERROR, ["-s", str(msg)]) cSocket.sendto(responseData, (self.client_address[0], UDP_PORT))
O RLY? SAEM arg AN 1 YA RLY FOUND YR 1 NO WAI FOUND YR PRODUKT OF arg AN I IZ factorial YR DIFF OF arg AN 1 MKAY OIC IF U SAY SO ITZ A NUMBR VISIBLE I IZ factorial YR 3 MKAY VISIBLE WHATEVR KTHXBYE """ lmaocode = generate_LMAOcode_from_LOLcode(lolcode_str) print("Generated LMAOcode:") print(lmaocode) executed_lmao_output = interpret(lmaocode, 'LMAOcode', seed=SEED, standard_input=STANDARD_INPUT) expected_output = "49\n5\n97\n" print(expected_output == executed_lmao_output) print("" "" "" "") roflcode = generate_ROFLcode_from_LOLcode(lolcode_str) print("Generated ROFLcode:") print(roflcode) executed_rofl_output = interpret(roflcode, 'ROFLcode', seed=SEED, standard_input=STANDARD_INPUT) print(expected_output == executed_rofl_output) print(executed_rofl_output)
def test_command(): assert interpret("How to!!")[0]=="howto" print("test passed")
from interpreter import interpret from jit import jit from jit_link import run import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("program", type=str, help="program to be run") parser.add_argument("--interpret", help="Use the interpreter instead of the jit", action="store_true") parser.add_argument("-o", "--optlevel", help="Optimisation level", type=int, default=2) parser.add_argument("-v", "--verbose", help="Verbose: print out llvm-ir", action="store_true") args = parser.parse_args() pgm = open(args.program).read() if args.interpret: interpret(pgm) else: ir = jit(pgm) run(str(ir), args.optlevel, args.verbose)
from interpreter import interpret import sys with open(sys.argv[1], 'r') as source_file: program = source_file.read().splitlines() interpret(program)
"Convert a Python object back into a Lisp-readable string." return ("[%s]" % ','.join(map(to_string, exp)) if isinstance(exp, list) else str(exp)) def repl(prompt='lis.py> '): "A prompt-read-eval-print loop." while True: try: val = interpret(raw_input(prompt), GLOBAL_ENV) except (EOFError, SystemExit): break except (Exception, KeyboardInterrupt) as e: print e else: if val is not None: print to_string(val) if __name__ == "__main__": import doctest import sys doctest.testmod() if len(sys.argv) == 1: repl() else: with open(sys.argv[1]) as f: print interpret(f.read(), GLOBAL_ENV)
#ugly stuff to import modules one directory up import os,sys parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,parentdir) from util import constructParser from interpreter import interpret def loadRules(filename): file = open(filename) rulesText = file.read() file.close() return rulesText rulesText = loadRules("language.txt") programText = "((42)/(2))" parser = constructParser(rulesText) rightDerivation = parser.parse(programText) print "result of {}:".format(programText) print interpret(rightDerivation)
wakeup = True def handler(signum, stack): global wakeup wakeup = True def interative_hook(): environment.current_bindings.dump() sys.stdout.write('END\n') sys.stdout.flush() sys.stderr.write('# ' + str(environment.lastlineno) + '\n') sys.stderr.write('END\n') sys.stderr.flush() global wakeup wakeup = False while not wakeup: time.sleep(5) if __name__ == '__main__': environment.tracehook = interative_hook signal.signal(signal.SIGUSR1, handler) interpret() parse() sys.stdout.write('TERMINATED\n') sys.stdout.flush() sys.stderr.write('TERMINATED\n') sys.stderr.flush()
code = "" while True: try: # Read rfid code or manual input if (keyboard_input_handler.can_read()): code = keyboard_input_handler.read() print("Scanned code: " + code) logger.info("Scanned code: " + code) print("last code:" + shared.last_code) if (code == shared.last_code): continue interpreted = interpreter.interpret(code) if (interpreted.action == interpreter.Action.play): player.play(interpreted.arg) if (interpreted.action == interpreter.Action.play_mpd): card = interpreted.arg print(card) player.play_mpd(card["uri"], card["index"], card["kind"] == "playlist") elif (interpreted.action == interpreter.Action.text2speech): card = interpreted.arg print("Speek to file:") print(card) speek.to_file(card["desc"]) player.play_mpd(card["uri"]) elif (interpreted.action == interpreter.Action.terminate): break
import tokenizer import parser import interpreter import sys if __name__ == "__main__": try: if len(sys.argv) < 2: print("need a file") sys.exit(-1) with open(sys.argv[1], 'r') as f: s = f.read() try: tokens = tokenizer.tokenize(s) except TypeError as e: print("ERROR:", e) sys.exit(1) try: ast = parser.parse(tokens) except (TypeError, SyntaxError) as e: print("ERROR:", e) sys.exit(2) interpreter.interpret(ast) try: pass except Exception as e: print("ERROR:", e) except (KeyboardInterrupt, EOFError): print()
instructions, loops, IO = interpreter.parse(file, os.stat(sys.argv[3]).st_size) with open(sys.argv[2], "r+b") as file: posts = [] for i in range(pointer - 43, -1, -48): file.seek(i) chunk = file.read(48) if chunk[-9: -6] == b"\x00\x00\x00": break posts.append(chunk) posts.reverse() memory = bytearray(os.stat(sys.argv[2]).st_size) pointer = interpreter.interpret(instructions[: instructions.index("W")], loops, memory) file.seek(0) file.write(memory[: pointer - 7]) file.write(b"\x01\x01\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00") for i in posts: file.write(i) pointer += len(posts) * 48 with open(sys.argv[1], "w") as file: file.write("{}\n{}\n".format(position, pointer))
def handle(self): data = self.request[0] inData = self.request[0].strip() cSocket = self.request[1] curThread = threading.current_thread() if not self.client_address[0] in netutil.ip4_addresses(): result, msg = interpreter.interpret(data, self.client_address[0]) if result == SERVER_REQUEST: freeSpace = self.FreeDiskSpace() responseData = messages.getMessage(SERVER_REQUEST_ACKNOWLEDGE, ["-i", str(TYPE_RASPMEDIA_PLAYER), "-i", "0","-s", str(configtool.readConfig()['player_name']), "-i", str(freeSpace[0]), "-i", str(freeSpace[1])]) addr = (self.client_address[0], UDP_PORT) print "Sending response to client:" print (addr) if cSocket.sendto(responseData, addr): print "Response sent!" else: print "Sending response failed!" elif result == FILELIST_REQUEST: files = mediaplayer.getMediaFileList() args = ['-i', str(len(files))] for file in files: args.append('-s') args.append(file) responseData = messages.getMessage(FILELIST_RESPONSE,args) if cSocket.sendto(responseData, (self.client_address[0], UDP_PORT)): print "Filelist sent!" elif result == CONFIG_REQUEST: responseData = messages.getConfigMessage() if cSocket.sendto(responseData, (self.client_address[0], UDP_PORT)): print "Config sent!" elif result == GROUP_CONFIG_REQUEST: response = messages.getGroupConfigMessage() if cSocket.sendto(response, (self.client_address[0], UDP_PORT)): print "Group Config sent!" elif result == GROUP_CONFIG_ADD_ACTION: configtool.addGroupAction(msg) gConf = configtool.readGroupConfig() response = messages.getMessage(GROUP_CONFIG_ADD_ACTION) if cSocket.sendto(response, (self.client_address[0], UDP_PORT)): print "Action saved confirmation sent!" GroupManager.ReInitGroupManager(gConf) elif result == GROUP_CONFIG_ACTION_DELETE: configtool.deleteGroupAction(msg) gConf = configtool.readGroupConfig() response = messages.getMessage(GROUP_CONFIG_ACTION_DELETE) if cSocket.sendto(response, (self.client_address[0], UDP_PORT)): print "Action deleted confirmation sent!" GroupManager.ReInitGroupManager(gConf) elif result == PLAYER_UPDATE_ERROR: responseData = messages.getMessage(PLAYER_UPDATE_ERROR, ["-s", str(msg)]) cSocket.sendto(responseData, (self.client_address[0], UDP_PORT)) elif result == FILE_DATA_REQUEST: # send images from player over tcp to host in separate thread to not block other udp handling t = threading.Thread(target=self.SendImagesOverTCP, args=[self.client_address[0]]) t.daemon = True t.start() elif result == DISK_INFO_REQUEST: freeSpace = self.FreeDiskSpace() responseData = messages.getMessage(DISK_INFO_REQUEST, ["-i", str(freeSpace[0]), "-i", str(freeSpace[1])]) addr = (self.client_address[0], UDP_PORT) if cSocket.sendto(responseData, addr): print "Disk Info sent!" else: print "Sending disk info failed!" else: print "Received own broadcast... ignored."
def testInterpret(self): result = interpret('+ 1 + 2 + 3 4') self.assertEqual(result, 10)
def main(utterance, world, holding, objects, **_): result = {} result['utterance'] = utterance trees = parse(utterance) if not trees: result['output'] = "Parse error!" return result result['trees'] = [str(t[2].node["sem"]) for t in trees] import interpreter result['goals'] = goals =[interpreter.interpret(tree,world,objects,holding) for tree in trees] if not goals: result['output'] = "Interpretation error!" return result #if there are several parse tree, we check every one and see how many works, we just #ignore the one that does not work, and if there is only one left, then it is good #if there are several left, we should ask question and let the user decide which one #he want parse_tree_for_ambiguity=[t[2].node["sem"] for t in trees] flag=False error_information=[] goals_copy=copy.deepcopy(goals) for i in range(0,len(goals_copy)): if(isinstance(goals_copy[i],dict)): flag=True else: error_information.append(goals_copy[i]) goals.remove(goals_copy[i]) try: del parse_tree_for_ambiguity[i] except: pass if(not flag): del result['goals'] if(len(error_information)>1): error=[] for i in range(0,len(error_information)): error.append(" In No."+str(i+1)+" parse tree , "+error_information[i]) result['output']="There are "+str(len(error_information))+" different way to interpret this sentence ~!"+" and ".join(error) else: result['output']=error_information.pop() return result #We use this module to solve these ambiguity problems #First: there are several plannable goal, we ask questions #Second: there are one plannable goal, but there are several objects to be moved and #the quantifier is not all or any, we should tell the user import ambiguity response=ambiguity.is_ambiguous(goals,world,objects,parse_tree_for_ambiguity) if response[0]: del result['goals'] result['output']=response[1] return result #after check of ambiguity,then,there are only one element in the goals and it is a unambiguious goal goal = goals[0] #update the parse_trees,to exclude the trees that are not possible result['trees']=[str(i) for i in parse_tree_for_ambiguity] import planner result['plan'] =plan=planner.plan(goal,world,holding,objects) if not plan: result['output'] = "Planning error!" return result elif isinstance(plan,str): del result['plan'] result['output']=plan return result result['output'] = "Success!" return result
from gui import draw from interpreter import interpret from translate import play # # x = -10 + 1; print x; print x + 25; print x/0 #blocks = [[14,26,21,1,10,22,1],[41,14,-1,-1,-1,-1,-1], [41,14,22,2,5,-1,-1], [41,14,24,10,-1,-1,-1]] # incomplete statement, throws a syntax error #blocks = [[14,26,1,10,22],[41,14,-1,-1,-1]] # x = 10 + # tries to do 10+True, throws a type error #blocks = [[14,26,1,10,22,19],[41,14,-1,-1,-1,-1]] # x = 10 + True # prints even numbers from 1 to 10. x = 1; while(x < 10){if x % 2 == 0 then print x; x++} #blocks = [[14,26,1,-1,-1,-1,-1],[13,14,30,9,-1,-1,-1],[-1,11,14,42,2,26,10],[-1,-1,41,14,-1,-1,-1],[-1,14,26,14,22,1,-1]] #blocks = [[14,26,5,22,3,25,6],[41,14,-1,-1,-1,-1,-1]] blocks = [[13,19,-1], [-1,41,5], [11,19,-1], [-1,41,6]] blocks = play() print(blocks) (filename, isErr, errLoc) = interpret(blocks) draw(blocks, filename, isErr, errLoc)