def main(): num_args = len(sys.argv)-1 try: if num_args == 0: sys.stderr.write("Error: not enough arguments\n") if num_args > 2: sys.stderr.write("Error: too many arguments\n") if sys.argv[1][1] == 's': if num_args == 1: # read from stdin print "hello" elif num_args == 2: # read from file f = open(sys.argv[2], 'r') input_line = "" for line in f: input_line += line s = Scanner(input_line) s.all() f.close() elif sys.argv[1][1] == 'c': sys.stderr.write("Error: invalid option\n") elif sys.argv[1][1] == 't': sys.stderr.write("Error: invalid option\n") elif sys.argv[1][1] == 'a': sys.stderr.write("Error: invalid option\n") elif sys.argv[1][1] == 'i': sys.stderr.write("Error: invalid option\n") else: sys.stderr.write("Error: invalid option\n") except Exception as e: pass
def main(): while (True): Input = input() if Input == "q" or Input == "Q": break sccaner = Scanner(Input) if (sccaner.get_tokens() == True): pass #print(sccaner.tokens) else: print("some thing wrong with sccaner") continue parser = Parser(sccaner.tokens) output = parser.compute_exp() if parser.error: print("some thing wrong with parser") else: print(output)
def test_for_error_on_strings_that_start_with_numbers(self): """ 4pple """ with open('./test_cases/StringStartWithNumbers.txt') as f: fileContents = f.read() with self.assertRaises(BadTokenExpection): Scanner.scan(fileContents)
def test_for_error_on_bad_numbers(self): """ 1.1.2 """ with open('./test_cases/BadNumber.txt') as f: fileContents = f.read() with self.assertRaises(BadTokenExpection): Scanner.scan(fileContents)
def main(): input_file = sys.argv[1] # output_file = open('token_file.txt', 'w') s = Scanner() s.open_file(input_file) s.get_token() p = Parser(s.tokens) print p.system_goal()
def __init__(self, fileName): try: self.sourceFile = open(fileName, 'r') except IOError: sys.exit("Source file not found") self.scanner = Scanner(self.sourceFile) self.symbolTableStack = SymbolTableStack() self.analyzer = Analyzer(fileName, self.symbolTableStack)
def initializescan(url): print(url) report = Report(url) scanner = Scanner() results = scanner.scan(url) # TODO: send EMAIL with LINK to report results report.update_results(str(results)) return
def main(): args = parser() global ip ip = net.getValidIp(args.ip) if ip == False: print("please enter a valid IP") sys.exit() scanner = Scanner(args, ip) result, counter = scanner.scan() showResult(result, counter)
def __init__(self, input_code: str): # TODO initialize self.symbol_table = SymbolTable() self.symbol_table.new_scope() self.pars_stack = Stack() self.scanner = Scanner(input_code, symbol_table=self.symbol_table) self.dfa = TransitionDiagram() # TODO self.dfa.make_diagrams() self.look_ahead = "" self.current_token = None self.current_token_info = None self.pars_stack.push(self.dfa.start_state) self.code_generator = CodeGenerator(self.symbol_table)
def test_for_error_on_bad_assignment(self): """ read test assignment x := 7 y = 7 write """ with open('./test_cases/BadAssignment.txt') as f: fileContents = f.read() with self.assertRaises(BadTokenExpection): Scanner.scan(fileContents)
class Camera: camera = None grid = None def __init__(self, rubik_dimensions=3, camera_size=(640, 480)): """Initialize scanner Keyword arguments: rubik_dimensions -- Rubik's cube size (default 3) camera_size -- width and height of the camera (default (640, 480) ) """ self.cube_size = rubik_dimensions self.VIDEO_WIDTH = camera_size[0] self.VIDEO_HEIGHT = camera_size[1] # Setting camera properties self.camera = cv2.VideoCapture(0) self.camera.set(CV_CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, self.VIDEO_WIDTH) self.camera.set(CV_CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, self.VIDEO_HEIGHT) self.camera.set(cv2.cv.CV_CAP_PROP_BRIGHTNESS, 100) self.camera.set(cv2.cv.CV_CAP_PROP_CONTRAST, 100) self.scanner = Scanner(rubik_dimensions, camera_size, 3) def scan(self, fps=30): while (True): ret, bgr_frame = self.camera.read() # Change from BGR to RGB b, g, r = cv2.split(bgr_frame) frame = cv2.merge([r, g, b]) self.scanner.draw_grid(frame) # Back to BGR r, g, b = cv2.split(frame) bgr_frame = cv2.merge([b, g, r]) # Reflect and display the resulting frame bgr_frame = cv2.flip(bgr_frame, 1) cv2.imshow('Rubik\'s cube scanner', bgr_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break def release(self): # When everything done, release the capture self.camera.release() cv2.destroyAllWindows()
class Camera: camera = None grid = None def __init__(self, rubik_dimensions = 3, camera_size = (640, 480)): """Initialize scanner Keyword arguments: rubik_dimensions -- Rubik's cube size (default 3) camera_size -- width and height of the camera (default (640, 480) ) """ self.cube_size = rubik_dimensions self.VIDEO_WIDTH = camera_size[0] self.VIDEO_HEIGHT = camera_size[1] # Setting camera properties self.camera = cv2.VideoCapture(0) self.camera.set(CV_CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, self.VIDEO_WIDTH); self.camera.set(CV_CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, self.VIDEO_HEIGHT); self.camera.set(cv2.cv.CV_CAP_PROP_BRIGHTNESS, 100) self.camera.set(cv2.cv.CV_CAP_PROP_CONTRAST, 100) self.scanner = Scanner(rubik_dimensions, camera_size, 3) def scan(self, fps = 30): while(True): ret, bgr_frame = self.camera.read() # Change from BGR to RGB b, g, r = cv2.split(bgr_frame) frame = cv2.merge([r, g, b]) self.scanner.draw_grid(frame) # Back to BGR r, g, b = cv2.split(frame) bgr_frame = cv2.merge([b, g, r]) # Reflect and display the resulting frame bgr_frame = cv2.flip(bgr_frame,1) cv2.imshow('Rubik\'s cube scanner', bgr_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break def release(self): # When everything done, release the capture self.camera.release() cv2.destroyAllWindows()
def __init__(self): # Init GUI super(PDMSGUI, self).__init__() loadUi('QT/PDMS/PDMS_05.ui', self) self.setWindowTitle('PDMS') # Init Scan tab # Init PDF Viewer self.webViewPDF = QtWebEngineWidgets.QWebEngineView() self.webViewPDF.setObjectName("webView") self.gridBrowser.addWidget(self.webViewPDF, 0, 0, 1, 1) self.webViewPDF.load( QtCore.QUrl.fromUserInput('%s?file=%s' % (PDFJS, PDF))) # Init HTML Viewer self.webViewHTML = QtWebEngineWidgets.QWebEngineView() self.webViewHTML.setObjectName("webView") self.gridBrowser.addWidget(self.webViewHTML, 0, 1, 1, 1) #self.webViewHTML.setUrl(QtCore.QUrl("http://www.google.com/")) self.webViewHTML.setUrl( QtCore.QUrl( "file:///H:/repos/PDMS/data/docs/docHTML/doc_2018212_129_24.HTML" )) # Set callbacks self.ScanButton.clicked.connect(self.on_button_scan) self.AddTag.clicked.connect(self.add_tag) self.AddDoc.clicked.connect(self.saveDoc) # Init Objects self.access = DocumentsFileAccess(path_Documents) self.scanner = Scanner(self.access) self.scanner.loadDocuments() # Init Search tab self.searchViewPDF = QtWebEngineWidgets.QWebEngineView() self.searchViewPDF.setObjectName("Search Document") self.searchGrid.addWidget(self.searchViewPDF, 0, 0, 1, 1) self.searchViewPDF.load( QtCore.QUrl.fromUserInput('%s?file=%s' % (PDFJS, PDF))) self.DocS_Access = DocumentsFileAccess(path_Documents) self.DocS = DocSearcher(self.DocS_Access) self.DocS.loadDocuments() # Set callbacks self.SearchButton.clicked.connect(self.on_button_search) self.DocsCombo.currentIndexChanged.connect(self.onActivated) self.SearchTag.returnPressed.connect(self.on_key)
def run(self, source): self.error_report.had_error = False scanner = Scanner(source, self.error_report) tokens = scanner.scan_tokens() parser = Parser(tokens, self.error_report) expression = parser.parse() if self.error_report.had_error: return result = expression.interpret() print(result)
def main(): block = open("Testfiles/many.i", "r") test = Scanner(block) word = test.next_word() while word != "EoF": # print "tokens", test.tokens if word is not None: if word[0] == "invalid": lex_error(word) else: print >> sys.stdout, str(word[2]) + ": < " + word[0] + ', \"' + word[1] + "\" >" #print "tokens", test.tokens word = test.next_word()
def __init__(self, file_name): self.symbol_table = SymbolTable() self.pc = 2 self.symbol_table.entries.append( SymbolTableEntry('output', 'ID', None, 1, None, None)) self.scope_stack: List[int] = [0] self.memory_manager = MemoryManager() self.scanner = Scanner(file_name, self.symbol_table) self.semantic_analyser = SemanticAnalyser(self.symbol_table, self.scope_stack, self.pc, self.memory_manager) self.code_generator = CodeGenerator(self.symbol_table, self.memory_manager, self.pc, self.scope_stack)
def process_image(self, image): file_converter = FileConverter() #convert the image to byte string image_bytes = file_converter.png_to_jpeg(image) scanner = Scanner() #scan the image and give it a birds eye view, returns a np of pixels that makes up the image scan_np = scanner.scan(image_bytes) #extract the individual answers from the scanned test extractor = Extract() answers = extractor.get_all_answers(scan_np, 5) color = Color() bw_answers = color.all_ans_to_bw(answers) size = Size() DIM = (28, 28) shrunk_images = size.shrink_images(bw_answers, DIM) #convert the answer images to a single array, which we used in training our model answers_flat = file_converter.convert_images( shrunk_images) #returns image as (1, 28, 28, 1) and as type float #now that we have a list of images of the answers as bw 1D numpy arrays, # we can run them through our model and grade them # first we need to load our model model_loader = ModelLoader() MODEL_JSON = 'models/modified_model_98.json' MODEL_WEIGHTS = 'models/modified_model_98.h5' model = model_loader.load_model_2(MODEL_JSON, MODEL_WEIGHTS) #compile model model.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) grader = Grader() answers = grader.get_answers(answers_flat, model) #get the images as a 784 (28x28) length string so we can store the data in a database ans_strings = file_converter.get_string_images(answers_flat) compressed_images = file_converter.compress_images(ans_strings) #add the images to database so we can create a large dataset of handwritten letters # storage = Storage() # storage.insert(answers, compressed_images) return answers
class ClientThread(threading.Thread): def __init__(self): self.sc=Scanner() threading.Thread.__init__(self) self.s = xmlrpclib.ServerProxy('http://localhost:9997') def toString(self): x= "La operacion "+str(self.sc.getNro1())+" "+self.sc.getOperation()+" "+str(self.sc.getNro2())+" = "+str(mekeOperation(self.sc,self.s)) return x def run(self): #time.sleep(3) print "Llamada cliente1 " print self.toString()
class Server(WebSocketHandler): users = set() # 用来存放在线用户的容器 scanner = Scanner() token_cls = Token() RestartServer = RestartServer() def open(self): logger.info("client " + self.request.remote_ip + " connected") self.users.add(self) # 建立连接后添加用户到容器中 def on_message(self, message): logger.info("Recive message: " + message) message = message.split('?s=') msg_type = message[0] if len(message) > 1: msg_info = message[1] if msg_type == "GET_DATA": data = self.scanner.run() if msg_type == "GET_TOKEN": data = self.token_cls.get_token(msg_info) if msg_type == "RESTART": data = self.RestartServer.run(msg_info, self) self.write_message(data) def on_close(self): logger.info("client " + self.request.remote_ip + " cloed") self.users.remove(self) # 用户关闭连接后从容器中移除用户 def check_origin(self, origin): return True # 允许WebSocket的跨域请求
def run(self, data, prompt=False): try: tokens = Scanner(data).scanTokens() if prompt: tokens = self.continueLines(tokens) if not tokens: return ast, errors = Parser(tokens).parse() if errors: return self.alarmErrors('parser', errors) LispPrinter().printProgram(ast) ids, errors = self.resolver.resolve(ast) if errors: return self.alarmErrors('resolver', errors) #self.compiler.compile(ast) #self.vm.replace(self.compiler.code, self.compiler.data) #self.vm.print() #self.vm.run() #if self.vm.stack: print(self.vm.pop()) rlt = self.interp.interpret(ast, ids=ids) if rlt is not None: print(stringify(rlt)) except LoxError as ex: print(ex) self.hadError = True
def match(current_token, expected_tt): """ Matches the current token with an expected_tt token or token type, then reads the next token from the scanner. If a match cannot be made, raises a Parser.Error object. :param current_token: The current token being read :param expected_tt: The expected TokenType :return: None """ assert (isinstance(current_token, Token)) assert (isinstance(expected_tt, TokenType)) # If the current token matches the expected_tt token, or token type, if current_token.t_type == expected_tt: # then get the next token and put it in current_token current_token.assignTo(Scanner.get_token(Parser.file_reader)) else: # otherwise, we have an error. line_data = Parser.file_reader.get_line_data() raise MatchError( "At line %d, column %d: " % (line_data["Line_Num"], line_data["Column"]) + "Expected %r but found %r, but they were unequal.\n" % (expected_tt, current_token) + "%s" % line_data["Line"] + " " * line_data["Column"] + "^\n")
def p_handler(self): file = open(self.filename) scanner = Scanner(self.filename) parser = Parser() line = file.readline() line_count = 1 head = DoublyLinkedList() prev_node = DoublyLinkedList() prev_node.set_prev(head) grammar_error = False grammar_error_count = 0 lexical_error = False success_count = 0 while line: res = [] while line[0] == "/" and len(line) > 2 and line[1] == "/": line = file.readline() line_count += 1 if not line: res.append((9, "", line_count - 1)) #if not lexical_error and not grammar_error: #print("Successfully parsed the ILOC file, finding " + str(success_count) + " ILOC operations") return head.next.next, lexical_error or grammar_error if line[-1] != '\n': line = line + '\n' self.buffer = line encountered_error = False while self.buffer[self.index] != "\n": word_pair = self.word_scan(line_count) if word_pair[0] == -1: lexical_error = True encountered_error = True break if word_pair[0] != -2: res.append(word_pair) if self.index == len(self.buffer): break if not encountered_error: cur_node = parser.parse_line(res) if cur_node: success_count += 1 prev_node.set_next(cur_node) prev_node = prev_node.next else: if line[0] != "\n": grammar_error = True grammar_error_count += 1 self.buffer = "" self.index = 0 line = file.readline() line_count += 1 file.close() #if not lexical_error and not grammar_error: #print("Successfully parsed the ILOC file, finding " + str(success_count) + " ILOC operations") #else: if grammar_error: print("Parser found " + str(grammar_error_count) + " syntax errors") #print (lexical_error) #print (grammar_error) return head.next.next, lexical_error or grammar_error
def on_query_completions(self, view, prefix, locations): # get the open project folders pdirs = view.window().folders() pline = self._get_pointer_line(view) sc = Scanner(pline) completions = sc.get_comp_list() print 'Got Completions: ' + repr(completions) + ' in ' + os.getcwd() #completions = ['hello', 'blub'] return (completions, sublime.INHIBIT_EXPLICIT_COMPLETIONS)
def test_order_info_frame(): posSystem = Scanner(config_dev.CONFIG) order_info = posSystem.wp_rest_interface.get_order_info(order_id) print order_info order_info_frame = Frame_Order(master=Tkinter.Tk(), order_data=order_info) order_info_frame.mainloop()
def test_main(self): first_scanner = Scanner(TOKENS, code) print('List of tokens after lexical analysis contains: ') pprint(first_scanner.list_tokens) first_parser = Parser(first_scanner) trial = Runner(first_parser) main = trial.main() return main
def main(): # submission code FILE_NAME = input("Input the file name: ") chario = Chario(FILE_NAME) # link the input source file scanner = Scanner(chario) parser = Parser(chario, scanner) # do syntax analysis parser.subprogramBody()
def __init__(self): self.scanner = Scanner() self.code_gen = CodeGen() self.prod_number = {} self.grammar_dict = self.read_raw_grammar() self.semantic_stack = ['@KIR', 'PHEAD'] # print("grammar : ", self.grammar_dict) self.nullable_dict = {} self.fill_nullable_dict() # print("is_nullable : ", self.nullable_dict) self.first_dict = self.compute_first_dict() # print("first : ", self.first_dict) self.follow_dict = self.compute_follow_dict() # print("follow : ", self.follow_dict) self.predict_dict = self.compute_predict_dict() # print("predict : ", self.predict_dict) self.parse_table = self.generate_parse_table()
def __init__(self, string: str): re_str_dict = { "line": r'-+\s*', "item_begin": r'-\s.*', "str_begin_with_sym_sub": r'-+[^-\s]+|-+[^-]+.+', "str_begin_without_sym_sub": r'[^-].*', "space_line": r'\s*' } tree_dict = { 'Doc': [['doc_parts']], 'doc_parts': [['space_lines', 'doc_part', 'doc_parts'], ['space_lines', 'doc_part', 'space_lines']], 'doc_part': [['Select Part'], ['Fill Part'], ['Question Part'], ['Short Question Part']], 'space_lines': [['space_line', 'space_lines'], ['space_line'], []], 'Select Part': [['title', 'line', 'items']], 'Fill Part': [['title', 'line']], 'Question Part': [['title_no_items', 'items']], 'Short Question Part': [['title']], 'title': [['strs']], 'title_no_items': [['strs_no_items']], 'items': [['item', 'items'], ['item']], 'item': [['item_begin', 'item_ends'], ['item_begin']], 'item_ends': [['str_begin_without_sym_sub', 'item_ends'], ['str_begin_with_sym_sub', 'item_ends'], ['str_begin_without_sym_sub'], ['str_begin_with_sym_sub']], 'strs': [['singlestr', 'strs'], ['singlestr']], 'strs_no_items': [['singlestr_no_items', 'strs_no_items'], ['singlestr_no_items']], 'singlestr': [['str_begin_without_sym_sub'], ['item_begin'], ['str_begin_with_sym_sub']], 'singlestr_no_items': [['str_begin_without_sym_sub'], ['str_begin_with_sym_sub']] } reduce_tree_list = [ 'doc_parts', 'doc_part', 'strs', 'singlestr', 'str_begin_without_sym_sub', 'item_begin', 'item_begin', 'item_ends', 'items', 'item_end', 'singlestr_no_items', 'strs_no_items', '(:delete item:)space_lines', '(:delete item:)line', '(:delete item:)space_line', '(:change name to:title:)title_no_items' ] self.scanner = Scanner(re_str_dict) self.parser = Parser(tree_dict, reduce_tree_list) self.string = string
def read_records(input_file_name): record_list = [] file = open(input_file_name) scan = Scanner("") for line in file.readlines(): list_line = [] line = line.rstrip() scan.fromstring(line) username = scan.readtoken() quotes = '"{}"'.format(''.join( str(e) for e in re.findall('"([^"]*)"', line))) date_str = line[-19:] date_str = date_str.lstrip() date = datetime.strptime(date_str, '%Y %m %d %H:%M:%S') list_line.append(username) list_line.append(quotes) list_line.append(date) record_list.append(list_line) scan.readline() return record_list
def continueLines(self, tokens): self.tokens.extend(tokens) if Scanner.checkParen(self.tokens) > 0: # uncompleted tokens = [] self.tokens.pop() # pop EOF else: # matched or error tokens = self.tokens self.tokens = [] return tokens
def test_order_item_info_frame(): posSystem = Scanner(config_dev.CONFIG) order_data = posSystem.wp_rest_interface.get_order_info(order_id) print order_data item_info_frame = Frame_Product(master=Tkinter.Tk(), item_data=order_data["line_items"][0]) item_info_frame.mainloop()
def test_for_no_error_on_duplicates(self): """ read write test duplicate another duplicate read write """ with open('./test_cases/WithDuplicates.txt') as f: fileContents = f.read() correctTokens = ['read', 'write', 'id', 'id', 'id', 'id', 'read', 'write'] tokens = Scanner.scan(fileContents) self.makeSureArraysAreTheSame(tokens, correctTokens)
def test_for_no_error_on_strings_that_start_with_letters_but_have_numbers(self): """ f00bar m8 """ with open('./test_cases/StringStartWithLetter.txt') as f: fileContents = f.read() correctTokens = ['id', 'id'] tokens = Scanner.scan(fileContents) self.makeSureArraysAreTheSame(tokens, correctTokens)
class Main: def __init__(self, src, dst, dports, iface): self.src = src self.dst = dst self.dports = dports self.iface = iface self.inp_queue = Queue() self.outp_queue = Queue() self.res_queue = Queue() self.preceiver = PacketReceiver(iface = self.iface, queue = self.inp_queue) self.psender = PacketSender(iface = self.iface, queue = self.outp_queue) self.scanner = Scanner(self.inp_queue, self.outp_queue, self.res_queue, self.src, self.dst, self.dports) def start(self): self.preceiver.start() self.psender.start() self.scanner.start()
def __init__(self, filename): self.file_obj = open(filename, "r") self.scanner = Scanner.Scanner(self.file_obj) self.IR = IR.IR() self.new_record = DoublyLinkedList() self.result = False self.num_errors = 0 self.valid_operation = 0 self.max_sr = 0 self.is_store = False
def __init__(self): # app title appuifw.app.title = u"Sissi" # app lock self.lock = e32.Ao_lock() # ensure data dir exists self.datadir = os.path.join(u"C:\\Data", u"Sissi") if not os.path.exists(self.datadir): os.makedirs(self.datadir) # create a directory for temporary data self.cachedir = u"D:\\Sissi" if not os.path.exists(self.cachedir): os.makedirs(self.cachedir) # get screen resolution self.screen = sysinfo.display_pixels() # extra classes instantiated self.scanner = Scanner(self) self.netmapper = NetMapper(self) self.map = Map(self) self.cos_api = COSApi(self) # timer self.t = e32.Ao_timer() self.active = False # set canvas self.activate() # configuration / settings self.draw_screen('reading config') self.config_file = os.path.join(self.datadir, "settings.ini") self.config = {} # TODO: read these from a configuration file self.apid = None # Default access point self.read_config() if self.config.has_key("apid"): self._select_access_point(self.config["apid"]) # set extra handler to be called on each GPS loop self.scanner.set_extra_handler(self.loop) # update our menu self._update_menu() self.draw_screen('ready!') # self.debug(self.screen) self.scanner_handler() # start scanning automatically # set exit key handler appuifw.app.exit_key_handler = self.exit_key_handler
def main(argv): scannerDebug,parserDebug,grammarDebug,offset = parseOptions(argv) phrase = parsePhrase(argv, offset) gFile = "./testing/simple_grammar" # parse the grammer g = GrammarParser(gFile, grammarDebug) definition,relations = g.getDetails() # scan s = Scanner(offset,phrase,definition,scannerDebug) s.scan() ### TODO check for lexing errors before parsing # parse classes, lexemes, keyList, tokens = s.getParseInfo() p = Parser(tokens,classes,lexemes,keyList,relations,parserDebug) p.parse() root = makeTree(p.orderedTokens) print execute(root)
def scan_project(): scanner = Scanner('/Users/zhengxiankai/Documents/Code/WebCacheTest/WebCacheTest.xcodeproj/project.pbxproj') target1 = 'WebCacheTest copy' target2 = 'WebCacheTest' build_phases1 = scanner.get_build_phases_by_target_name(target1) build_phases2 = scanner.get_build_phases_by_target_name(target2) print ' "{0}" 包含,而 "{1}" 不包含的文件\n'.format(target1, target2) for key1, kv1 in build_phases1.iteritems(): kv2 = build_phases2[key1] for _, v in kv1.iteritems(): if v not in kv2.itervalues(): print '\t' + v print '\n' print ' "{0}" 包含,而 "{1}" 不包含的文件\n'.format(target2, target1) for key1, kv1 in build_phases2.iteritems(): kv2 = build_phases1[key1] for _, v in kv1.iteritems(): if v not in kv2.itervalues(): print '\t' + v
def __init__(self, rubik_dimensions = 3, camera_size = (640, 480)): """Initialize scanner Keyword arguments: rubik_dimensions -- Rubik's cube size (default 3) camera_size -- width and height of the camera (default (640, 480) ) """ self.cube_size = rubik_dimensions self.VIDEO_WIDTH = camera_size[0] self.VIDEO_HEIGHT = camera_size[1] # Setting camera properties self.camera = cv2.VideoCapture(0) self.camera.set(CV_CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, self.VIDEO_WIDTH); self.camera.set(CV_CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, self.VIDEO_HEIGHT); self.camera.set(cv2.cv.CV_CAP_PROP_BRIGHTNESS, 100) self.camera.set(cv2.cv.CV_CAP_PROP_CONTRAST, 100) self.scanner = Scanner(rubik_dimensions, camera_size, 3)
print 'error: the drier program should be invoked as follows: Invocation = \"./sc\" [\"-\" (\"-\" (\"s\"|\"c\"|\"t\"|\"a\"|\"i\")] [filename]' exit (-1) #if there are no argument except for the name of the program, the driver is supposed to generate code for an input program elif len(sys.argv) == 1: input_string = '' new_line = '' while new_line != 'stop\n': try: input_string += new_line new_line = raw_input() + '\n' except (EOFError, KeyboardInterrupt): break #construct the object of Scanner by it's constructor scanner = Scanner(input_string) #produce a list of tokens by calling it's function token_array = scanner.all() #if produces the error message, then display it if scanner.have_error() == True: print scanner.get_error_message() else: output = Output() factory = AstFactory(output) parser = Parser(token_array, output, factory) #print 'parse start' parser.parse() print 'parse success' if parser.get_error_message() != '': print parser.get_error_message()
def run(self): #print dir(self) scanner = Scanner(self.program, self.url, self.cookies, self.headers, self.output, self.source) scanner.run() scanner.report() pass
exit() if options['filter']: options['filter']=options['filter'].split(",") LOG.info("Scanning with filter: %s"%options['filter']) if options['blacklist']: options['blacklist']=options['blacklist'].split(",") LOG.info("Skipping blacklisted files: %s"%options['blacklist']) if options['modes']: options['modes']=options['modes'].split(",") LOG.info("option probing modes enabled: %s"%options['modes']) # start the magic results = {} for path in arguments: scanner = Scanner(path,filter=options['filter'], blacklist=options['blacklist'], recursive=not(options['no-recursion'])) # init aggro_args settings x = Exploit() # general functionality x_aggro = AggroArgs() # attack speciic stuff for nr,f in enumerate(scanner.walk()): # skip non-executable files if not (os.path.isfile(f) and os.access(f, os.X_OK)): LOG.debug("[>] Skipping - not executable - %s"%f) continue # skip non elf files if os.name in ['posix','mac']: if not any(s in x.shellex("file -L '%s'"%f, shell=True).lower() for s in ['elf','executable']):
class Parser(object): scanner = None analyzer = None sourceFile = None symbolTableStack = None lookahead = '' firstIdFlag = False # Constructor def __init__(self, fileName): try: self.sourceFile = open(fileName, 'r') except IOError: sys.exit("Source file not found") self.scanner = Scanner(self.sourceFile) self.symbolTableStack = SymbolTableStack() self.analyzer = Analyzer(fileName, self.symbolTableStack) def parse(self): self.lookahead = self.scanner.getNextToken() self.systemGoal() print "Parsing Successful" self.sourceFile.close() def match(self, toMatch): lexeme = self.scanner.lexeme if(self.lookahead == toMatch): self.lookahead = self.scanner.getNextToken() return lexeme else: # print the caller # print inspect.stack()[1][3] self.matchError(toMatch) def systemGoal(self): if self.lookahead is "MP_PROGRAM": # 1 SystemGoal -> Program eof self.program() else: self.error("MP_PROGRAM") def program(self): if self.lookahead is "MP_PROGRAM": # 2 Program -> ProgramHeading ";" Block "." self.programHeading() self.match("MP_SCOLON") self.block() self.match("MP_PERIOD") else: self.error("MP_PROGRAM") def programHeading(self): if self.lookahead is "MP_PROGRAM": # 3 ProgramHeading -> "program" ProgramIdentifier self.match("MP_PROGRAM") self.programIdentifier() self.symbolTableStack.addTable('Main', self.analyzer.getLabel()) self.analyzer.genBranch(self.analyzer.getLabel()) else: self.error("MP_PROGRAM") def block(self): if self.lookahead in ["MP_VAR", "MP_BEGIN", "MP_FUNCTION", "MP_PROCEDURE"]: # 4 Block -> VariableDeclarationPart ProcedureAndFunctionDeclarationPart StatementPart self.variableDeclarationPart() self.procedureAndFunctionDeclarationPart() self.statementPart() else: self.error('"MP_VAR", "MP_BEGIN", "MP_FUNCTION", "MP_PROCEDURE"') def variableDeclarationPart(self): if self.lookahead is "MP_VAR": # 5 VariableDeclarationPart -> "var" VariableDeclaration ";" VariableDeclarationTail self.match("MP_VAR") self.firstIdFlag = True self.variableDeclaration() self.match("MP_SCOLON") self.variableDeclarationTail() elif self.lookahead in ["MP_BEGIN", "MP_FUNCTION", "MP_PROCEDURE"]: return else: self.error('"MP_VAR", "MP_BEGIN", "MP_FUNCTION", "MP_PROCEDURE"') def variableDeclarationTail(self): if self.lookahead in ["MP_PROCEDURE", "MP_FUNCTION", "MP_BEGIN"]: # 7 VariableDeclarationTail -> lambda return elif self.lookahead is "MP_IDENTIFIER": # 6 VariableDeclarationTail -> VariableDeclaration ";" VariableDeclarationTail self.variableDeclaration() self.match("MP_SCOLON") self.variableDeclarationTail() else: self.error('"MP_PROCEDURE", "MP_FUNCTION", "MP_BEGIN", "MP_IDENTIFIER", "MP_SCOLON"') def variableDeclaration(self): if self.lookahead is "MP_IDENTIFIER": # 8 VariableDeclaration -> IdentifierList ":" Type idList = self.identifierList() self.match("MP_COLON") varType = self.type() for name in idList: self.symbolTableStack.getCurrentTable().insertEntry(name, 'var', varType, '', self.firstIdFlag) self.firstIdFlag = False else: self.error("MP_IDENTIFIER") def type(self): if self.lookahead is "MP_INTEGER": # 9 Type -> "Integer" self.match("MP_INTEGER") return 'Integer' elif self.lookahead is "MP_FLOAT": # 108 Type -> "Float" self.match("MP_FLOAT") return 'Float' elif self.lookahead is "MP_STRING": # 109 Type -> "String" self.match("MP_STRING") return 'String' elif self.lookahead is "MP_BOOLEAN": # 110 Type -> "Boolean" self.match("MP_BOOLEAN") return 'Boolean' else: self.error("Integer, Float, String, Boolean") def procedureAndFunctionDeclarationPart(self): if self.lookahead is "MP_PROCEDURE": # 10 ProcedureAndFunctionDeclarationPart -> ProcedureDeclaration ProcedureAndFunctionDeclarationPart self.procedureDeclaration() self.procedureAndFunctionDeclarationPart() elif self.lookahead is "MP_FUNCTION": # 11 ProcedureAndFunctionDeclarationPart -> FunctionDeclaration ProcedureAndFunctionDeclarationPart self.functionDeclaration() self.procedureAndFunctionDeclarationPart() elif self.lookahead is "MP_BEGIN": # 12 ProcedureAndFunctionDeclarationPart -> lambda return else: self.error("Procedure, Function, Begin") def procedureDeclaration(self): if self.lookahead is "MP_PROCEDURE": # 13 ProcedureDeclaration -> ProcedureHeading ";" Block ";" self.procedureHeading(); self.match('MP_SCOLON') self.block() self.match('MP_SCOLON') else: self.error("Procedure") def functionDeclaration(self): if self.lookahead is "MP_FUNCTION": # 14 FunctionDeclaration -> FunctionHeading ";" Block ";" self.functionHeading() self.match("MP_SCOLON") self.block() self.match("MP_SCOLON") else: self.error("Function") def procedureHeading(self): if self.lookahead is "MP_PROCEDURE": # 15 ProcedureHeading -> "procedure" procedureIdentifier OptionalFormalParameterList self.match("MP_PROCEDURE") name = self.procedureIdentifier() self.analyzer.incrementLabel() self.symbolTableStack.getCurrentTable().insertEntry(name, 'procedure', label=self.analyzer.getLabel()) self.symbolTableStack.addTable(name, self.analyzer.getLabel()) self.optionalFormalParameterList() else: self.error("Procedure") def functionHeading(self): if self.lookahead is "MP_FUNCTION": # 16 FunctionHeading -> "function" functionIdentifier OptionalFormalParameterList ":" Type self.match("MP_FUNCTION") name = self.functionIdentifier() self.analyzer.incrementLabel() self.symbolTableStack.getCurrentTable().insertEntry(name, 'function', label=self.analyzer.getLabel()) self.symbolTableStack.addTable(name, self.analyzer.getLabel()) self.optionalFormalParameterList() self.match("MP_COLON") type = self.type() self.symbolTableStack.updateType(name, type) else: self.error("Function") def optionalFormalParameterList(self): if self.lookahead is 'MP_LPAREN': # 17 OptionalFormalParameterList -> "(" FormalParameterSection FormalParameterSectionTail ")" self.match('MP_LPAREN') self.firstIdFlag = True self.formalParameterSection() self.formalParameterSectionTail() self.match('MP_RPAREN') elif self.lookahead in ['MP_COLON', 'MP_SCOLON', 'MP_INTEGER', 'MP_FLOAT', 'MP_BOOLEAN', 'MP_STRING']: # 18 OptionalFormalParameterList -> lambda return else: self.error("(, :, ;, Integer, Float, Boolean, String") def formalParameterSectionTail(self): if self.lookahead is "MP_SCOLON": # 19 FormalParameterSectionTail -> ";" FormalParameterSection FormalParameterSectionTail self.match('MP_SCOLON') self.formalParameterSection() self.formalParameterSectionTail() elif self.lookahead is 'MP_RPAREN': # 20 FormalParameterSectionTail -> lambda return else: self.error(";, )") def formalParameterSection(self): if self.lookahead is 'MP_IDENTIFIER': # 21 FormalParameterSection -> ValueParameterSection self.valueParameterSection() elif self.lookahead is 'MP_VAR': # 22 FormalParameterSection -> VariableParameterSection self.variableParameterSection() else: self.error("Identifier, Var") def valueParameterSection(self): if self.lookahead is 'MP_IDENTIFIER': # 23 ValueParameterSection -> IdentifierList ":" Type identList = [] identList = self.identifierList(); self.match('MP_COLON') varType = self.type() for name in identList: self.symbolTableStack.getCurrentTable().insertEntry(name, 'dparam', varType, '', self.firstIdFlag) self.firstIdFlag = False else: self.error("Identifier") def variableParameterSection(self): if self.lookahead is 'MP_VAR': # 24 VariableParameterSection -> "var" IdentifierList ":" Type self.match('MP_VAR') identList = [] identList = self.identifierList(); self.match('MP_COLON') varType = self.type() for name in identList: self.symbolTableStack.getCurrentTable().insertEntry(name, 'iparam', varType, '', self.firstIdFlag) self.firstIdFlag = False else: self.error("Var") def statementPart(self): if self.lookahead is 'MP_BEGIN': # 25 StatementPart -> CompoundStatement label = self.symbolTableStack.getCurrentTable().label self.analyzer.genLabel(label) if label == 1: self.analyzer.initMainAR() self.compoundStatement() self.symbolTableStack.getCurrentTable().printTable() self.analyzer.endProcOrFunc(self.symbolTableStack.getCurrentTable()) self.symbolTableStack.popTable() else: self.error("Begin") def compoundStatement(self): if self.lookahead is 'MP_BEGIN': # 26 CompoundStatement -> "begin" StatementSequence "end" self.match('MP_BEGIN') self.analyzer.finishProcOrFuncAR() self.statementSequence() self.match('MP_END') else: self.error("begin") def statementSequence(self): if self.lookahead in ['MP_SCOLON', 'MP_IDENTIFIER', # 27 StatementSequence -> Statement StatementTail 'MP_BEGIN', 'MP_END', 'MP_READ', 'MP_WRITE', 'MP_IF', 'MP_ELSE', 'MP_REPEAT', 'MP_UNTIL', 'MP_WHILE', 'MP_FOR', 'MP_WRITELN']: self.statement() self.statementTail() else: self.error("'MP_SCOLON', 'MP_IDENTIFIER', 'MP_BEGIN', 'MP_END', 'MP_READ',\ 'MP_WRITE', 'MP_IF', 'MP_ELSE', 'MP_REPEAT', 'MP_UNTIL', 'MP_WHILE',\ 'MP_FOR', 'MP_WRITELN'") def statementTail(self): if self.lookahead is 'MP_SCOLON': # 28 StatementTail -> ";" Statement StatementTail self.match('MP_SCOLON') self.statement() self.statementTail() elif self.lookahead in ['MP_END', 'MP_UNTIL']: # 29 StatementTail -> lambda return else: self.error(";, end, until") def statement(self): if self.lookahead in ['MP_SCOLON', 'MP_END', 'MP_ELSE', 'MP_UNTIL']: # 30 Statement -> EmptyStatement self.emptyStatement() elif self.lookahead is 'MP_BEGIN': # 31 Statement -> CompoundStatement self.compoundStatement() elif self.lookahead is 'MP_READ': # 32 Statement -> ReadStatement self.readStatement() elif self.lookahead in ['MP_WRITE', 'MP_WRITELN']: # 33 Statement -> WriteStatement self.writeStatement() elif self.lookahead is 'MP_IDENTIFIER': # 39 Statement -> ProcedureStatement OR # 34 Statement -> AssignmentStatement # if MP_ASSIGN is second lookahead, go to AssignStatement, else go to ProcedureStatement second_lookahead = self.scanner.peekNextToken() if second_lookahead is 'MP_ASSIGN': self.assignmentStatement() else: self.procedureStatement() elif self.lookahead is 'MP_IF': # 35 Statement -> IfStatement self.ifStatement() elif self.lookahead is 'MP_WHILE': # 36 Statement -> WhileStatement self.whileStatement() elif self.lookahead is 'MP_REPEAT': # 37 Statement -> RepeatStatement self.repeatStatement() elif self.lookahead is 'MP_FOR': # 28 Statement -> ForStatement self.forStatement() else: self.error(";, end, else, until, begin, read, write, writeln, identifier, :=, if, while, repeat, for") def emptyStatement(self): if self.lookahead in ['MP_SCOLON', 'MP_END', # 40 EmptyStatement -> lambda 'MP_ELSE', 'MP_UNTIL']: return else: self.error(";, end, else, until") def readStatement(self): if self.lookahead is 'MP_READ': # 41 ReadStatement -> "read" "(" ReadParameter ReadParameterTail ")" self.match('MP_READ') self.match('MP_LPAREN') self.readParameter() self.readParameterTail() self.match('MP_RPAREN') else: self.error("read") def readParameterTail(self): if self.lookahead is 'MP_COMMA': # 42 ReadParameterTail -> "," ReadParameter ReadParameterTail self.match('MP_COMMA') self.readParameter() self.readParameterTail() elif self.lookahead is 'MP_RPAREN': # 43 ReadParameterTail -> lambda return else: self.error("comma, )") def readParameter(self): if self.lookahead is 'MP_IDENTIFIER': # 44 ReadParameter -> VariableIdentifier id = self.variableIdentifier() identRec = self.analyzer.processId(id) self.analyzer.genRead(identRec) else: self.error("identifier") def writeStatement(self): if self.lookahead is 'MP_WRITE': # 45 WriteStatement -> "write" "(" WriteParameter WriteParameterTail ")" self.match('MP_WRITE') self.match('MP_LPAREN') self.writeParameter(None) self.writeParameterTail() self.match('MP_RPAREN') elif self.lookahead is 'MP_WRITELN': # 111 WriteStatement -> writeln "(" WriteParameter WriteParameterTail ")" self.match('MP_WRITELN') self.match('MP_LPAREN') self.writeParameter('writeln') self.writeParameterTail('writeln') self.match('MP_RPAREN') else: self.error("write, writeln") def writeParameterTail(self, kind): if self.lookahead is 'MP_COMMA': # 46 WriteParameterTail -> "," WriteParameter self.match('MP_COMMA') self.writeParameter(kind) self.writeParameterTail(kind) elif self.lookahead is 'MP_RPAREN': # 47 WriteParameterTail -> lambda return else: self.error("comma, )") def writeParameter(self, kind): if self.lookahead in ['MP_LPAREN', 'MP_IDENTIFIER', # 48 WriteParameter -> OrdinalExpression 'MP_PLUS', 'MP_MINUS', 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_NOT', 'MP_INTEGER_LIT', 'MP_TRUE', 'MP_FALSE']: self.ordinalExpression() self.analyzer.genWrite() if kind == 'writeln': self.analyzer.genWriteln() else: self.error("(, identifier, +, -, any literal value, not") def assignmentStatement(self): # semantic records expressionRec = {} identRec = {} if self.lookahead is 'MP_IDENTIFIER': # 49 AssignmentStatement -> VariableIdentifier ":=" Expression OR id = self.variableIdentifier() identRec = self.analyzer.processId(id) self.match('MP_ASSIGN') expressionRec = self.expression() self.analyzer.genAssign(identRec, expressionRec) # This doesn't change parsing functionality # elif self.lookahead is 'MP_IDENTIFIER': # 50 AssignmentStatement -> FunctionIdentifier ":=" Expression # self.functionIdentifier() # self.match('MP_ASSIGN') # self.expression() else: self.error("identifier") def ifStatement(self): if self.lookahead is 'MP_IF': # 51 IfStatement -> "if" BooleanExpression "then" Statement OptionalElsePart self.match('MP_IF') self.booleanExpression() self.analyzer.incrementLabel() false_label_number = self.analyzer.getLabel() self.analyzer.genBranchFalse(false_label_number) # Generate branch to Optional Else if False self.match('MP_THEN') self.statement() self.analyzer.incrementLabel() skip_else_label_number = self.analyzer.getLabel() self.analyzer.genBranch(skip_else_label_number) # Generate Branch past optional else if was inside of 'then' self.analyzer.genLabel(false_label_number) self.optionalElsePart() self.analyzer.genLabel(skip_else_label_number) else: self.error("if") def optionalElsePart(self): #TODO: Table says else is ambiguous? haven't looked at it yet if self.lookahead is 'MP_ELSE': # 52 OptionalElsePart -> "else" Statement self.match('MP_ELSE') self.statement() elif self.lookahead in ['MP_SCOLON', 'MP_END', 'MP_UNTIL']: # 53 OptionalElsePart -> lambda return else: self.error("else, ;, end, until") def repeatStatement(self): if self.lookahead is 'MP_REPEAT': # 54 RepeatStatement -> "repeat" StatementSequence "until" BooleanExpression self.match('MP_REPEAT') self.analyzer.incrementLabel() starting_label = self.analyzer.getLabel() self.analyzer.genLabel(starting_label) self.statementSequence() self.match('MP_UNTIL') self.booleanExpression() self.analyzer.genBranchFalse(starting_label) else: self.error("repeat") def whileStatement(self): if self.lookahead is 'MP_WHILE': # 55 WhileStatement -> "while" BooleanExpression "do" Statement self.match('MP_WHILE') self.analyzer.incrementLabel() start_label = self.analyzer.getLabel() self.analyzer.genLabel(start_label) self.booleanExpression() self.analyzer.incrementLabel() false_label = self.analyzer.getLabel() self.analyzer.genBranchFalse(false_label) self.match('MP_DO') self.statement() self.analyzer.genBranch(start_label) self.analyzer.genLabel(false_label) else: self.error("while") def forStatement(self): ident_rec = {} expression_rec = {} if self.lookahead is 'MP_FOR': # 56 ForStatement -> "for" ControlVariable ":=" InitialValue StepValue FinalValue "do" Statement self.match('MP_FOR') ident_rec = self.controlVariable() self.match('MP_ASSIGN') expression_rec = self.initialValue() self.analyzer.genAssign(ident_rec, expression_rec) step = self.stepValue() self.analyzer.incrementLabel() start_label = self.analyzer.getLabel() self.analyzer.incrementLabel() false_label = self.analyzer.getLabel() self.analyzer.genLabel(start_label) self.finalValue() self.analyzer.genPushId(ident_rec) if(step == "to"): self.analyzer.genBoolean(">=", ident_rec, expression_rec) self.analyzer.genBranchFalse(false_label) elif(step == "downto"): self.analyzer.genBoolean("<=", ident_rec, expression_rec) self.analyzer.genBranchFalse(false_label) self.match('MP_DO') self.statement() if(step == "to"): self.analyzer.genPushInt(str(1)) elif(step == "downto"): self.analyzer.genPushInt(str(-1)) self.analyzer.genPushId(ident_rec) self.analyzer.output("ADDS") self.analyzer.genAssign(ident_rec, expression_rec) self.analyzer.genBranch(start_label) self.analyzer.genLabel(false_label) else: self.error("for") def controlVariable(self): identRec = {} if self.lookahead is 'MP_IDENTIFIER': # 57 ControlVariable -> VariableIdentifier id = self.variableIdentifier() identRec = self.analyzer.processId(id) identRec["lexeme"] = id return identRec else: self.error("identifier") def initialValue(self): if self.lookahead in ['MP_LPAREN', 'MP_IDENTIFIER', # 58 InitialValue -> OrdinalExpression 'MP_PLUS', 'MP_MINUS', 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_NOT', 'MP_INTEGER_LIT', 'MP_TRUE', 'MP_FALSE']: return self.ordinalExpression() else: self.error("(, identifier, +, -, any literal value, not") def stepValue(self): if self.lookahead is 'MP_TO': # 59 StepValue -> "to" return self.match('MP_TO') elif self.lookahead is 'MP_DOWNTO': # 60 StepValue -> "downto" return self.match('MP_DOWNTO') else: self.error("to, downto") def finalValue(self): if self.lookahead in ['MP_LPAREN', 'MP_IDENTIFIER', # 61 FinalValue -> OrdinalExpression 'MP_PLUS', 'MP_MINUS', 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_NOT', 'MP_INTEGER_LIT', 'MP_TRUE', 'MP_FALSE']: self.ordinalExpression() else: self.error("(, identifier, +, -, any literal value, not") def procedureStatement(self): if self.lookahead is 'MP_IDENTIFIER': # 62 ProcedureStatement -> ProcedureIdentifier OptionalActualParameterList self.analyzer.incrementSP(4) # leave space for function/procedure procedureName = self.procedureIdentifier() self.optionalActualParameterList() entry = self.symbolTableStack.getCurrentTable().find(procedureName) if entry != None: self.analyzer.genCall(entry['label']) else: print "Error: "+procedureName+" not found. It either doesn't exist or out of scope." sys.exit() else: self.error("identifier") def optionalActualParameterList(self): if self.lookahead is 'MP_LPAREN': # 63 OptionalActualParameterList -> "(" ActualParameter ActualParameterTail ")" self.match('MP_LPAREN') self.actualParameter() self.actualParameterTail() self.match('MP_RPAREN') elif self.lookahead in ['MP_SCOLON', 'MP_RPAREN', 'MP_END', 'MP_COMMA', # 64 OptionalActualParameterList -> lambda 'MP_THEN', 'MP_ELSE', 'MP_UNTIL', 'MP_TO', 'MP_DO', 'MP_DOWNTO', 'MP_EQUAL', 'MP_LTHAN', 'MP_GTHAN', 'MP_LEQUAL', 'MP_GEQUAL', 'MP_NEQUAL', 'MP_PLUS', 'MP_MINUS', 'MP_OR', 'MP_TIMES', 'MP_DIV', 'MP_MOD', 'MP_AND', 'MP_SLASH']: return else: self.error(";, ), end, comma, then, else, until, to do, downto, an equality operator, an arithmetic operator, and, mod") def actualParameterTail(self): if self.lookahead is 'MP_COMMA': # 65 ActualParameterTail -> "," ActualParameter ActualParameterTail self.match('MP_COMMA') self.actualParameter() self.actualParameterTail() elif self.lookahead is 'MP_RPAREN': # 66 ActualParameterTail -> lambda return else: self.error("comma, )") def actualParameter(self): if self.lookahead in ['MP_LPAREN', 'MP_IDENTIFIER', # 67 ActualParameter -> OrdinalExpression 'MP_PLUS', 'MP_MINUS', 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_NOT', 'MP_INTEGER_LIT', 'MP_TRUE', 'MP_FALSE']: self.ordinalExpression() else: self.error("(, identifier, +, -, any literal value, not") def expression(self): expression_rec = {} if self.lookahead in ['MP_LPAREN', 'MP_IDENTIFIER', # 68 Expression -> SimpleExpression OptionalRelationalPart 'MP_PLUS', 'MP_MINUS', 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_NOT', 'MP_INTEGER_LIT', 'MP_TRUE', 'MP_FALSE']: expression_rec = self.simpleExpression() expression_rec = self.optionalRelationalPart(expression_rec) return expression_rec # return self.mapTokenToType(self.lookahead) else: self.error("(, identifier, +, -, any literal value, not") def optionalRelationalPart(self, expression_rec): rightOp = {} leftOp = expression_rec if self.lookahead in ['MP_EQUAL', 'MP_LTHAN', # 69 OptionalRelationalPart -> RelationalOperator SimpleExpression 'MP_GTHAN', 'MP_LEQUAL', 'MP_GEQUAL', 'MP_NEQUAL']: operator = self.relationalOperator() rightOp = self.simpleExpression() self.analyzer.genBoolean(operator, leftOp, rightOp) expression_rec["type"] = 'Boolean' return expression_rec elif self.lookahead in ['MP_SCOLON', 'MP_RPAREN', # 70 OptionalRelationalPart -> lambda 'MP_END', 'MP_COMMA', 'MP_THEN', 'MP_ELSE', 'MP_UNTIL','MP_DO', 'MP_TO', 'MP_DOWNTO']: return expression_rec else: self.error("an equality operator, ;, ), then, else, until, do, to, downto") def relationalOperator(self): if self.lookahead is 'MP_EQUAL': # 71 RelationalOperator -> "=" operator = self.match('MP_EQUAL') elif self.lookahead is 'MP_LTHAN': # 72 RelationalOperator -> "<" operator = self.match('MP_LTHAN') elif self.lookahead is 'MP_GTHAN': # 73 RelationalOperator -> ">" operator = self.match('MP_GTHAN') elif self.lookahead is 'MP_LEQUAL': # 74 RelationalOperator -> "<=" operator = self.match('MP_LEQUAL') elif self.lookahead is 'MP_GEQUAL': # 75 RelationalOperator -> ">=" operator = self.match('MP_GEQUAL') elif self.lookahead is 'MP_NEQUAL': # 76 RelationalOperator -> "<>" operator = self.match('MP_NEQUAL') else: self.error("an equality operator") return operator def simpleExpression(self): # semantic records termRec = {} termTailRec = {} if self.lookahead in ['MP_LPAREN', 'MP_IDENTIFIER', # 77 SimpleExpression -> OptionalSign Term TermTail 'MP_PLUS', 'MP_MINUS', 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_NOT', 'MP_INTEGER_LIT', 'MP_TRUE', 'MP_FALSE']: sign = self.optionalSign() termRec = self.term() type = termRec['type'] if sign == "-": if type == "Integer": self.analyzer.genNeg() elif type in ["Float", "Fixed"]: self.analyzer.genNegf() termTailRec = termRec termTailRec = self.termTail(termTailRec) expressionRec = termTailRec # This is what Rocky suggested return expressionRec else: self.error("(, identifier, +, -, any literal value, not") def termTail(self, termTailRec = {}): # Semantic Records addopRec = {} termRec = {} if self.lookahead in ['MP_PLUS', 'MP_MINUS', 'MP_OR']: # 78 TermTail -> AddingOperator Term TermTail addopRec["lexeme"] = self.addingOperator() termRec = self.term() resultRec = self.analyzer.genArithmetic(termTailRec, addopRec, termRec) self.termTail(resultRec) termTailRec = resultRec return termTailRec elif self.lookahead in ['MP_SCOLON', 'MP_RPAREN', 'MP_END', # 79 TermTail -> lambda 'MP_COMMA', 'MP_THEN', 'MP_ELSE', 'MP_UNTIL', 'MP_DO', 'MP_TO', 'MP_DOWNTO', 'MP_EQUAL', 'MP_LTHAN', 'MP_GTHAN', 'MP_LEQUAL', 'MP_GEQUAL', 'MP_NEQUAL']: return termTailRec else: self.error("+, -, or, ;, ), end, comma, then, else, until, do, to, downto, an equality operator") def optionalSign(self): if self.lookahead is 'MP_PLUS': # 80 OptionalSign -> "+" self.match('MP_PLUS') elif self.lookahead is 'MP_MINUS': # 81 OptionalSign -> "-" return self.match('MP_MINUS') elif self.lookahead in ['MP_LPAREN', 'MP_IDENTIFIER', # 82 OptionalSign -> lambda 'MP_NOT', 'MP_INTEGER_LIT', 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_TRUE', 'MP_FALSE']: return else: self.error("+, -, (, identifier, +, -, any literal value, not") def addingOperator(self): if self.lookahead is 'MP_PLUS': # 83 AddingOperator -> "+" return self.match('MP_PLUS') elif self.lookahead is 'MP_MINUS': # 84 AddingOperator -> "-" return self.match('MP_MINUS') elif self.lookahead is 'MP_OR': # 85 AddingOperator -> "or" return self.match('MP_OR') else: self.error("+, -, or") def term(self): termRec = {} if self.lookahead in ['MP_LPAREN', # 86 Term -> Factor FactorTail 'MP_IDENTIFIER', 'MP_NOT', 'MP_INTEGER_LIT', 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_TRUE', 'MP_FALSE']: termRec["type"] = self.factor() termRec = self.factorTail(termRec) return termRec # return self.mapTokenToType(self.lookahead) else: self.error("(, identifier, +, -, any literal value, not") def factorTail(self, termRec): rightOp = {} operator = {} if self.lookahead in ['MP_TIMES', 'MP_DIV', # 87 FactorTail -> MultiplyingOperator Factor FactorTail 'MP_MOD', 'MP_AND', 'MP_SLASH']: operator["lexeme"] = self.multiplyingOperator() rightOp["type"] = self.factor() self.analyzer.genArithmetic(termRec, operator, rightOp) self.factorTail(rightOp) return termRec elif self.lookahead in ['MP_SCOLON', 'MP_RPAREN', 'MP_END', # 88 FactorTail -> lambda 'MP_COMMA', 'MP_THEN', 'MP_ELSE', 'MP_UNTIL', 'MP_DO', 'MP_TO', 'MP_DOWNTO', 'MP_EQUAL', 'MP_LTHAN', 'MP_GTHAN', 'MP_LEQUAL', 'MP_GEQUAL', 'MP_NEQUAL', 'MP_PLUS', 'MP_MINUS', 'MP_OR']: return termRec else: self.error("*, div, mod, and /, ;, ), end, comma, then, else, until, do, to, downto, an equality operator, +, -, or") def multiplyingOperator(self): if self.lookahead is 'MP_TIMES': # 89 MultiplyingOperator -> "*" return self.match('MP_TIMES') elif self.lookahead is 'MP_DIV': # 90 MultiplyingOperator -> "div" return self.match('MP_DIV') elif self.lookahead is 'MP_MOD': # 91 MultiplyingOperator -> "mod" return self.match('MP_MOD') elif self.lookahead is 'MP_AND': # 92 MultiplyingOperator -> "and" return self.match('MP_AND') elif self.lookahead is 'MP_SLASH': # 112 MultiplyingOperator -> "/" return self.match('MP_SLASH') else: self.error("*, div, mod, and, /") def factor(self): # semantic record identRec = {} if self.lookahead in ['MP_INTEGER_LIT']: # 93 Factor -> UnsignedInteger integer = self.match('MP_INTEGER_LIT') self.analyzer.genPushInt(integer) return "Integer" elif self.lookahead is 'MP_IDENTIFIER': # 94 Factor -> VariableIdentifier OR # 97 Factor -> FunctionIdentifier OptionalActualParameterList id_kind = self.analyzer.processId(self.scanner.lexeme)["kind"] if id_kind == "function": self.analyzer.incrementSP(4) # leave space for function/procedure's display register id = self.functionIdentifier() self.optionalActualParameterList() entry = self.symbolTableStack.getCurrentTable().find(id) if entry != None: self.analyzer.genCall(entry['label']) # self.analyzer.popDisplayAndParams(id) else: print "Error: "+id+" not found. It either doesn't exist or out of scope." sys.exit() elif id_kind in ["var", "iparam", "dparam"]: id = self.variableIdentifier() identRec["lexeme"] = id self.analyzer.genPushId(identRec) return self.analyzer.processId(id)["type"] elif self.lookahead is 'MP_NOT': # 95 Factor -> "not" Factor self.match('MP_NOT'); self.factor() self.analyzer.genNot() return "Boolean" elif self.lookahead is 'MP_LPAREN': # 96 Factor -> "(" Expression ")" self.match('MP_LPAREN') type = self.expression()["type"] self.match('MP_RPAREN') return type elif self.lookahead in ['MP_FLOAT_LIT']: # 113 Factor -> UnsignedFloat float = self.match('MP_FLOAT_LIT') self.analyzer.genPushFloat(float) return "Float" elif self.lookahead in ['MP_FIXED_LIT']: # 113 Factor -> UnsignedFloat fixed = self.match('MP_FIXED_LIT') self.analyzer.genPushFloat(fixed) return "Float" elif self.lookahead in ['MP_STRING_LIT']: # 114 Factor -> StringLiteral string = self.match('MP_STRING_LIT') self.analyzer.genPushString(string) return "String" elif self.lookahead in ['MP_TRUE']: # 115 Factor -> "True" self.match('MP_TRUE') self.analyzer.genPushBoolean(1) return "Boolean" elif self.lookahead in ['MP_FALSE']: # 116 Factor -> "False" self.match('MP_FALSE') self.analyzer.genPushBoolean(0) return "Boolean" else: self.error("(, identifier, +, -, any literal value, not") def programIdentifier(self): if(self.lookahead == "MP_IDENTIFIER"): # 98 ProgramIdentifier -> Identifier return self.match("MP_IDENTIFIER") else: self.error("identifier") def variableIdentifier(self): if(self.lookahead == "MP_IDENTIFIER"): # 99 VariableIdentifier -> Identifier return self.match("MP_IDENTIFIER") else: self.error("identifier") def procedureIdentifier(self): if(self.lookahead == "MP_IDENTIFIER"): # 100 ProcedureIdentifier -> Identifier return self.match("MP_IDENTIFIER") else: self.error("identifier") def functionIdentifier(self): if(self.lookahead == "MP_IDENTIFIER"): # 101 FunctionIdentifier -> Identifier return self.match("MP_IDENTIFIER") else: self.error("identifier") def booleanExpression(self): if(self.lookahead in ["MP_LPAREN", "MP_IDENTIFIER", # 102 BooleanExpression -> Expression "MP_PLUS", "MP_MINUS", "MP_NOT", "MP_INTEGER_LIT", 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_TRUE', 'MP_FALSE']): self.expression() else: self.error("(, identifier, +, -, any literal value, not, +, -") def ordinalExpression(self): if(self.lookahead in ["MP_LPAREN", "MP_IDENTIFIER", # 103 OrdinalExpression -> Expression "MP_PLUS", "MP_MINUS", "MP_NOT", "MP_INTEGER_LIT", 'MP_FLOAT_LIT', 'MP_FIXED_LIT', 'MP_STRING_LIT', 'MP_TRUE', 'MP_FALSE']): return self.expression() else: self.error("(, identifier, +, -, any literal value, not, +, -") def identifierList(self): if(self.lookahead == "MP_IDENTIFIER"): # 104 IdentifierList -> Identifier IdentifierTail ident = [] ident.append(self.scanner.lexeme) self.match("MP_IDENTIFIER") self.identifierTail(ident) return ident else: self.error("identifier") def identifierTail(self,ident): if(self.lookahead == "MP_COMMA"): # 105 IdentifierTail -> "," Identifier IdentifierTail self.match("MP_COMMA") ident.append(self.scanner.lexeme) self.match("MP_IDENTIFIER") self.identifierTail(ident) elif(self.lookahead == "MP_COLON"): # 106 IdentifierTail -> lambda return else: self.error("comma, :") def error(self, expected): print "ERROR: Syntax error found on line " + str(self.scanner.getLineNumber()) + ", column " + str(self.scanner.getColumnNumber()) print "Found " + self.scanner.lexeme + " when expected one of: " + expected # print the caller # print inspect.stack()[1][3] sys.exit() def matchError(self, expected): print "ERROR: Match error found on line " + str(self.scanner.getLineNumber()) + ", column " + str(self.scanner.getColumnNumber()) + " lexeme: " + self.scanner.lexeme print "Found " + self.lookahead + " when expected " + expected # print the caller sys.exit()
class SissiApp: __id__ = u'Sissi' __version__ = u'0.1' def __init__(self): # app title appuifw.app.title = u"Sissi" # app lock self.lock = e32.Ao_lock() # ensure data dir exists self.datadir = os.path.join(u"C:\\Data", u"Sissi") if not os.path.exists(self.datadir): os.makedirs(self.datadir) # create a directory for temporary data self.cachedir = u"D:\\Sissi" if not os.path.exists(self.cachedir): os.makedirs(self.cachedir) # get screen resolution self.screen = sysinfo.display_pixels() # extra classes instantiated self.scanner = Scanner(self) self.netmapper = NetMapper(self) self.map = Map(self) self.cos_api = COSApi(self) # timer self.t = e32.Ao_timer() self.active = False # set canvas self.activate() # configuration / settings self.draw_screen('reading config') self.config_file = os.path.join(self.datadir, "settings.ini") self.config = {} # TODO: read these from a configuration file self.apid = None # Default access point self.read_config() if self.config.has_key("apid"): self._select_access_point(self.config["apid"]) # set extra handler to be called on each GPS loop self.scanner.set_extra_handler(self.loop) # update our menu self._update_menu() self.draw_screen('ready!') # self.debug(self.screen) self.scanner_handler() # start scanning automatically # set exit key handler appuifw.app.exit_key_handler = self.exit_key_handler def debug(self,obj): self.draw_screen(simplejson.dumps(obj)) def update(self, dummy=(0, 0, 0, 0)): self.t.cancel() text = self.get_canvas_text() self.draw_screen(text) if self.active: self.t.after(0.5, self.update) def get_canvas_text(self): text = "" if self.scanner.text != None: text += self.scanner.text if self.netmapper.text != None: text += self.netmapper.text if self.cos_api.text != None: text += self.cos_api.text if len(text) == 0: text = "Waiting for location fix!" return text def draw_screen(self,text): self.canvas.clear() line_height = y = 15 text = text.split("\n") for line in text: self.canvas.text((3, y), u""+line, font=(u"Series 60 Sans", 12), fill=0x333333) y += line_height def open_ossi(self): path = u"e:\\python\\ossi.html" c=appuifw.Content_handler() c.open(path) app_lock = e32.Ao_lock() app_lock.wait() appuifw.app.exit_key_handler = self.exit_key_handler def _select_access_point(self, apid = None): """ Shortcut for socket.select_access_point() TODO: save selected access point to the config TODO: allow user to change access point later """ if apid is not None: self.apid = apid else: access_points = socket.access_points() sort_key = "iapid" decorated = [(dict_[sort_key], dict_) for dict_ in access_points] decorated.sort() access_points = [dict_ for (key, dict_) in decorated] ap_names = [dict_["name"] for dict_ in access_points] ap_ids = [dict_["iapid"] for dict_ in access_points] selected = appuifw.selection_list(ap_names, search_field=1) #print selected, ap_names[selected], ap_ids[selected] if selected is not None: self.apid = ap_ids[selected] if self.apid: self.apo = socket.access_point(self.apid) socket.set_default_access_point(self.apo) self.config["apid"] = self.apid self.save_config() self._update_menu() return self.apid def _update_menu(self): scanner_string = 'Start' if self.__dict__.has_key("scanner"): # check that scanner has been initialized if self.scanner.running: scanner_string = 'Stop' appuifw.app.menu = [ (u""+scanner_string+" scanner", self.scanner_handler), (u"Show map", self.toggle_map), (u"Reset config", self.reset_config), (u"About", lambda:appuifw.note("Sissi is OtaSizzle S60 daemon. Version: " + self.__version__ + "\n\nJ Turunen / HIIT", 'info')), (u"Close", self.exit_key_handler), ] def read_config(self): data = {} try: f = open(self.config_file, "rt") data = eval(f.read()) #data = f.read() f.close() except: appuifw.note(u"Generating a settings file...", 'info') # raise # List here ALL POSSIBLE configuration keys, so they will be initialized defaults = { "otasizzle_username" : None, "otasizzle_password" : None, "cos_method" : u"http", "cos_domain" : u"cos.alpha.sizl.org", "cos_path" : u"/location/single_update", "apid" : None, "onm_url" : u"http://opennetmap.org/api/?operation=get_wlan_01&wlan_ids=", "script" : u"/api/", } # List here all configuration keys, which must be defined before use # If a config key has key "function", it's called to define value # TODO: make some order for these mandatory = { "otasizzle_username" : {"querytext" : u"your OtaSizzle username", "valuetype" : "text", "default" : u'', "canceltext" : u'username is mandatory!', }, "otasizzle_password" : {"querytext" : u"your OtaSizzle password", "valuetype" : "text", "default" : u'', "canceltext" : u'password is mandatory!', }, "apid" : {"querytext" : u"Select default data connection!", "valuetype" : "function", "default" : u'', "canceltext" : None, "function" : self._select_access_point, }, } # Loop all possible keys (found from defaults) for key in defaults.keys(): if data.has_key(key): # Use the value found from the data defaults[key] = data[key] elif mandatory.has_key(key) and defaults[key] is None: # Ask mandatory values from the user value = None if mandatory[key].has_key("function"): # if defined, call the "function" appuifw.note(mandatory[key]["querytext"], 'info') value = mandatory[key]["function"]() # "function" must return a value else: while value is None: value = appuifw.query(mandatory[key]["querytext"], mandatory[key]["valuetype"], mandatory[key]["default"]) if value is None and mandatory[key]["canceltext"]: appuifw.note(mandatory[key]["canceltext"], 'error') elif value is None: # If canceltext is u"", change value None to u"" value = u"" defaults[key] = value self.config = defaults self.save_config() def save_config(self): f = open(self.config_file, "wt") f.write(repr(self.config)) f.close() def reset_config(self): if appuifw.query(u'Are you sure you want to delete all settings?', 'query') is True: os.remove(self.config_file) appuifw.note(u"Done, now you need to restart Sissi!", 'info') self.running = False self.lock.signal() appuifw.app.exit_key_handler = None def scanner_handler(self): if self.scanner: if self.scanner.running: self.scanner.stop() else: self.scanner.start() self._update_menu() def loop(self): if self.scanner.position.has_key("gps_data"): # first check whether we have a GPS position self.cos_api.post(self.scanner.position["gps_data"]["lat"], self.scanner.position["gps_data"]["lon"]) # if map view is active load a new one if self.map.active: self.map.load(self.scanner.position["gps_data"]["lat"], self.scanner.position["gps_data"]["lon"]) elif self.scanner.position.has_key("wlan_data"): # if not then see if we have wlans in the latest scanned position wlanlist = self.scanner.position["wlan_data"]["wlanlist"] wlanlist.sort(lambda x, y: cmp(y['rxlevel'], x['rxlevel'])) if len(wlanlist) > 1: self.netmapper.get_location(wlanlist) # fetching calculated location from OpenNetMap if self.netmapper.computed_location["latitude"] and self.netmapper.computed_location["longitude"]: self.cos_api.post(self.netmapper.computed_location["latitude"], self.netmapper.computed_location["longitude"]) # if map view is active load a new one if self.netmapper.computed_location["latitude"] and self.netmapper.computed_location["longitude"] and self.map.active: self.map.load(self.netmapper.computed_location["latitude"], self.netmapper.computed_location["longitude"]) elif self.scanner.position.has_key("gsm_data"): # not yet implemented!! pass def toggle_map(self): if not appuifw.app.body == self.canvas: self.map.active = False self.activate() else: self.active = False self.map.activate() def activate(self): self.active = True appuifw.app.exit_key_handler = self.exit_key_handler try: self.canvas except: self.canvas = appuifw.Canvas(redraw_callback=self.update) appuifw.app.body = self.canvas self._update_menu() def run(self): self.lock.wait() self.close() def exit_key_handler(self): if appuifw.query(u"Quit program", 'query') is True: self.running = False self.scanner.stop() self.lock.signal() def close(self): # positioning.stop_position() appuifw.app.exit_key_handler = None self.running = False
def __init__(self, aText): self.tokens = [] scan = Scanner(aText) while scan.hasChar(): #print(scan.content[scan.curr_pos]) #TODO: implement comment parsing #TODO: EOF if scan.eatNext( Token.WHITESPACE_CHARS ): #print("skip whitespace") continue elif scan.eatNext( Token.KEYWORDS ): self.tokens.append( Token(scan.lastEat["String"], Token.SYMBOL, scan.lastEat["SingleChars"]) ) elif scan.eatNext( Token.NEWLINE_CHARS ): #ignore newline #self.tokens.append( Token("", Token.NEWLINE, scan.lastEat["SingleChars"]) ) pass elif scan.eatNext( Token.IDENTIFIER_STARTCHARS ): startChar = scan.lastEat fullString = scan.lastEat["String"] while scan.eatNext( Token.IDENTIFIER_CHARS ): fullString += scan.lastEat["String"] #TODO: startChar only contains position from the first char self.tokens.append( Token(fullString, Token.IDENTIFIER, startChar["SingleChars"]) ) elif scan.eatNext( Token.NUMBER_STARTCHARS ): startChar = scan.lastEat fullString = scan.lastEat["String"] while scan.eatNext( Token.NUMBER_CHARS ): fullString += scan.lastEat["String"] #TODO: startChar only contains position from the first char self.tokens.append( Token(fullString, Token.NUMBER, startChar["SingleChars"]) ) elif scan.eatNext( Token.STRING_START_END_CHAR ): beginStr = scan.lastEat if not scan.eatNextUntil( Token.STRING_START_END_CHAR ): raise Exception("Cannot parse String") fullString = scan.lastEat["String"] fullSingleChars = beginStr["SingleChars"] fullSingleChars.extend( scan.lastEat["SingleChars"] ) #TODO: join with the previous line self.tokens.append( Token(fullString[0:-1], Token.STRING, fullSingleChars) ) else: raise Exception("Parser Error") scan.curr_pos += 1 self.tokens.append( Token("EOF", Token.EOF, [SingleChar("EOF", 0, 0, 0)]) ) for i in self.tokens: print(i)
def __init__(self): self.scanner = Scanner() self.scanner.build()
def __init__(self, filename): self.f = Scanner(filename)
class Lexer: def __init__(self, filename): self.f = Scanner(filename) def lex(self): ch = self.f.fgetc() self.f.skipWhiteSpace() ch = self.f.fgetc() if ch == "": self.f.close() return Lexeme("ENDOFFILE") if ch == '[': return Lexeme("OBRACKET") elif ch == ']': return Lexeme("CBRACKET") elif ch == '.': return Lexeme("PERIOD") elif ch == ';': return Lexeme("SEMICOLON") elif ch == ':': return Lexeme("COLON") elif ch == ',': return Lexeme("COMMA") elif ch == '+': return Lexeme("PLUS") elif ch == '-': return Lexeme("SUBTRACT") elif ch == '*': return Lexeme("TIMES") elif ch == '/': return Lexeme("DIVIDE") elif ch == '%': return Lexeme("MODULUS") elif ch == '&': return Lexeme("AND") elif ch == '|': return Lexeme("OR") elif ch == '^': return Lexeme("XOR") elif ch == '=': ch = self.f.fgetc() if ch == '=': return Lexeme("EQUALS") else: self.f.ungetc() return Lexeme("ASSIGN") elif ch == '!': ch = self.f.fgetc() if ch == '=': return Lexeme("NOTEQUALS") else: self.f.ungetc() return Lexeme("NOT") elif ch == '<': ch = self.f.fgetc() if ch == '=': return Lexeme("LESSOREQUAL") else: self.f.ungetc() return Lexeme("LESSTHAN") elif ch == '>': ch = self.f.fgetc() if ch == '=': return Lexeme("GREATEROREQUAL") else: self.f.ungetc() return Lexeme("GREATERTHAN") else: if(ch.isdigit()): self.f.ungetc() return self.lexNumber() elif(ch.isalpha()): self.f.ungetc() return self.lexVariable() elif(ch == '"'): return self.lexString() return self.lexUnknown() def lexNumber(self): curr = Lexeme("NUMBER") num = "" ch = self.f.fgetc() while(ch.isdigit()): num += ch ch = self.f.fgetc() self.f.ungetc() curr.value = int(num) return curr def lexVariable(self): name = "" ch = self.f.fgetc() while(ch.isalnum()): name += ch ch = self.f.fgetc() if(name == "moenus"): curr = Lexeme("FUNCTION") elif(name == "dum"): curr = Lexeme("WHILE") elif(name == "si"): curr = Lexeme("IF") elif(name == "aut"): curr = Lexeme("ELSE") elif(name == "revenire"): curr = Lexeme("RETURN") else: curr = Lexeme("VARIABLE") curr.value = name self.f.ungetc() return curr def lexString(self): curr = Lexeme("STRING") string = "" ch = self.f.fgetc() while(ch != '"'): string += ch ch = self.f.fgetc() curr.value = string return curr def lexUnknown(self): curr = Lexeme("UNKNOWN") ch = self.f.fgetc() val = "" while not ch.isspace(): val += ch ch = self.f.fgetc() curr.value = val return curr
import urlparse import urllib import json import cgi import argparse parser = argparse.ArgumentParser(description='Fire up the Prophet code autocompleter API') parser.add_argument('path', help='root directory of code') parser.add_argument('pattern', help='source files should match this pattern') args = parser.parse_args() path = args.path pattern = args.pattern print "Traversing", path, "with pattern", pattern scanner = Scanner(path, pattern) fileDict = scanner.scan() print scanner.files, "files, with", scanner.lines, "non blank lines" prophet = Prophet(fileDict) #set up API class RequestHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.wfile.write("<h1>Prophet code completer</h1> path: " + path + "<br> pattern: " + pattern) def do_POST(self): self.send_response(200) self.send_header('Access-Control-Allow-Origin', '*')
class Parser(object): palka = '' def __init__(self): self.scanner = Scanner() self.scanner.build() tokens = Scanner.tokens precedence = ( ("nonassoc", 'SI'), ("nonassoc", 'SINO'), ("right", 'IGUAL'), ("left", 'OR'), ("left", 'AND'), ("nonassoc", 'MAYORQUE', 'MENORQUE', 'IGUALIGUAL', 'NOT', 'MAYORIGUAL', 'MENORIGUAL'), ("left", 'MAS', 'MENOS'), ("left", 'MULTI', 'DIV', 'MOD'), ) error = 0 def p_error(self,t): Parser.error = 1 if t: print("Syntax error at line {0}, column {1}: LexToken({2}, '{3}')".format(t.lineno, self.scanner.find_tok_column(t), t.type, t.value)) #exit(1); else: print('At end of input') def p_programa(self,t): """programa : PROGRAMA ID PUNTOCOMA declara_variables declara_funciones metodo_principal | PROGRAMA ID PUNTOCOMA declara_variables metodo_principal | PROGRAMA ID PUNTOCOMA declara_funciones metodo_principal | PROGRAMA ID PUNTOCOMA metodo_principal """ if len(t) == 7: t[0] = [t[1], t[2], t[4], t[5],t[6]] print("Sintaxis correcta") elif len(t) == 6: t[0] = [t[1], t[2], t[4], t[5]] print("Sintaxis correcta") else: t[0] = [t[1],t[2], t[4]] print("Sintaxis correcta") def p_declara_variables(self,t): """declara_variables : declara_variables1 | declara_variables1 declara_variables """ if len(t) == 3: t[0] = ["declaracion_variables", t[1],t[2]] else: t[0] = ["declaracion_variables", t[1]] def p_declara_variables1(self,t): """declara_variables1 : tipo DOSPUNTOS lista_ids PUNTOCOMA | tipo DOSPUNTOS lista_ids PUNTOCOMA declara_variables1 """ if len(t) == 6: temp = [] temp.append(t[1]) temp.append(t[3]) temp1 = t[5] t[0]= temp + t[5] else: temp1 = [] temp1.append(t[1]) temp1.append(t[3]) t[0] = temp1 #print(t[0]) def p_tipo(self,t): """tipo : ENTERO | REAL | CHAR """ t[0] = t[1] def p_lista_ids(self,t): """lista_ids : variable | variable COMA lista_ids """ if len(t) == 4: temp = [] temp.append(t[1]) t[0]= temp + t[3] else: t[0] = [t[1]] def p_variable(self,t): """variable : ID | ID indice_matriz | ID indice_matriz indice_matriz """ if len(t) == 4: t[0] = t[1], t[2], t[3] elif len(t) == 3: t[0] = t[1], t[2] else: t[0] = t[1] def p_indice_matriz(self,t): """indice_matriz : CORIZQ ENTERO CORDER """ t[0] = ('indice_matriz', t[2]) def p_declara_funciones(self,t): #7, 6, 8, 7 """declara_funciones : declara_funciones1 declara_funciones | declara_funciones1 """ if len(t) == 3: t[0] = ["declara_funciones", t[1],t[2]] else: t[0] = ["declara_funciones", t[1]] def p_declara_funciones1(self,t): #7, 6, 8, 7 """declara_funciones1 : MODULO tipo_retorno ID PARIZQ lista_parametros PARDER bloque | MODULO tipo_retorno ID PARIZQ PARDER bloque | MODULO tipo_retorno ID PARIZQ lista_parametros PARDER bloque declara_funciones1 | MODULO tipo_retorno ID PARIZQ PARDER bloque declara_funciones1 """ # t[0] = ('declara_funciones', t[1], t[2], t[3], t[4], t[6]) # #print(*t, sep='\n') if len(t) == 8 and t[6] == ')': t[0] = [ t[1], t[2], t[3],t[5],t[7]] + ["END"] elif len(t) == 7: t[0] = [t[1], t[2],t[3],t[6]] + ["END"] elif len(t) == 9: temp = [] temp.append(t[1]) temp.append(t[2]) temp.append(t[3]) temp.append(t[5]) temp.append(t[7]) temp.append("END") t[0] = temp + t[8] elif len(t) == 8 and t[5] == ')': temp = [] temp.append(t[1]) temp.append(t[2]) temp.append(t[3]) temp.append(t[6]) temp.append("END") t[0] = temp + t[7] #print(t[0]) def p_tipo_retorno(self,t): """tipo_retorno : tipo | VOID """ t[0] = t[1] def p_lista_parametros(self,t): """lista_parametros : lista_parametros1 lista_parametros | lista_parametros1 """ if len(t) == 3: t[0] = ["lista_parametros", t[1],t[2]] else: t[0] = ["lista_parametros", t[1]] def p_lista_parametros1(self,t): """lista_parametros1 : tipo DOSPUNTOS lista_idparam PUNTOCOMA | tipo DOSPUNTOS lista_idparam PUNTOCOMA lista_parametros1 """ if len(t) == 6: temp = [] temp.append(t[1]) temp.append(t[3]) t[0]= temp + t[5] else: temp1 = [] temp1.append(t[1]) temp1.append(t[3]) t[0] = temp1 def p_lista_idparam(self,t): """lista_idparam : variable | variable COMA lista_idparam """ if len(t) == 4: temp = [] temp.append(t[1]) t[0]= temp + t[3] else: t[0] = [t[1]] def p_bloque(self,t): #8 , 7, 7, 6, 7, 6, 6, 5 """bloque : LLAVEIZQ declara_variables estatutos_control REGRESA PARIZQ expresion PARDER LLAVEDER | LLAVEIZQ estatutos_control REGRESA PARIZQ expresion PARDER LLAVEDER | LLAVEIZQ declara_variables REGRESA PARIZQ expresion PARDER LLAVEDER | LLAVEIZQ REGRESA PARIZQ expresion PARDER LLAVEDER | LLAVEIZQ declara_variables estatutos_control REGRESA PARIZQ PARDER LLAVEDER | LLAVEIZQ estatutos_control REGRESA PARIZQ PARDER LLAVEDER | LLAVEIZQ declara_variables REGRESA PARIZQ PARDER LLAVEDER | LLAVEIZQ REGRESA PARIZQ PARDER LLAVEDER """ if len(t) == 9: t[0] = ['bloque', t[2], t[3], t[4], t[6]] elif len(t) == 8 and t[3] == 'regresa': t[0] = ['bloque', t[2], t[3], t[5]] elif len(t) == 7 and t[2] == 'regresa': t[0] = ['bloque', t[2], t[4]] elif len(t) == 8 and t[4] == 'regresa': t[0] = ['bloque', t[2], t[3],t[4]] elif len(t) == 7 and t[3] == 'regresa': t[0] = ['bloque', t[2], t[3]] elif len(t) ==6: t[0] = ['bloque', t[2]] #print(t[0]) def p_metodo_principal(self,t): """metodo_principal : PRINCIPAL PARIZQ PARDER LLAVEIZQ declara_variables estatutos_control LLAVEDER | PRINCIPAL PARIZQ PARDER LLAVEIZQ estatutos_control LLAVEDER | PRINCIPAL PARIZQ PARDER LLAVEIZQ declara_variables LLAVEDER | PRINCIPAL PARIZQ PARDER LLAVEIZQ LLAVEDER """ if len(t) == 8: t[0] = [t[1], t[5],t[6]] elif len(t) == 7: t[0] = [t[1],t[5]] else: t[0] = [t[1]] #print(t[0]) def p_estatutos_control(self,t): """estatutos_control : estatutos_control1 estatutos_control | estatutos_control1 """ if len(t) == 3: t[0] = ["estatutos", t[1],t[2]] else: t[0] = ["estatutos", t[1]] #print(t[0]) def p_estatutos_control1(self,t): """estatutos_control1 : estatuto_control PUNTOCOMA | estatuto_control PUNTOCOMA estatutos_control1 """ if len(t) == 4: t[0] = t[1]+t[3] else: t[0] = t[1] #print(t[0]) def p_estatuto1(self,t): """estatuto : asignacion | llamada | lectura | escritura """ t[0] = t[1] #print(t[0]) def p_estatuto_control(self,t): """estatuto_control : decision | repeticion | estatuto """ t[0] = [t[1]] #print(t[0]) def p_asignacion(self,t): """asignacion : variable IGUAL estatuto | variable IGUAL expresion """ t[0] = ['asignacion', t[1], t[3]] #print(t[0]) def p_llamada(self,t): """llamada : ID PARIZQ PARDER | ID PARIZQ lista_valores PARDER | ID PARIZQ lista_valores PARDER expresion | ID PARIZQ PARDER expresion """ if len(t) == 6: t[0] = ['llamada', t[1], t[3], t[5]] elif len(t) == 5: t[0] = ['llamada', t[1], t[3]] elif len(t) == 5 and t[3] == ")": t[0] = ['llamada', t[1], t[4]] else: t[0] = ['llamada', t[1], t[4]] #print(t[1]) def p_lectura(self,t): """lectura : LEER PARIZQ lista_valores PARDER """ t[0] = ['lectura', t[1], t[3]] def p_escritura(self,t): """escritura : ESCRIBIR PARIZQ lista_valores PARDER """ t[0] = ['escritura', t[1], t[3]] def p_decision(self,t): """decision : SI PARIZQ expresion PARDER hacer | SI PARIZQ expresion PARDER hacer SINO hacer """ if len(t) == 8: t[0] = ['decision', t[1], t[3], t[5], t[6],t[7]] else: t[0] = ['decision', t[1], t[3], t[5]] def p_hacer(self,t): """hacer : LLAVEIZQ LLAVEDER | LLAVEIZQ estatutos_control LLAVEDER """ if len(t) == 4: t[0] = ['hacer', t[2]] else: t[0] = ['hacer'] def p_repeticion(self,t): """repeticion : mientras | repite """ t[0] = ['repeticion', t[1]] def p_mientras(self,t): """mientras : MIENTRAS PARIZQ expresion PARDER HAZ hacer """ t[0] = [t[1], t[3],t[6]] def p_repite(self,t): """repite : REPITE hacer HASTA PARIZQ expresion PARDER """ t[0] = [t[1], t[2],t[5]] def p_lista_valores(self,t): """lista_valores : expresion | expresion COMA lista_valores """ if len(t) == 4: temp = [] temp.append(t[1]) t[0]= temp + t[3] else: t[0] = [t[1]] def p_expresion(self,t): """expresion : expresion AND exp | expresion OR exp | expresion NOT exp | expresion MENORQUE exp | expresion MAYORQUE exp | expresion IGUALIGUAL exp | expresion MENORIGUAL exp | expresion MAYORIGUAL exp | determinante | inversa """ t[0] = t[1] + t[2] + str(t[3]) def p_expresion2(self, t): 'expresion : exp' t[0] = t[1] #print(t[0]) def p_exp(self,t): '''exp : exp MAS term | exp MENOS term''' t[0] = str(t[1]) + str(t[2]) + str(t[3]) #print(t[0]) def p_exp2(self,t): 'exp : term' t[0] = t[1] #print(t[0]) def p_term(self,t): '''term : term MULTI fact | term DIV fact''' # temp = [] # temp.append(t[2]) # temp.append(t[1]) # t[0] = temp + [t[3]] t[0] = str(t[1]) + str(t[2]) + str(t[3]) #print(t[0]) def p_term2(self,t): 'term : fact' t[0] = t[1] #print(t[0]) def p_fact(self,t): '''fact : varcte''' t[0] = t[1] #print(t[0]) def p_varcte(self,t): '''varcte : ENTERO | REAL | CHAR | ID ''' t[0] = t[1] #print(t[0]) def p_group(self,t): 'fact : PARIZQ expresion PARDER' t[0] = t[2] def p_determinante(self,t): """determinante : estatuto PESOS""" def p_inversa(self,t): """inversa : estatuto INTERROGACION"""
import os from Scanner import Scanner if __name__ == '__main__': # scan_folder = r'C:\Users\zheng\Desktop\classes-dex2jar.jar.src\client' # output_directory = u'C:\\Users\\zheng\\Desktop\\未命名文件夹\\1' # file_filter_pattern = r'.java' # search_pattern = r'BaseActivity' # # Scanner.scan_and_copy(scan_folder, file_filter_pattern, search_pattern, output_directory) # print 'complete' # 扫描目录下所有图片 scan_folder = r'C:\Users\bomo\Desktop\fdsafdsa' file_filter_pattern = r'.java' content_pattern = r'/api/platformLinkIn/weibo' files = Scanner.scan(scan_folder, file_filter_pattern, content_pattern) for i in files: _, name = os.path.split(i) print i
from Scanner import Scanner, usage scanner = Scanner({'depth': 1, 'excludes': ['timeDiff.php', 'after.php', 'testOut.php']}) scanner.scanDir() myScanner = Scanner({'extension': '.log', 'pattern': r'^err', 'depth': 1, 'path': '/var/log', 'scan':True, 'full': True}) myScanner.scanDir()
class Parser(object): palka = '' def __ini_(self): self.scanner = Scanner() self.scanner.build() tokens = Scanner.tokens precedence = ( ("nonassoc", 'SI'), ("nonassoc", 'SINO'), ("right", 'IGUAL'), ("left", 'OR'), ("left", 'AND'), ("nonassoc", 'MAYORQUE', 'MENORQUE', 'IGUALIGUAL', 'NOT', 'MAYORIGUAL', 'MENORIGUAL'), ("left", 'MAS', 'MENOS'), ("left", 'MULTI', 'DIV', 'MOD'), ) error = 0 def p_error(t): Parser.error = 1 if p: print("Syntax error at line {0}, column {1}: LexToken({2}, '{3}')".format(p.lineno, self.scanner.find_tok_column(t), p.type, p.value)) #exit(1); else: print('At end of input') def p_programa(t): """programa : PROGRAMA ID PUNTOCOMA estatutos_dec_vars declara_funciones metodo_principal | PROGRAMA ID PUNTOCOMA declara_funciones metodo_principal | PROGRAMA ID PUNTOCOMA metodo_principal """ if len(t) == 7: t[0] = AST.Programa( t[4], t[5], t[6]) print("Sintaxis correcta") elif len(t) == 6: t[0] = AST.Programa('None', t[4], t[5]) print("Sintaxis correcta") else: t[0] = AST.Programa('None','None',t[4]) print("Sintaxis correcta") def p_declara_variables(t): """declara_variables : tipo DOSPUNTOS lista_ids declara_variables | empty """ if len(t) == 7: t[0] = AST.Declara_variables(t[1], t[3], t[4]) print("Sintaxis correcta") else t[0] = AST.Empty() def p_estatutos_dec_vars(t): """estatutos_dec_vars : tipo DOSPUNTOS lista_ids PUNTOCOMA estatutos_dec_vars | empty """ if len(t) == 7: t[0] = AST.Estatutos_dec_vars( t[1], t[3], t[4]) print("Sintaxis correcta") else t[0] = AST.Empty() def p_tipo(t): """tipo : ENTERO | REAL | CHAR """ t[0] = t[1] def p_lista_ids(t): """lista_ids : variable | variable COMA lista_ids """ if len(t) == 4: t[0] = ('lista_ids', t[1], t[2]) print("Sintaxis correcta") else t[0] = ('lista_ids', t[1]) def p_variable(t): """variable : ID | ID indice_matriz | ID indice_matriz indice_matriz """ if len(t) == 4: t[0] = ('variable', t[1], t[2], t[3]) print("Sintaxis correcta") elif len(t) == 3: t[0] = ('variable', t[1], t[2]) print("Sintaxis correcta") else t[0] = ('variable', t[1]) print("Sintaxis correcta") def p_indice_matriz(t): """indice_matriz : CORDER ENTERO COR """ t[0] = ('indice_matriz', t[2]) def p_declara_funciones(t): """declara_funciones : MODULO tipo_retorno ID PARIZQ lista_parametros PARDER bloque declara_funciones | empty """ t[0] = ('declara_funciones', t[1], t[2], t[3], t[4], t[6]) def p_tipo_retorno(t): """tipo_retorno : tipo | VOID """ t[0] = ('tipo_retorno', t[1]) def p_lista_parametros(t): """lista_parametros : tipo DOSPUNTOS lista_idparam lista_parametros | empty """ t[0] = ('lista_parametros', t[1], t[3], t[4]) def p_lista_idparam(t): """lista_idparam : ID | ID COMA lista_idparam """ if len(t) == 4: t[0] = ('lista_idparam', t[1], t[3]) print("Sintaxis correcta") else t[0] = ('lista_idparam', t[1]) print("Sintaxis correcta") def p_bloque(t): """bloque : LLAVEIZQ declara_variables estatutos REGRESA PARIZQ expresion PARDER LLAVEDER """ t[0] = ('bloque', t[2], t[3], t[4], t[5]) def p_metodo_principal(t): """metodo_principal : PRINCIPAL PARIZQ PARDER LLAVEIZQ declara_variables estatutos LLAVEDER """ t[0] = ('metodo_principal', t[1], t[5], t[6]) def p_estatutos(t): """estatutos : estatuto | estatuto PUNTOCOMA estatutos | empty """ if len(t) == 4: t[0] = ('estatutos', t[1], t[3]) else t[0] = ('estatutos', t[1]) def p_estatuto(t): """estatuto : asignacion | llamada | lectura | escritura | decision | repeticion | expresion """ t[0] = ('estatuto', t[1]) def p_asignacion(t): """asignacion : variable IGUAL estatuto """ t[0] = ('asignacion', t[1], t[3]) def p_llamada(t): """llamada : ID PARIZQ lista_valores PARDER """ t[0] = ('llamada', t[1], t[3]) def p_lectura(t): """lectura : LEER PARIZQ lista_valores PARDER """ t[0] = ('lectura', t[1], t[3]) def p_escritura(t): """escritura : ESCRIBIR PARIZQ lista_valores PARDER """ t[0] = ('escritura', t[1], t[3]) def p_decision(t): """decision : SI PARIZQ estatuto PARDER | SI PARIZQ estatuto PARDER SINO LLAVEIZQ estatutos LLAVEDER """ if len(t) == 9: t[0] = ('decision', t[1], t[3], t[5], t[6]) else t[0] = ('decision', t[1], t[3]) def p_repeticion(t): """repeticion : mientras | repite """ t[0] = ('repeticion', t[1]) def p_mientras(t): """mientras : MIENTRAS PARIZQ estatuto PARDER HAZ LLAVEIZQ estatutos LLAVEDER """ t[0] = ('mientras', t[1], t[3], t[5],t[7]) def p_repite(t): """repite : REPITE LLAVEIZQ estatutos LLAVEDER HASTA PARIZQ estatuto PARDER """ t[0] = ('repite', t[1], t[3], t[5],t[7])
import cv2 #import numpy as np from Scanner import Scanner from TopCode import TopCode scan = Scanner() cam = cv2.VideoCapture(0) if not cam.isOpened(): raise Exception("No camera detected!") while True: ret, image = cam.read() cv2.imshow("img", image) cv2.waitKey(1) if(image is not None): spots = scan.scan(image = image) print "Detected " + str(len(spots)) + " targets"