def FindRadionuclideInventory(matName, SE_FMA, Directory): DirectoryResults = Directory + '/' + matName # Directory with the results from ActiWiz DirectoryRN = DirectoryResults + '_RN' # Directory with the scaling factors if not os.path.exists(DirectoryRN): # Create the directory if not existing os.makedirs(DirectoryRN) # List of files to be analysed, with Actiwiz results ListFiles = os.listdir(DirectoryResults) ListNuclidesFMA = [] # Loop to analyse all the files with the Actiwiz results for fileName in ListFiles: originalInventory = [] scanner(DirectoryResults + '/' + fileName, originalInventory, '#') # The following list contains nuclides with activity above declaration shortInventoryFMA = FMA(SE_FMA, originalInventory) # List of nuclides as above, but cumulative over all the scenarios for a in shortInventoryFMA: AddNuclide(a[0], ListNuclidesFMA) # Open the file in the desired directory and save the data f = open(DirectoryRN + '/RadionuclideInventory_FMA_' + str(SE_FMA), 'w') # Writing the radionuclides for a in ListNuclidesFMA: f.write("".join(map(lambda x: str(x), a)) + "\n") f.close() return ()
def scan(filename, out): try: with open(out, 'w') as f: with redirect_stdout(f): sc.scanner(filename) except FileNotFoundError as e: print(e)
def ask_directory(): directory = tkFileDialog.askdirectory() if directory == '': tkMessageBox.showinfo("Информация", "Директория не выбрана!") else: scanner.scanner(directory) tkMessageBox.showinfo("Информация", "Сканирование завершено!") root.quit()
def parse(self): # print(self.text_box.get()) scanner(self.text_box.get()) lst_tokens = tokenizer(file='output.txt') init_node = Node() parser = Parser(lst_tokens) parser.parents.append(init_node.index) parser.program() parser.draw_tree()
def schedule_test_for_sequence(executable): """ Schedule test for a sequence :param executable: :return: """ results = {} scanner(executable, results, "sequence_result") return results["sequence_result"]
def FMA(SE_FMA, inventory): limits = [] scanner('Andra_FMA_2', limits, "#") sum_activity = 0. inventoryWithFMA = [] for a in inventory: for b in limits: if a[0] == b[0]: name = a[0] activity = a[1] # energy=a[2] limit = b[1] declaration = b[2] maxlimit = b[3] emission = b[4] FMA_fraction3 = (emission == 1) inventoryWithFMA.append([ name, activity, FMA_fraction3, declaration, maxlimit, limit ]) sum_activity = sum_activity + activity # print (sum_activity) RN_list = [] for c in inventoryWithFMA: if c[4] > c[1] / sum_activity * SE_FMA > c[3]: RN_list.append([c[0], c[1] / sum_activity * SE_FMA]) RN_list.sort(lambda x, y: cmp(y[1], x[1])) RN_list.sort(key=lambda x: x[0]) f = open("Results/Aluminium_6060_RA/RadionuclideInventory_RA_", 'a+') # f.write(",".join(map(lambda x: str(x), RN_list))+"\n") f.write(",".join([','.join(map(str, item)) for item in RN_list]) + "\n") # f.write("#"+"".join(RN_list)+"\n") f.close() from parse_results import parseResults parseResults("Results/Aluminium_6060_RA/RadionuclideInventory_RA_", "Results/Aluminium_6060_RA/RadionuclideInventory_RA_new.csv") print(RN_list) return (RN_list)
def ValueIRAS(inventory): limits = [] scanner('Andra', limits, "#") totalIRAS = 0. for a in inventory: for b in limits: if a[0] == b[0]: name = a[0] activity = a[1] limit = b[1] totalIRAS = totalIRAS + activity / limit return (totalIRAS)
def ValueNewORAP(inventory): limits = [] scanner('NewORAP', limits, "#") totalORAP = 0. for a in inventory: for b in limits: if a[0] == b[0]: name = a[0] activity = a[1] limit = b[6] totalORAP = totalORAP + activity / limit return (totalORAP)
def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) #Scanner init self.SC = scanner.scanner() self.frames = {} for F in (StartPage, Scanner, PageTwo): page_name = F.__name__ frame = F(container, self) self.frames[page_name] = frame # put all of the pages in the same location; # the one on the top of the stacking order # will be the one that is visible. frame.grid(row=0, column=0, sticky="nsew") self.show_frame("StartPage")
def find_bi_grams(self, filename): scan = scanner.scanner(filename) src = scan.get_sourcelist() for line in src: bigram = line.get_gram() if self.is_valid_bi_gram(bigram.split()): self.bgf_table.append(line)
def __init__(self): cmd.Cmd.__init__(self) self.prompt = "> " self.intro = "Welcome to console!" ## defaults to None #print "########################################################################################################################################################" #print "# #" #print "# ,ad8888ba, 88 ,ad8888ba, 888888888888 #" #print "# d8"' `"8b 88 d8"' `"8b 88 #" #print "# d8' `8b 88 d8' 88 #" #print "# 88 88 8b,dPPYba, 88,dPYba,,adPYba, ,adPPYba, 8b,dPPYba, 88 88 88 #" #print "# 88 88 88P' \"Y8 88P\' \"88\" \"8a a8P_____88 88P\' \"Y8 88 88 88 #" #print "# Y8, ,8P 88 88 88 88 8PP""""""\" 88 88 Y8, 88 #" #print "# Y8a. .a8P 88 88 88 88 "8b, ,aa 88 88 Y8a. .a8P 88 #" #print "# `"Y8888Y"' 88 88 88 88 `"Ybbd8"' 88 88 `"Y8888Y"' 88 #" #print "# #" #print "# #" #print "# #" #print "# 88888888ba 88 888888888888 88 #" #print "# 88 "8b ,d ,d "" 88 88 #" #print "# 88 ,8P 88 88 88 88 #" #print "# 88aaaaaa8P' ,adPPYba, 8b,dPPYba, MM88MMM ,adPPYba, ,adPPYba, MM88MMM 88 8b,dPPYba, ,adPPYb,d8 88 ,adPPYba, ,adPPYba, 88 #" #print "# 88""""""' a8P_____88 88P' `"8a 88 a8P_____88 I8[ "" 88 88 88P' `"8a a8" `Y88 88 a8" "8a a8" "8a 88 #" #print "# 88 8PP""""""" 88 88 88 8PP""""""" `"Y8ba, 88 88 88 88 8b 88 88 8b d8 8b d8 88 #" #print "# 88 "8b, ,aa 88 88 88, "8b, ,aa aa ]8I 88, 88 88 88 "8a, ,d88 88 "8a, ,a8" "8a, ,a8" 88 #" #print "# 88 `"Ybbd8"' 88 88 "Y888 `"Ybbd8"' `"YbbdP"' "Y888 88 88 88 `"YbbdP"Y8 88 `"YbbdP"' `"YbbdP"' 88 #" #print "# aa, ,88 #" #print "# "Y8bbdP" #" #print "# By: Job, Rico, Quinten & Lars - From: The Hage University #" #print "########################################################################################################################################################" #print "########################################################################################################################################################" #scanner Object self.SC = scanner.scanner()
def main(lines): if(label3.cget("text") == "Code"): gr.reset() gr.outputs = src.scanner(lines) save_to_file(gr.outputs,"whatheoutputs.txt") #for debugging gr.set_error() #set error = zero gr.program() gr.generate_tree() print(gr.get_error()) if(gr.get_error()): #handling errors label2.config(text="Syntax Error!") # gr.generate_tree() elif(label3.cget("text") == "Parse"): gr.outputs = parser_input(lines) #gr.set_error() # set error = zero gr.program() print(gr.get_error()) if (gr.get_error()): # handling errors label2.config(text="Syntax Error!") else: gr.generate_tree()
def selector(mode=0): global _files filetypes = ['.png', '.jpg', 'gif'] filetypes_2 = [('Image files', '*.png;*.jpg;*.gif')] if (mode == 0): print('单文件选择') files = tk.filedialog.askopenfilename(filetypes=filetypes_2) _files.append(files) elif (mode == 1): print('多文件选择') files = tk.filedialog.askopenfilenames(filetypes=filetypes_2) _files.extend(list(files)) elif (mode == 2): print('文件夹遍历') directory = tk.filedialog.askdirectory() if not directory == '': scan = scanner() _files.extend(scan.scan(directory, filetypes)) elif (mode == 3): # 单层文件夹 # _files = tk.filedialog.askopenfilenames() pass # 去重 _files = list(set(_files)) # 美化 for filename in _files: _files[_files.index(filename)] = filename.replace('\\', '/') # 显示于列表 _files.sort() lsbox_files.set(_files)
def main(): parser = argparse.ArgumentParser(prog="GENESTEALER") parser.add_argument('mode', choices=["manual", "auto"], help="Whether to expect specified targets or not") parser.add_argument( '--target', action='extend', nargs='+', help="Initial target for worm (only for manual attack mode)", type=ip_address) args = parser.parse_args() if args.mode == 'manual' and args.target is None: parser.error("Manual mode specified but no target given!") else: nmap = scanner() if args.mode == 'manual': for victim in args.target: print(f"Manual attack started against {victim}") attack(victim) else: print("Auto attack against network") curr_box = nmap.get_self_ip() print("Identifying targets...") victims = nmap.ping_scan(curr_box) if victims is [] or victims is None: print("Found no one to pwn :(") for victim in victims: attack(victim)
def AboveDeclarationForGivenCurrent(inventory, current): limits = [] scanner('Andra_FMA', limits, "#") inventoryAboveDeclaration = [] for a in inventory: for b in limits: if a[0] == b[0]: name = a[0] activity = a[1] * current declaration = b[2] if activity >= declaration: inventoryAboveDeclaration.append([name, activity]) inventoryAboveDeclaration.sort(lambda x, y: cmp(y[1], x[1])) return (inventoryAboveDeclaration)
def BelowMDAForGivenCurrent(inventory, current): limits = [] scanner('Andra_FMA', limits, "#") inventoryBelowMDA = [] for a in inventory: for b in limits: if a[0] == b[0]: name = a[0] activity = a[1] * current maxlimit = b[3] if activity <= maxlimit: inventoryBelowMDA.append([name, activity]) inventoryBelowMDA.sort(lambda x, y: cmp(y[1], x[1])) return (inventoryBelowMDA)
def __init__(self): cmd.Cmd.__init__(self) self.prompt = "> " self.intro = "Welcome to console!" ## defaults to None #scanner Object self.SC = scanner.scanner()
def main(file_programm, file_tokens, file_xml_tree): tokens_list_without_comment = [] # Сегмент лексического анализа with open(file_programm, 'r') as input_file_program: tokens_list = scanner.scanner(input_file_program) errors = False with open(file_tokens, 'w') as output_file_tokens: for token in tokens_list: line = token.get_description() if token.lexeme != 'Comment': tokens_list_without_comment.append(token) output_file_tokens.write(line + '\n') if token.definite_lexeme is 'Error': line = 'Error:' + str( token.get_line_number()) + token.get_error_description() print(line) errors = True # Сегмент синтаксического анализа if not errors: xml_tree = xml_builder(tokens_list_without_comment) with open(file_xml_tree, 'w') as output_file_xml_tree: output_file_xml_tree.write(xml_tree) print('OK') else: sys.exit(0)
def scan_drawing(self): """ Method called when one click on the scan and save button. The scanner object is created here (and hence deleted) to be sure that it does not stay in the memory. """ if False in self.info_complete.values(): QtGui.QMessageBox.warning(self, 'information incomplete', 'One of the information is not correct') return my_scanner = scanner.scanner(self.config) scanner_name = my_scanner.get_scanner_name() my_scanner.set_scanner(scanner_name[0]) my_scanner.set_scan_area() drawing_path = self.check_scanned_drawing_directory() print(drawing_path, type(drawing_path)) if drawing_path: if os.path.isfile(drawing_path): response = QtGui.QMessageBox.question( self, 'same drawing found' '', 'This drawing alreay exists. Re-scan?', QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) if response == QtGui.QMessageBox.Yes: pass elif response == QtGui.QMessageBox.No: return my_scanner.scan(drawing_path)
def main(src): try: # On test si le fichier existe bien fo = open(src, "r") fo.close() except IOError: print("Le fichier donné n'existe pas.") return 0 with open(src) as file: exp = file.read() # On transforme la chaine d'entrée en une liste d'unité lexicale ul = scanner(exp) # On convertit cette liste en une liste contenant l'expression postfixé postfix = parser(ul) if postfix[0]: print("Chaine valide\n") # A commenter pour la lisibilité lors des test # On écrit dans un fichier, sous forme d'une pile, l'expression codegen(postfix[1]) os.chmod("a.out", 0o744) return True else: print("Erreur syntaxique à la position {}: {}.\nIl manque une partie "\ "de l'expression\n".format(postfix[1], exp[postfix[1]-1])) return False
def convert_Tree(string): ''' Convert string to abstract format tree ''' string = '(' + string + ')' tree, status = parser(scanner(string, 's'), 't') tree = checkQuation(tree) return convert(tree)
def read_wiz(file, inventory): temp1 = [] temp2 = [] total = 0. scanner(file, temp1, '#') for a in temp1: # a[0] is the element name # a[2] is the mass number # a[3] is the relative activity # a[7] is the fraction of LE limit temp2.append([a[0] + '-' + str(int(a[2])), a[7]]) total = total + a[7] for b in temp2: # b[0] is the nuclide name # b[1]/total is the fraction of LE (normalized to 1) inventory.append([b[0], b[1] / total]) return
def run(self): # info = urllib2.urlopen(self.url).info() html_name, url_name = scanner([self.url], "000") a = Analyzer(html_name, url_name) print self.url self.model.mydata = self.model.mydata + [(self.url, a.getAds()[1], a.getAds()[0], a.getUniqueVisitors(), "0")] self.model.emit(SIGNAL("layoutChanged()"))
def test_scanner(self): param = ["5- (9+2 *3)", "56"] # liste des paramaetres a tester result = [[('NOMBRE', '5'), ('OP', '-'), ('PAR_OUV', '('), ('NOMBRE', '9'), ('OP', '+'), ('NOMBRE', '2'), ('OP', '*'), ('NOMBRE', '3'), ('PAR_FER', ')')], [("NOMBRE", '56')] ] # liste des resultats pour chaque parametre for i in range(2): self.assertEqual(scanner.scanner(param[i]), result[i])
def test_scanner(self): param = ["VRAI OU NON FAUX", "(VRAI)"] # liste des parametres a tester result = [[('BOOL', 'VRAI'), ('OP', 'OU'), ('OP', 'NON'), ('BOOL', 'FAUX')], [('PAR_OUV', '('), ('BOOL', 'VRAI'), ('PAR_FER', ')')] ] # liste des resultats pour chaque parametre for i in range(2): self.assertEqual(scanner.scanner(param[i]), result[i])
def parser(): global token token = scanner.scanner() # inicializa con el primer token # print "inicio", token exp() # print "fin", token if token[0] == scanner.END: print "Expresion bien construida!!" else: error("expresion mal terminada")
def AnalysisOneMaterial(matName, keyNuclide, DMN, Directory): DirectoryResults = Directory + '/' + matName # Directory with the results from ActiWiz DirectorySF = DirectoryResults + '_SF' # Directory with the scaling factors if not os.path.exists(DirectorySF): # Create the directory if not existing os.makedirs(DirectorySF) # List of files to be analysed, with Actiwiz results ListFiles = os.listdir(DirectoryResults) for nuclide in DMN: ScalingList = [] for fileName in ListFiles: originalInventory = [] scanner(DirectoryResults + '/' + fileName, originalInventory, '#') try: activityKeyNuclide, ScalingFactorDMN = FindScalingFactor( nuclide, keyNuclide, originalInventory, ) ScalingList.append( [activityKeyNuclide, ScalingFactorDMN, fileName]) # activityKeyNuclide*1.0E10 ScalingList.sort(lambda x, y: cmp(x[0], y[0])) except: pass # Open the file in the desired directory and save the data f = open(DirectorySF + '/' + nuclide + '_' + keyNuclide, 'w') # Writing the first line of comment, with the input parameters# f.write("# Activity of key nuclide, Scaling Factor,Scenario\n") # Writing the scaling factors, line by line for a in ScalingList: # b=[a[1],a[2]] # Artefact to pick up only the last two values and skip a[0], which is the nuclide f.write(" ".join(map(lambda x: str(x), a)) + "\n") return ()
def testDriver_i(): for line in sys.stdin: outPut = '' if line == '\n': print('The input line is empty, exit program') sys.exit() info, status = parser(scanner(line,'s'),'t') if status == True: info = interpreter(info) outPut = "\n> " + line + str(info) + '\n' sys.stdout.write(outPut)
def testDriver_s(): for line in sys.stdin: outPut = '' if line == '\n': print('The input line is empty, exit program') sys.exit() info = scanner(line,'t') print(info) print('\n') #outPut = "\nInput string : " + line + info + '\n' sys.stdout.write(outPut)
def testDriver_p(): for line in sys.stdin: outPut = '' if line == '\n': print('The input line is empty, exit program') sys.exit() parserInfo, status = parser(scanner(line,'t'),'t') print("This is final result") print(parserInfo) #outPut = "\nInput string : " + line + parserInfo + '\n' sys.stdout.write(outPut)
def openfile(self): root.filename = filedialog.askopenfilename( initialdir=".", title="Select a file", filetypes=(('png files', '*.png'), ('jpg files', '*.jpg'))) scan = scanner(root.filename) scan.getDigits() self.digits = scan.grid for i in range(9): for j in range(9): if scan.grid[i][j] != 0: self.grid[i][j].insert(0, int(scan.grid[i][j]))
def detector(): while True: frame = capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) data = scanner(gray) if data != "nothing detected": # detected print(data) text_file = open( os.path.dirname(os.path.realpath(__file__)) + '/detected.txt', "w") text_file.write(data) text_file.close()
def main(): read_config_file() camera = sc.scanner(pylog=True, summary=False) time.sleep(2) menu = cm.CursesMenu("Astroscan", "Actions") scanitem = cm.items.FunctionItem("Capture controls", scan_controls, [camera, menu]) settingmenu = cm.SelectionMenu(strings=[], title="Astroscan parameters menu") resetitem = cm.items.FunctionItem("Set image count", reset_imgcount, []) hdritem = cm.items.FunctionItem("Set HDR number", reset_hdrframe, []) inftyitem = cm.items.FunctionItem("Set maximum count", reset_imginfty, []) rangeitem = cm.items.FunctionItem("Set exposure bracket", reset_exprange, []) expitem = cm.items.FunctionItem("Set exposure time", reset_exptime, [camera]) isoitem = cm.items.FunctionItem("Set ISO value", reset_iso, [camera]) calibmenu = cm.SelectionMenu(strings=[], title="Astroscan calibration menu") flatitem = cm.items.FunctionItem("Take flat exposures", take_flats, [camera, 0.0]) zeroitem = cm.items.FunctionItem("Take zero exposures", take_zeros, [camera, 0.0]) menu.append_item(scanitem) settingmenu.append_item(resetitem) settingmenu.append_item(hdritem) settingmenu.append_item(inftyitem) settingmenu.append_item(rangeitem) settingmenu.append_item(expitem) settingmenu.append_item(isoitem) settingitem = cm.items.SubmenuItem("Settings menu", settingmenu, menu) menu.append_item(settingitem) calibmenu.append_item(flatitem) calibmenu.append_item(zeroitem) calibitem = cm.items.SubmenuItem("Calibration menu", calibmenu, menu) menu.append_item(calibitem) menu.show()
def runner(): finish = False print( "\nHello! welcome to use the shell version of mini-scheme.\nYou can type your code after < or type nothing to exit the program \n" ) while finish == False: line = input('< ') outPut = '' if line == '': print('The input line is empty, exit program') finish = True else: info, status = parser(scanner(line, 's'), 't') if status == True: info = interpreter(info) outPut = str(info) + '\n' print(outPut)
def main(argv): try: global url url = argv[1] filename = argv[2] chunks = int(argv[3]) except IndexError: print "Error in the syntax!\n" print "\tUsage:\n", sys.argv[0], "<url> <filename> <numofchunks>" sys.exit(1) files = [] sizes = [] print "Connecting to the site for getting file size..." size = int(getsize(url)) print "Size: ", size, "bytes" print "Starting to set the required ips." ips, diface = scanner(chunks) print ips, diface chunksize = int(size / chunks) partsize = int(size / chunks) newstart = 0 if len(argv) > 4: if argv[4] == '-p': try: part = int(argv[5]) filename = filename + str(part) + '.dat' newstart = int((part - 1) * partsize) # print newstart # sys.exit(1) # newend = partsize+newstart partsize = int(size / (chunks * chunks)) except Exception, e: print "Error! expected the required chunk number to re-download with \"-p\" option." sys.exit(1) else: print "Error! Expected only three arguments!\n\tUsage:\n" print sys.argv[0], "<url> <filename> <numofchunks> [-p <chunknumber to re-download>" print "(Be sure that num of chunks is same as the previous failed download.)]" sys.exit(1)
if url_properties != None: for property in url_properties: scanner.set_option(property, url_properties[property]) if 'br-x' not in url_properties.keys() and 'br-y' not in url_properties.keys(): scanner.max_end_scan() else: scanner.max_end_scan() print page # Begin scan, it feeds a frame at a time scanner.start_scan() while scanner.is_scanning: scanner.scan() scanner.img.save(self.wfile,'JPEG') else: print 'Scan in progress, this request is sent single image' self.send_header('Content-type','image/jpeg') self.end_headers() scanner.img.save(self.wfile,'JPEG') return scanner = scanner(0) server = ThreadedHTTPServer(('',80),scanHandler) server.serve_forever()
import requests import pickle queries = ['baby questions', 'need to know about baby', 'new baby', 'what to expect baby'] outfile = 'baby_questions.pkl' #search google and get query results print 'searching Google for: ' + str(queries) gstart = timer() start = timer() query_results = [] for q in queries: print q + '...' query_results.extend(scanner(q, 1, 4)) #search term, pages to scrape, num processes end = timer() print 'num results = %f' % len(query_results) print 'time elapsed = ' + str(end-start) + ' sec' print '...' #now go through each query and get the raw html print 'getting raw HTML from each website:' h = html2text.HTML2Text() h.ignore_links = True h.ignore_images = True final_questions = []
def main(): opts = mgetopt() if opts: scanner(opts['-r'], opts['-t'])
] } json_data = json.dumps(location_data) location_result = json.loads((requests.post(url, data=json_data)).text) loc = location_result['location'] accuracy = location_result['accuracy'] lattitude = loc['lat'] longitude = loc['lng'] return lattitude, longitude, accuracy if __name__ == '__main__': try: while True: tidy() print "Creating general scanner object" g_scanner = scanner(iface) #print "g_scanner:", g_scanner #debug print "Creating pipe for general scan" #Pipes for control of external application processes airodump_parent_conn, airodump_child_conn = Pipe() print "Creating process for general scan" airodump = Process(target=g_scanner.scan, kwargs={ 'out_format':'netxml', 'out_dest':output_dir, 'conn':airodump_child_conn, 'interval':'20'}) #This interval should be configurable by cmd line variable print "Creating process for folder watch" observer = Observer() #folder watchdog process to monitor outputxml from airodump-ng observer.schedule(MyHandler(), path=output_dir) airodump.start() scanning = True time_started = time.time()
# Import Psyco if available #try: # import psyco # psyco.full() # print "Psyco loaded" #except ImportError: # pass #from labeling import label_object, scan_dataset, scans_database #database = scans_database.scans_database() #database.load('/home/martin/robot1_data/usr/martin/laser_camera_segmentation/labeling','database.pkl') #dataset = scan_dataset.scan_dataset() #print dataset cfg = configuration.configuration('/home/martin/robot1_data/usr/martin/laser_camera_segmentation/labeling') sc = scanner.scanner(cfg) pc = Processor.Processor(cfg) name = ut.formatted_time() name='2009Oct17_122644' #sc.capture_and_save(name) pc.load_data(name) #pc.load_raw_data('pill_table/2009Sep12_142422') pc.process_raw_data() pc.save_mapped_image(name) pc.display_all_data() print 'done'
def showDialog(self): text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog', 'Enter Hologram:hologram(#)+hologram(#)') if ok: #lists input on the right self.lbl.setText(text) self.lbl.move(500,125) self.lbl.adjustSize() if text == "phaseshift": for u in range(100): phiout = projectconveyor.construct(u*(2.*np.pi/100.)) #calls projectconveyer to create the optical conveyor array img = SLM(phiout) #sends the array to SLM() which projects the array onto the SLM pixmap = QtGui.QPixmap(img) pixmap = pixmap.scaledToHeight(300) self.label.setPixmap(pixmap)#sends the array to the smaller window on the main screen print(u*(2.*np.pi/100.)) QtGui.QApplication.processEvents() #pauses the program to let the image buffer onto the SLM and window elif text == "cameratest": cv.NamedWindow("camera",1) #starts up opencv capture = cv.CaptureFromCAM(1) QtGui.QApplication.processEvents() img = cv.QueryFrame(capture) cv.ShowImage("camera",img) cv.SaveImage("cameratest.jpg",img) elif text == "video": #captures video cap= cv.VideoCapture(0) fourcc = cv.cv.CV_FOURCC(*'XVID') #fourcc = cv.VideoWriter_fourcc(*'XVID') out = cv.VideoWriter('output.avi',fourcc,50.0,(640,480)) #fps and resolution while (cap.isOpened()): ret, frame = cap.read() if ret==True: frame = cv.flip(frame,0) out.write(frame) cv.imshow('frame',frame) if cv.waitKey(1) & 0xFF == ord('q'): break else: break cap.release() #out.release() cv.destroyAllWindows() elif text == "video1": #captures video inline self.playing = True cap= cv.VideoCapture(0) fourcc = cv.cv.CV_FOURCC(*'XVID') #fourcc = cv.VideoWriter_fourcc(*'XVID') out = cv.VideoWriter('output.avi',fourcc,50.0,(640,480)) #fps and resolution while self.playing: _, data = cap.read() data = cv.cvtColor(data, cv.cv.CV_BGR2RGB) qImage = QtGui.QImage(data, data.shape[1], data.shape[0], QtGui.QImage.Format_RGB888) self.label.setPixmap(QtGui.QPixmap.fromImage(qImage)) self.label.adjustSize() QtGui.qApp.processEvents() time.sleep(0.02) else: #IMPORTANT SECTION HERE ---------------ROBUST TEXT ACCEPTOR---------------------------- text = text.encode('ascii','ignore') #converts from unicode to ascii text = text.decode('ascii') hologram = scanner.scanner(text)#splits up the input into the individual holograms with their paramaters print(hologram) phiout = np.zeros((c.slm_h, c.slm_w)) for indiv in hologram: for file in os.listdir("/home/nikitas/Desktop/TractorMaster"):#searches main folder if indiv[0] in file: if file.endswith('.py'): a = __import__(indiv[0])#imports the corresponding function if indiv[1] == '': subphiout = a.construct()#default else: subphiout = a.construct(*indiv[1])#generates the array phiout += subphiout #adds the arrays, next line imports correction """fix = Image.open("/home/nikitas/Desktop/TractorMaster/correction.bmp") fix = np.array(fix) phiout += fix #adds correction map for SLM(532 nm) print("post1",fix) print("post1 shape", fix.shape)""" #phiout = phiout.astype(float) #phiout *= 200./256. #phiout = phiout % 256 print("post2", phiout) print("post2 shape",phiout.shape) converted_image = q2.gray2qimage(phiout, normalize = True) pixmap = QtGui.QPixmap(converted_image) pixmap = pixmap.scaledToHeight(300) SLM(converted_image) self.label.setPixmap(pixmap)
def __init__(self, mainDir, pause): self.mainDir = mainDir scanInt = scanner.scanner(self.mainDir) self.picList = scanInt.scanDir() self.pause = pause