def start(self, version): """Display the menu, wait for user input and then run the program Parameters: version - version number """ # display menu and ask for input file path filePath = None cwdpath = '' while not filePath: cwdpath, filePath = self.displayMenu(version) # merge working directory and file path totalPath = os.path.join(cwdpath, filePath) # call program selector program = Program(cwdpath, totalPath) timer = Timer() timer.tic() try: program.run() except NoInputFileException as e: print e.message timer.toc() self.logger.info(timer.string('\n' 'iFlow run time')) # upon closing, ask input before ending. This to keep plot windows open. # self.askClose() return
class Learner: def __init__(self): self.program = Program() self.reset() def reset(self): self.fitness = None self.num_skips = 0 def act(self, state): # NOTE: Actions are defined very narrowly for CartPole: # The value in register 0 is fed through a sigmod # and rounded to either 0 or 1, the two valid # actions for the CartPole environment. This does # not generalize to other environments!! self.program.execute(state) r0 = self.program.registers[0] action = int(round(sigmoid(r0))) return action def mutate(self): self.program.mutate() def save(self, name): pickle.dump(self, open(name + ".agent", 'wb'))
def parse(self): prog = Program() tok = self.lex.getLookaheadToken() while(tok.getTokenType() != TokenType.EOS): stmt = self.getStatement() prog.add(stmt) tok = self.lex.getLookaheadToken() return prog
def crossover(parent1, parent2, maxDepth, terms): child1 = parent1.copy() child2 = parent2.copy() randomNodeIndexParent1 = random.randint(0, parent1.nodeCount()-2) + 1 randomNodeIndexParent2 = random.randint(0, parent2.nodeCount()-2) + 1 randomNodeParent1 = parent1.subProgramAt(randomNodeIndexParent1)[0] randomNodeParent2 = parent2.subProgramAt(randomNodeIndexParent2)[0] child2.replaceAt(randomNodeIndexParent2, randomNodeParent1) child1.replaceAt(randomNodeIndexParent1, randomNodeParent2) return Program.prune(child1, 4, terms), Program.prune(child2, 4, terms)
def testLimitFiles(self): program = Program() with open("fileTest.txt", "r") as file: for line in file: program.open(line[0:-1]) self.assertEqual(program.getRecentFiles(), [ 'peixe.txt', 'santanche.txt', 'osu.exe', 'cyberpunk.txt', 'rambo.py', 'foo.txt', 'igor.py', 'sugoidesu.txt', 'bakamitai.mp3', 'kurisu.txt' ])
def main(): mode, length, width, file_path = load_data() program = Program(length, width, mode) program.read_file(file_path) if mode == 1: program.load_data() program.simulate1(length, width) elif mode == 2: program.simulate2(length, width)
def __init__(self, x, y, edge, start, goal, executable, auto): self.x, self.y = x, y self.edge = edge self.auto = auto self.goal = complex(*self[goal]) self.bot_pos = self.start = complex(*self[start]) self.bot_angle = complex(0, 1) self.window = Window(self.x, self.y) self.c_program = Program(executable) #self.c_program=IO() Thread(target=self.refresh, daemon=False).start() self.window.launch()
def main(): try: p = Parser("test1.mod") progs = Program(p.parse()) progs.execute() except LexicalException as e: print(e) except ParserException as e: print(e) except ValueError as e: print(e) print("ValueError in Interpreter") except Exception as e: print(e) print("Unknown error occurred - terminating")
def Program(self): functions = [] if self.peek().type == "FUNCTION": functions = self.Functions() aslist = self.Assignments() return Program(assignments=aslist, functions=functions)
def fromTextFile(self, path): with open(path, 'r') as f: appString = f.read() appString = appString.split(',') appString = [x for x in appString if x.strip()] appList = [Program(x) for x in appString] return self(apps=appList)
def run(program: Program, args: ArgsMap) -> ProgramResult: try: return program.run(**mk_func_args( program.run, ArgsMapSeries.make(args, as_argsmap(program)))) except Fizzle as fiz: if fiz.codelet is None: force_setattr(fiz, 'codelet', program) raise
def get_links(self, text): # download_links = [] # # found = self.download_regex.findall(text) # #found2 = self.download2_regex.findall(text) # # info_links = self.get_info_links(self, text) # # #print(found2) # # #sys.exit() # # counter = 0 # # for url in found: # # # Configura o link de download # url = url[13:-1] # # #links.append(Program(url, self.get_version(self, text), downloads[counter])) # download_links.append(Program(url, info_links[counter], None, 0, 0)) # # counter += 1 # # counter = 0 # for url in found2: # # # Configura o link de download # url = url[13:-1] # # url = "http://www.reporting-download.com/download/?appid=" + url[42:] # # #links.append(Program(url, self.get_version(self, text), downloads[counter])) # download_links.append(Program(url, info_links[counter], None, 0, 0)) # # counter += 1 links = [] found = self.page_regex.findall(text) #_, last_week = self.get_downloads(self, "", text, False) counter = 0 for url in found: l = self.create_links_list(self, url[:-2]) # Remove space and " chars if l is not None: l = html.unescape(l) links.append(Program(l, url[:-8], "", 0, None))#last_week[counter])) counter += 1 return links
def __init__(self, action = None, learner = None): """Initialize new Learner. This can either be done from scratch or as a copy of a previous Learner, maintaining that Learner's action, which may be a pointer to a Team. Be wary of using deepcopy! The temptation to copy Learners via deepcopy was there, but this is a mistake since it will create copies of any Team pointed to by self.action. On the other hand, copying Programs via deepcopy is correct and a conveneient way to ensure that the new Program gets its own copy of the list of instructions. """ # Set default value. This is so that setAction() will function properly # when checking the current self.action type. In general, the action # should always be set via setAction() self.action = 0 # This counter keeps track of how many Teams hold a pointer to # this Learner, ie. how many Teams this Learner is a member of. self.num_referencing_teams = 0 if learner is None: # Create Program associated with Learner self.program = Program() self.setAction(action) if action is None: print("WARNING - Learner::init - No Learner and no Action") # Assign Learner's action value self.setAction(randint(0, Learner.ATOMIC_ACTION_RANGE)) else: # Make a copy of the other Learner's Program self.program = deepcopy(learner.program) # Copy the other Learner's action, whether it's atomic or not self.setAction(learner.action) # If new action is a Team pointer, update that Team's number of # referencing Learners if not self.isActionAtomic(): self.action.incrementNumReferencingLearners()
def test_compute_minimum_area(self): from Drone import Drone drone_list = [ Drone('test1', 30.0, 18.0, (3840, 2160), 12, 104), Drone('test2', 30.0, 18.0, (3840, 2160), 12, 104), Drone('test3', 30.0, 18.0, (3840, 2160), 6, 104) ] obtained = Program().compute_minimum_area(drone_list) self.assertEqual(obtained, (15.359299586316945, 8.639606017303281)) self.assertEqual(obtained[0] * obtained[1], 132.6982971275077)
def compile(self, code): codeStream = InputStream(code) lexer = cargobotLexer(codeStream) stream = CommonTokenStream(lexer) parser = cargobotParser(stream) tree = parser.start() program = Program() listener = CargoBotListenerImpl(program) walker = ParseTreeWalker() walker.walk(listener, tree) return program
def part_one(): # Setup program = Program(1024 * 1024) program.load_code("testInput.txt") # Run #program.load_input([1]) program.run() print(program.is_done()) output = program.get_output() print(output)
def parse(self): '''Postcondition: Implements program -> function ID ( ) -> <block>''' self.match(self.lex.getNextTok(), TokenType.METHOD_TOK) self.match(self.lex.getNextTok(), TokenType.ID_TOK) self.match(self.lex.getNextTok(), TokenType.INPUTSTRT_TOK) self.match(self.lex.getNextTok(), TokenType.INPUTEND_TOK) program = Program(self.getBlock()) self.match(self.lex.getNextTok(), TokenType.END_TOK) self.match(self.lex.getNextTok(), TokenType.EOS_TOK) return program
def main(): tokenizer = create_tokenizer("input.txt") open_output_file("output.txt") program = Program() program.parse() program.evaluate() close_output_file() tokenizer.destroy()
class Defender(Communicator): RUN_SECONDS = 25 def __init__(self, fingerprint, host, port, other_host, other_port, name=None, match_all_but=0, original=None): super().__init__('defender', host, port, other_host, other_port) self.__fingerprints = fingerprint self.__program = Program(fingerprint, name, match_all_but=match_all_but, original=original) self.__result = None def start(self) -> None: super().start() sleep(1) self.send('DOWNLOAD %s' % self.__program.name) def handle_request(self, data): print('%-10s IN : %s' % (self.name, data)) parts = data.split(' ') if parts[0] == 'DOWNLOAD' and parts[-1] == 'OK': self.send(data.replace('DOWNLOAD', 'RUN').replace('OK', str(Defender.RUN_SECONDS))) elif parts[0] == 'RUN' and parts[-1] == 'SECONDS': self.run_defense(parts[1], parts[2], parts[4]) return False else: print('Invalid message:', data, flush=True) return True def run_defense(self, name, seconds, start_seconds): s = int(seconds) + int(start_seconds) if self.__program.name == name: print('Starting test run for %s seconds' % s, flush=True) self.__result = self.__program.test_run(s, save=True) else: raise AssertionError('Expected program %s to be loaded, got %s instead' % (name, self.__program.name)) print('Printing analysis', flush=True) self.__program.print_analysis(self.__result) def result(self): return self.__result
def parse(self): tok = self.get_next_token() self.match(tok, TokenType.MAIN_TOK) tok = self.get_next_token() self.match(tok, TokenType.LEFT_PAREN_TOK) tok = self.get_next_token() self.match(tok, TokenType.RIGHT_PAREN_TOK) tok = self.get_next_token() self.match(tok, TokenType.EOLN_TOK) block = self.get_statement_block() tok = self.get_next_token() if tok.Token.get_token_type() != TokenType.EOS_TOK: raise ParserException("invalid end of file") return Program(block)
def generateCallTree(sourceFiles, options): firstFile = open(sourceFiles, "r") # Open first given file for reading callTree = [] while True: try: line = firstFile.next().strip() # Read next line. except: # End of file break if isProgram(line): # Is this a line containing "program" statement? callTree.append(Program(firstFile, line)) else: # Ordinary statement recognizeSourceLineAndUpdateTree(callTree, line) return callTree
def parse(self): tok = self.getNextToken() self.match(tok, TokenType.FUNCTION_TOK) functionName = self.getId() tok = self.getNextToken() self.match(tok, TokenType.LEFT_PAREN_TOK) tok = self.getNextToken() self.match(tok, TokenType.RIGHT_PAREN_TOK) blk = self.getBlock() tok = self.getNextToken() self.match(tok, TokenType.END_TOK) tok = self.getNextToken() if tok.getTokType() != TokenType.EOS_TOK: raise Exception("garbage at end of file") return Program(blk)
def parse(self): tok = self.lex.get_next_token() Parser.match(tok, TokenType.FUNCTION_TOK) functionName = self.get_id() tok = self.lex.get_next_token() Parser.match(tok, TokenType.LEFT_PAREN_TOK) tok = self.lex.get_next_token() Parser.match(tok, TokenType.RIGHT_PAREN_TOK) blk = self.get_block() tok = self.lex.get_next_token() Parser.match(tok, TokenType.END_TOK) tok = self.lex.get_next_token() if tok.get_tok_type() != TokenType.EOS_TOK: raise Exception("garbage at end of file") return Program(blk)
def writeProgramCellsForYear(ws, row, program: Program, year): startCol = monthStartOutput + (year - startYear) * colsPerYear values = program.getMonthDict(year) lastMonth = 12 if year == lastYearData and lastMonthData < lastMonth: lastMonth = lastMonthData for month in range(1, lastMonth + 1): ws[get_column_letter(startCol + month - 1) + str(row)] = values[month - 1]['numEvents'] ws[get_column_letter(startCol + month - 1) + str(row + 1)] = values[month - 1]['numPeopleUnique'] ws[get_column_letter(startCol + month - 1) + str(row + 2)] = values[month - 1]['numPeople']
def parse(self): token = self.lex.get_next_token() Parser.match(token, TokenType.FUNCTION_TOK) function_Name = self.get_id() token = self.lex.get_next_token() Parser.match(token, TokenType.LEFT_PAREN_TOK) token = self.lex.get_next_token() Parser.match(token, TokenType.RIGHT_PAREN_TOK) block = self.get_block() token = self.lex.get_next_token() Parser.match(token, TokenType.END_TOK) token = self.lex.get_next_token() if token.get_tok_type() != TokenType.EOS_TOK: raise Exception("File has Garbage") print("There is extra information on the julia") return Program(block)
def part_two(): # Setup program program = list() for i in range(5): program.append(Program()) program[i].load_code("thrusterProgram.txt") # Try all phase setting permutations phase_configuration_permutations = itertools.permutations([5, 6, 7, 8, 9]) max_output = 0 for phase_configuration in phase_configuration_permutations: # Start each program output = 0 for i, phase in enumerate(phase_configuration): program[i].load_input([output, phase]) program[i].run() output = program[i].get_output() #print("Output: %d from %d with phase %d" % (output, i, phase)) # Run until done i = 0 while not program[4].is_done(): program[i].load_input([output]) program[i].run() output = program[i].get_output() i = (i + 1) % 5 #print([x.is_done() for x in program]) #print("Output: %d from %d" % (output, i)) if output > max_output: max_output = output print("Max output is: %d" % max_output)
def loadFromFile(self,filename): self.parser=ProgramParser(filename) #Strip any path information name=filename[filename.rfind("\\")+1:] if "\\" in filename else filename self.program=Program(self.parser.tokens,name) path=filename[:filename.rfind("\\")+1] gen=self.program.populate() try: typ,val=gen.next() while True: try: if typ=='imp': self.__import([path+v for v in val]) typ,val=gen.next() elif typ=='inp': gen.send(self.__getPartition(val)) else: raise SemanticException('Unknown request %s'%typ) except SemanticException, ex: gen.throw(ex) except StopIteration: pass
def get_links(self, text): links = [] found = self.page_regex.findall(text) _, last_week = self.get_downloads(self, "", text, False) counter = 0 for url in found: l = self.create_links_list(self, url) if l is not None: l = html.unescape(l) links.append(Program(l, url[:-8], "", 0, last_week[counter])) counter += 1 return links
def load_data(): wb = load_workbook(CBOutreachFile) ws = wb['Outreach Events'] findLastRowInput(ws) for i in range(firstRowInput, lastRowInput + 1): global data row = str(i) initiative = ws[cInitiative + row].value strategy = ws[cStrategy + row].value activity = ws[cActivity + row].value program = ws[cProgram + row].value if program is None: continue else: program = program.strip() date = ws[cDate + row].value # type: datetime numPeople = ws[cNumPeople + row].value numPeopleUnique = ws[cNumPeopleUnique + row].value if initiative not in data: data[initiative] = {} if strategy not in data[initiative]: data[initiative][strategy] = {} if activity not in data[initiative][strategy]: data[initiative][strategy][activity] = {} if program not in data[initiative][strategy][activity]: data[initiative][strategy][activity][program] = Program( initiative, strategy, activity, program) programInstance = data[initiative][strategy][activity][ program] # type: Program programInstance.addEvent(date, numPeople, numPeopleUnique) getLastMonthAndYearWithEntries()
def test_run_invalid_input(self): program = Program() program.transport = mock.create_autospec(Transport) program.parser = mock.create_autospec(Parser) program.interpolator = mock.create_autospec(Interpolator) program.transport.read.return_value = 'input' program.parser.parse.side_effect = ValueError('Error') program.interpolator.interpolate.return_value = 'output' actual = program.run() program.transport.read.assert_called() program.parser.parse.assert_called() program.parser.parse.assert_called_with('input') program.interpolator.interpolate.assert_not_called() program.transport.write.assert_called_with('Invalid matrix!')
def test_run(self): program = Program() program.transport = mock.create_autospec(Transport) program.parser = mock.create_autospec(Parser) program.interpolator = mock.create_autospec(Interpolator) program.transport.read.return_value = 'input' program.parser.parse.return_value = 'parsed_input' program.interpolator.interpolate.return_value = 'output' actual = program.run() program.transport.read.assert_called() program.parser.parse.assert_called() program.parser.parse.assert_called_with('input') program.interpolator.interpolate.assert_called_with('parsed_input') program.transport.write.assert_called_with('output')
def get_program(username): con = sql.connect('classes2.db') cur = con.cursor() cur.execute("SELECT major FROM Users WHERE username = ?", username) user = cur.fetchone() #have the user, now build their program courses = loadCourses.load() if user == "Computer Science": CS = Program("Computer Science") csBuild = programBuilder(2017, 0, 3, CS) return csBuild.planCourses() elif user == "Information Systems - Standard": IS0 = Program("Information Systems - Standard") is0Build = programBuilder(2017, 0, 3, IS0) return is0Build.planCourses() elif user == "Information Systems - Business Analysis/Systems Analysis": IS1 = Program( "Information Systems - Business Analysis/Systems Analysis") is1Build = programBuilder(2017, 0, 3, IS1) return is1Build.planCourses() elif user == "Information Systems - Business Intelligence": IS2 = Program("Information Systems - Business Intelligence") is2Build = programBuilder(2017, 0, 3, IS2) return is2Build.planCourses() elif user == "Information Systems - DB Administration": IS3 = Program("Information Systems - DB Administration") is3Build = programBuilder(2017, 0, 3, IS3) return is3Build.planCourses() elif user == "Information Systems - IT Enterprise Management": IS4 = Program("Information Systems - IT Enterprise Management") is4Build = programBuilder(2017, 0, 3, IS4) return is4Build.planCourses()
def part_one_and_two(): program = Program() program.load_code("input.txt") program.run()
def getPrograms(): ''' Get a dictionary of Programs and a list of Program names from the RSF self-documentation system. ''' import rsf.doc import rsf.prog programs = {} for progname in rsf.doc.progs.keys(): prog = rsf.doc.progs[progname] name = prog.name synopsis = prog.snps comments = prog.cmts desc = prog.desc file = prog.file also = prog.also wiki = prog.wiki vers = prog.vers uses = prog.uses.copy() program = Program(name,synopsis,comments,desc,uses,also,wiki,file,vers) for parname,par in prog.pars.items(): type = par.type.replace('\t','').replace('\n','').replace(' ','') desc = par.desc.replace('\t','').replace('\n','') default = par.default.replace('\t','').replace('\n','').replace(' ','') if default == '=': default = '' prange = par.range.replace('\t','').replace('\n','') parameter = Parameter(parname,type,desc,default,prange) program.add(parameter) custom = Parameter('custom','string','additional parameters specified by the user without key=val formatting','','') input = Parameter('input','string','input rsf file names','','') output = Parameter('output','string','output rsf file names','','') program.add(custom) program.add(input) program.add(output) programs[progname] = program for plotcommand in plotCommands.split(' '): name = plotcommand synopsis = 'Vppen command' comments = '' desc = '' file = '' also = '' wiki = '' vers = '' uses = {} program = Program(name,synopsis,comments,desc,uses,also,wiki,file,vers) custom = Parameter('custom','string','additional parameters specified by the user without key=val formatting','','') input = Parameter('input','string','input rsf file names','','') output = Parameter('output','string','output rsf file names','','') program.add(custom) program.add(input) program.add(output) programs[plotcommand] = program programNames = programs.keys() programNames.sort() return programs, programNames
class Processor(object): def __init__(self, filename=None): self.parser=None self.program=None self.filename=filename self.inheritedPartitions={} if filename is not None: self.loadFromFile(filename) def loadFromFile(self,filename): self.parser=ProgramParser(filename) #Strip any path information name=filename[filename.rfind("\\")+1:] if "\\" in filename else filename self.program=Program(self.parser.tokens,name) path=filename[:filename.rfind("\\")+1] gen=self.program.populate() try: typ,val=gen.next() while True: try: if typ=='imp': self.__import([path+v for v in val]) typ,val=gen.next() elif typ=='inp': gen.send(self.__getPartition(val)) else: raise SemanticException('Unknown request %s'%typ) except SemanticException, ex: gen.throw(ex) except StopIteration: pass def __import(self,imp): for impItem in imp: filename=impItem+'.stdll' parser=LibraryParser(filename) self.__populateLibrary(parser.tokens,impItem) def __populateLibrary(self,tokens,name): assert isinstance (name,str) library=Library(tokens,name[name.rfind("\\")+1:]) path=name[:name.rfind("\\")+1] gen=library.populate() try: typ,val=gen.next() while True: try: if typ=='imp': self.__import([path+v for v in val]) typ,val=gen.next() elif typ=='inp': typ,val=gen.send(self.__getPartition(val)) else: raise SemanticException('Unknown request %s\n'%typ) except SemanticException, ex: gen.throw(ex) except StopIteration: pass self.inheritedPartitions.update(library.inheritedPartitions) def __getPartition(self,partition): dic=self.inheritedPartitions for r in partition: if r in dic: dic=dic[r] else: raise SemanticException('Partition %s not found\n'%'.'.join(partition)) return dic def getCode(self,out): try: if not out: if self.filename.endswith('.stdl'): out=self.filename[:-5] else: out=self.filename ext,code=self.program.getCode() out+=ext with open(out,'w') as f: f.write(code) return ('Produced file: %s\nOK.\n'%out) except IOError, ioe: return str(ioe)
def convert_to_ast(node): program = Program() program.set_name(node.get_name()) program.set_type(node.get_type()) dclr_child = node.get_child_nodes()[0] dclr_list = DclrList() while True: if dclr_child is not None and dclr_child.get_name() == 'var': ident_name = dclr_child.get_child_nodes()[0] declaration = Declaration(ident_name.get_name()) declaration.set_name(ident_name.get_name()) declaration.set_type(symbol_table.get(ident_name.get_name())) dclr_list.add_declaration_to_list(declaration) AST.dot.edge(dclr_list.get_gv_name(), declaration.get_gv_name()) length = len(dclr_child.get_child_nodes()) dclr_child = dclr_child.get_child_nodes()[length - 1] else: break program.set_dclr_list(dclr_list) AST.dot.edge(program.get_gv_name(), dclr_list.get_gv_name()) stmt_child = node.get_child_nodes()[2] stmt_list = generate_statement_list(stmt_child) if stmt_list.get_type_error(): AST.dot.edge(program.get_gv_name(), stmt_list.get_gv_name(), color='red') else: AST.dot.edge(program.get_gv_name(), stmt_list.get_gv_name()) program.set_stmt_list(stmt_list) return program
memory = Memory(32) mmu = ContinousAllocation(memory, BestFit()) mmu = Paging(memory, 4) hard_disk = HardDisk() cpu = Cpu(None, None, None) scheduling_policy = Fifo() h_kernel = Kernel(cpu, mmu, hard_disk, scheduling_policy) h_kernel = Kernel(cpu, mmu, hard_disk) Log().debug_mode = False shell = SheelH(h_kernel) h_kernel.start() pro = Program('program1') pro.add_instruction(Add(1,2)) pro.add_instruction(Add(1,2)) pro.add_instruction(Add(1,2)) pro.add_instruction(Add(1,2)) pro.add_instruction(Add(1,2)) pro.add_instruction(Add(1,2)) pro.add_instruction(Add(1,2)) pro2 = Program('program2') pro2.add_instruction(Add(3,2)) pro2.add_instruction(Add(3,2)) pro2.add_instruction(Add(3,2)) pro2.add_instruction(Add(3,2)) pro3 = Program('program3') pro3.add_instruction(Add(4,2)) pro3.add_instruction(Add(4,2))
def _getProgram(self): from Program import Program dval = self.d["values"] p = Program(dval["name"], dval["cmd"]) p.setCpu(dval["ncpu"]) p.setOrder(dval["order"]) p.setCanFail(dval['canFail']) p.addStdOut(dval['stdout']) p.addStdErr(dval['stderr']) p.setHost(dval['host']) p.setExit(dval['exit']) self.obj = p
""" Created on Oct 4, 2009 @author: jnelson """ from Program import Program def fib(n): o = 0 t = 1 for i in range(n): yield t o, t = t, o + t if __name__ != "__main__": exit p = Program("Program.py") p.parse_file()
def import_sheet(doc): #print "Import!", doc root = Program('XSLT') # The root program puts the mark on the Result node and the cursor on the Source. # It then runs the program for the default mode. There is one program for each mode, and # it acts as a dispatcher. It finds a template which matches the cursor node and runs # the program for that template. op = add(root.code.start, 'do_search', '/xslt/Result') op = add(op, 'mark_selection') op = add(op, 'do_search', '/xslt/Source') op = add(op, 'play', 'XSLT/Default mode') # This program copies a text node to the output prog = Program('DefaultText') root.add_sub(prog) op = add(prog.code.start, 'yank') op = add(op, 'mark_switch') op = add(op, 'put_as_child_end') op = add(op, 'move_left') op = add(op, 'mark_switch') # To start with, the cursor is on the source document node and # the mark is on the result document node. # # The mode program is called with: # => Cursor = context node # Mark = result parent (append children here) # <= Cursor is undefined # Mark is unchanged reader = StylesheetReader() sheet = reader.fromDocument(doc) global s s = sheet # sheet.matchTemplates is { mode -> { type -> { (ns, name) -> [match] for elements # { [match] otherwise # # Each match is ((precedence,?), pattern, axis_type, TemplateElement) # # The list of matches is sorted; use the first that matches. Multiple lookups # may be required (eg, lookup 'html' then None (for 'node()' and '*')). # Patterns like 'text()|comment()' are broken down into two match elements. # XXX: Could have two modes with the same name but different namespaces... i = 1 for mode in sheet.matchTemplates.keys(): mode_name = mode_prog_name(mode) prog = Program(mode_name) root.add_sub(prog) tests = prog.code.start print "Mode", mode types = sheet.matchTemplates[mode] #loose_ends = [] all = [] for type in types.keys(): if type == Node.ELEMENT_NODE: templates = types[type].values()[:] else: templates = [types[type]] # templates is a list of templates for items of this type when in this mode for tl in templates: for t in tl: all.append(t) all = all[:] all.sort() all.reverse() # highest numbers first last = None for sort_key, (unused_pattern, axis_type, template) in all: pattern = `template._match` if pattern == last: continue last = pattern #print sort_key, pattern, axis_type, template name = pattern.replace('/', '%') temp = Program(`i` + '-' + name) op = add(temp.code.start, 'mark_switch') make_template(op, template) i += 1 prog.add_sub(temp) if pattern.startswith('/'): if pattern == '/': pattern = '' pattern = '/xslt/Source' + pattern # XXX: Hack tests = add(tests, 'xslt_fail_if', pattern) op = Op(action = ['play', temp.get_path()]) tests.link_to(op, 'fail') add(op, 'mark_switch') #loose_ends.append(op) # Now add the built-in rules #print "Tidy", loose_ends tests = add(tests, 'xslt_fail_if', 'text()') op = Op(action = ['play', 'XSLT/DefaultText']) tests.link_to(op, 'fail') tests = add(tests, 'do_global', '*') tests = add(tests, 'map', prog.get_path()) #tests = add(tests, 'mark_switch') #tests = add(tests, 'mark_switch') #[ op.link_to(tests, 'next') for op in loose_ends ] root.modified = 0 return root
def add_program_with_children(self): self.program = Program() self.program.add_initial_children()
class HeeksCNC: def __init__(self): self.tree = None self.program = None self.cad = None self.widgets = WIDGETS_WX self.program_window = None self.output_window = None self.machine_state = None def on_post_process(self): import wx wx.MessageBox("post process") def RunPythonScript(self): # clear the output file f = open(self.program.GetOutputFileName(), "w") f.write("\n") f.close() # Check to see if someone has modified the contents of the # program canvas manually. If so, replace the m_python_program # with the edited program. We don't want to do this without # this check since the maximum size of m_textCtrl is sometimes # a limitation to the size of the python program. If the first 'n' characters # of m_python_program matches the full contents of the m_textCtrl then # it's likely that the text control holds as much of the python program # as it can hold but more may still exist in m_python_program. text_control_length = self.program_window.textCtrl.GetLastPosition() if self.program.python_program[0:text_control_length] != self.program_window.textCtrl.GetValue(): # copy the contents of the program canvas to the string self.program.python_program = self.program_window.textCtrl.GetValue() from PyProcess import HeeksPyPostProcess HeeksPyPostProcess(True) def on_make_python_script(self): self.program.RewritePythonProgram() def on_run_program_script(self): self.RunPythonScript() def on_post_process(self): self.program.RewritePythonProgram(self) self.RunPythonScript() def on_open_nc_file(self): import wx dialog = wx.FileDialog(self.cad.frame, "Open NC file", wildcard = "NC files" + " |*.*") dialog.CentreOnParent() if dialog.ShowModal() == wx.ID_OK: from PyProcess import HeeksPyBackplot HeeksPyBackplot(dialog.GetPath()) def on_save_nc_file(self): import wx dialog = wx.FileDialog(self.cad.frame, "Save NC file", wildcard = "NC files" + " |*.*", style = wx.FD_SAVE + wx.FD_OVERWRITE_PROMPT) dialog.CentreOnParent() dialog.SetFilterIndex(1) if dialog.ShowModal() == wx.ID_OK: nc_file_str = dialog.GetPath() f = open(nc_file_str, "w") if f.errors: wx.MessageBox("Couldn't open file" + " - " + nc_file_str) return f.write(self.ouput_window.textCtrl.GetValue()) from PyProcess import HeeksPyPostProcess HeeksPyBackplot(dialog.GetPath()) def on_cancel_script(self): from PyProcess import HeeksPyCancel HeeksPyCancel() def add_menus(self): machining_menu = self.cad.addmenu('Machining') global heekscnc_path AddOperationMenuItems(machining_menu) self.cad.add_menu_item(machining_menu, 'Make Program Script', self.on_make_python_script, heekscnc_path + '/bitmaps/python.png') self.cad.add_menu_item(machining_menu, 'Run Program Script', self.on_run_program_script, heekscnc_path + '/bitmaps/runpython.png') self.cad.add_menu_item(machining_menu, 'Post Process', self.on_post_process, heekscnc_path + '/bitmaps/postprocess.png') self.cad.add_menu_item(machining_menu, 'Open NC File', self.on_open_nc_file, heekscnc_path + '/bitmaps/opennc.png') self.cad.add_menu_item(machining_menu, 'Save NC File', self.on_save_nc_file, heekscnc_path + '/bitmaps/savenc.png') self.cad.add_menu_item(machining_menu, 'Cancel Python Script', self.on_cancel_script, heekscnc_path + '/bitmaps/cancel.png') def add_windows(self): from Tree import Tree self.tree = Tree() self.tree.Add(self.program) self.tree.Refresh() if self.widgets == WIDGETS_WX: from wxProgramWindow import ProgramWindow from wxOutputWindow import OutputWindow self.program_window = ProgramWindow(self.cad.frame) self.output_window = OutputWindow(self.cad.frame) self.cad.add_window(self.program_window) self.cad.add_window(self.output_window) def on_new(self): self.add_program_with_children() self.tree.Recreate() def on_open(self): # to do, load the program pass def on_save(self): # to do, save the program pass def start(self): global heekscnc_path import wx import os import sys full_path_here = os.path.abspath( __file__ ) full_path_here = full_path_here.replace("\\", "/") heekscnc_path = full_path_here slash = heekscnc_path.rfind("/") if slash != -1: heekscnc_path = heekscnc_path[0:slash] slash = heekscnc_path.rfind("/") if slash != -1: heekscnc_path = heekscnc_path[0:slash] self.add_program_with_children() self.add_menus() self.add_windows() self.cad.on_start() def add_program_with_children(self): self.program = Program() self.program.add_initial_children()