def YoutubeLinkDownload(self): txt, ok = QtGui.QInputDialog.getText( self, "YouTube Link", "YTube Link:", QtGui.QLineEdit.Normal, "", QtCore.Qt.FramelessWindowHint ) if ok == True: if txt.startsWith("https://www.youtube.com"): key = self.freeKey() if key == -1: obj = Interface(self.PARTS) else: obj = self.dLoads[key] obj.PARTS = self.PARTS obj.clear() del self.dLoads[key] thread.start_new_thread(obj.start_Download, (txt, self.wMutex)) self.dLoads[self.links] = obj self.links = self.links + 1 else: msg = QtGui.QMessageBox( QtGui.QMessageBox.Warning, "Oops.", "Not a valid YTube Url ", QtGui.QMessageBox.Ok, self, QtCore.Qt.FramelessWindowHint, ) msg.show()
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Interface() self.ui.UI_Setup(self) self.list = [] self.flag = 0 self.ui.pushButton.clicked.connect(self.trigger)
def __init__(self): self.interface = Interface() self.config = Config() self.images = Images(self.config.get('Images', 'dir'), self.interface) self.imageList = self.images.getFileList() if len(self.imageList) == 0: raise Exception('There are no images to scythe')
def fetchAndSaveUrl(self, url="", bit=1): ok = True if len(url) == 0: url, ok = QtGui.QInputDialog.getText( self, "Link", "Download Link:", QtGui.QLineEdit.Normal, "", QtCore.Qt.FramelessWindowHint ) if ok == True: key = self.freeKey() if key == -1: obj = Interface(self.PARTS) key = self.links self.links = self.links + 1 else: obj = self.dLoads[key] obj.PARTS = self.PARTS obj.clear() del self.dLoads[key] thread.start_new_thread(obj.start_Download, (url, self.wMutex, bit)) self.dLoads[key] = obj else: msg = QtGui.QMessageBox( QtGui.QMessageBox.Warning, "Oops.", "Not a valid Url ", QtGui.QMessageBox.Ok, self, QtCore.Qt.FramelessWindowHint, ) msg.show()
def dicom_tests(): logger = logging.getLogger(dicom_tests.__name__) # Test DICOM Instantiate from OrthancInterface import OrthancInterface proxy = OrthancInterface(address='http://localhost:8043', name='3dlab-dev1') source = DICOMInterface(proxy=proxy, name='3dlab-dev0+dcm') # Test DICOM Subject Query r = source.find('subject', {'PatientName': 'ZNE*'})[0] assert r.subject_id == 'ZA4VSDAUSJQA6' # Test DICOM Q/R/DL from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('3dlab-dev0+dcm', repos) target = Interface.factory('3dlab-dev1', repos) w = source.find( 'series', { 'SeriesInstanceUID': '1.2.840.113654.2.55.4303894980888172655039251025765147023' })[0] u = target.retrieve(w, source)[0] target.copy(u, target, 'nlst_tmp_archive') assert os.path.getsize('nlst_tmp_archive.zip') == 176070 os.remove('nlst_tmp_archive.zip')
def main(): msg = WhatIsMessage() # The hidden prepend keyword of the text input also includes # double-quotes so that left whitespace is not stripped by the # server. if msg and msg.startswith("\""): msg = msg[1:] Logger("CHAT", "Console: {}: {}".format(activator.name, msg)) console = console_find(activator) if msg == "exit()": if console: console_remove(activator) inf = Interface(activator, None) inf.dialog_close() return if not console: console = console_create(activator) console.push(msg) if not msg: console.show()
def dicom_tests(): logger = logging.getLogger(dicom_tests.__name__) # Test DICOM Instantiate from OrthancInterface import OrthancInterface proxy = OrthancInterface(address='http://localhost:8043', name='3dlab-dev1') source = DICOMInterface(proxy=proxy, name='3dlab-dev0+dcm') # Test DICOM Subject Query r = source.find('subject', {'PatientName': 'ZNE*'})[0] assert r.subject_id == 'ZA4VSDAUSJQA6' # Test DICOM Q/R/DL from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('3dlab-dev0+dcm', repos) target = Interface.factory('3dlab-dev1', repos) w = source.find('series', {'SeriesInstanceUID': '1.2.840.113654.2.55.4303894980888172655039251025765147023'})[0] u = target.retrieve(w, source)[0] target.copy(u, target, 'nlst_tmp_archive') assert os.path.getsize('nlst_tmp_archive.zip') == 176070 os.remove('nlst_tmp_archive.zip')
def test_dicom_download_production(): # Example of how to download a worklist of series. # # Format worklist like this: # # SeriesInstanceUIDs: # - x.y.zzz.wwwwww.u.ttt.s.aaaaaaaaaaa.... # - x.y.zzz.wwwwww.u.ttt.s.aaaaaaaaaab.... # # Can search for "Series/Study/PatientInstanceUID", "AccessionNumber", "PatientName" or "PatientID" raise SkipTest repos = read_yaml('repos.yaml') source = Interface.factory('gepacs', repos) target = Interface.factory('deathstar', repos) # worklist_config = read_yaml('series_worklist.yaml')['SeriesInstanceUIDs'] # # for entry in worklist_config: # w = source.find('study', {'AccessionNumber': 'R13851441'})[0] u = target.find('study', {'AccessionNumber': 'R13851441'})[0] #u = target.retreive(w, source)[0] target.copy(u, target, '/Users/derek/Desktop/%s_archive' % u.study_id.o)
def __init__(self): '''Инициализация модуля Выполняется инициализация интерфейса, логгера и статуса соединения Определяется операционная система и задаются соответствующие пути ''' self.view = Interface(self) self.logger = logging.getLogger('RocketOne.Connector') self.connected = False # Пути до OpenVPN if os.name == "nt": #Windows paths self.ovpnpath = 'C:\\Program Files (x86)\\OpenVPN' self.path = getBasePath() + '/' self.ovpnconfigpath = self.ovpnpath + '\\config\\' self.configfile = 'config.ini' # self.ovpnconfigpath + self.ovpnexe = self.ovpnpath + '\\bin\\openvpnserv.exe' self.traymsg = 'OpenVPN Connection Manager' self.logger.debug("Started on Windows") elif os.name == "posix": #Linux Paths self.ovpnpath = '' self.path = getBasePath() + '/' self.ovpnconfigpath = self.ovpnpath + '//home//alexei//SOLOWAY//' self.ovpnexe = self.ovpnpath + 'openvpn' self.configfile = 'config.ini' self.traymsg = 'OpenVPN Connection Manager' self.logger.debug("Started on Linux")
def __init__(self, argv): # init, initialization class self.init = Init(argv) # Get logger from Init class self.log = logging.getLogger('get_UART') # Serial com variable definition self.serial_com = UART(port=self.init.get_serial_port()) # System class self.system = System() # Is UART init a program beginning self.init_UART_bit = self.init.get_init_UART_bit() # Define interface class self.interface = Interface() # Plot curve class self.plot_curve_class = PlotCurve() # Temp data self.temp_data_tab = []
def YoutubeLinkDownload(self): txt, ok = QtGui.QInputDialog.getText(self, 'YouTube Link', 'YTube Link:', QtGui.QLineEdit.Normal, '', QtCore.Qt.FramelessWindowHint) if ok == True: if txt.startsWith('https://www.youtube.com'): key = self.freeKey() if key == -1: obj = Interface(self.PARTS) else: obj = self.dLoads[key] obj.PARTS = self.PARTS obj.clear() del self.dLoads[key] thread.start_new_thread(obj.start_Download, (txt, self.wMutex)) self.dLoads[self.links] = obj self.links = self.links + 1 else: msg = QtGui.QMessageBox(QtGui.QMessageBox.Warning, 'Oops.', "Not a valid YTube Url ", QtGui.QMessageBox.Ok, self, QtCore.Qt.FramelessWindowHint) msg.show()
def insert_dicionarios(self, myJson): #myJson == [] # dic {} # list [] insercoes = [] atualizacoes = [] delete_list = [] #myJson is a list sendAlert = EnviarNotificacao() myJson = json.loads(myJson) for dicio in myJson: if str(dicio["type_log"]) == 'INSERT': insercoes.append(dicio) elif str(dicio["type_log"]) == 'DELETE': #Só id delete_list.append(str(dicio["id_produto"])) #lista de ids else: atualizacoes.append(dicio) print(insercoes) print(atualizacoes) print(delete_list) MyInterface = Interface() error = MyInterface.realiza_operacoes_atualizacao_bd( insercoes, atualizacoes, delete_list) if error is not None: print(error) pass #sendAlert.enviarEmail(error) #saving the last value read at or json if len(myJson) == 0: return last_dicio = myJson[-1] with open("the_last_logid.txt", "w", encoding='utf-8') as f: f.write(str(last_dicio["id_log"]))
def __init__(self): self.clock = 0.0 # Reloj de la simulacion self.number_of_runs = 0 # Cantidad de veces a ejecutar la simulacion self.simulation_time = 0.0 # Tiempo de simulacion por corrida self.max = 0.0 # Valor utilizado como infinito (se cambia a 4 * Tiempo de simulacion) self.x1_probability = 0.0 # Probabilidad de X1 self.x2_probability = 0.0 # Probabilidad de X2 self.x3_probability = 0.0 # Probabilidad de X3 self.distribution_list = {} # Contiene D1, D2, D3, D4, D5 y D6 self.event_list = {} # Contiene la lista de eventos para programar self.message_list = [ ] # Contiene todos los mensajes que se crean en una corrida self.processor_list = [ ] # Contiene todos los procesadores utilizados en la simulacion self.LMC1_list = [ ] # Lista ordenada de mensajes que deben llegar a la computadora 1 self.LMC2_list = [ ] # Lista ordenada de mensajes que deben llegar a la computadora 2 self.LMC3_list = [ ] # Lista ordenada de mensajes que deben llegar a la computadora 3 self.results = Results( ) # Objeto que contiene los resultados de cada corrida self.interface = Interface( ) # Instancia para utilizar la interfaz de consola self.computer_1 = None # Instancia de la Computadora 1 de la Simulación self.computer_2 = None # Instancia de la Computadora 2 de la Simulación self.computer_3 = None # Instancia de la Computadora 3 de la Simulación
def __init__(self, width, height, blocksize, fullscreen=False): Interface.__init__(self, width, height, blocksize) self.flags = pygame.DOUBLEBUF | pygame.HWSURFACE if fullscreen: self.flags |= pygame.FULLSCREEN self.window = pygame.display.set_mode((self.width, self.height), self.flags)
def fetchAndSaveUrl(self, url='', bit=1): ok = True if len(url) == 0: url, ok = QtGui.QInputDialog.getText(self, 'Link', 'Download Link:', QtGui.QLineEdit.Normal, '', QtCore.Qt.FramelessWindowHint) if ok == True: key = self.freeKey() if key == -1: obj = Interface(self.PARTS) key = self.links self.links = self.links + 1 else: obj = self.dLoads[key] obj.PARTS = self.PARTS obj.clear() del self.dLoads[key] thread.start_new_thread(obj.start_Download, (url, self.wMutex, bit)) self.dLoads[key] = obj else: msg = QtGui.QMessageBox(QtGui.QMessageBox.Warning, 'Oops.', "Not a valid Url ", QtGui.QMessageBox.Ok, self, QtCore.Qt.FramelessWindowHint) msg.show()
def removeMatrix(self, arglist): "Arguments: Matrixnumber\nremoves a matrix" try: index=string.atoi(arglist[0]) Interface.removeMatrix(self, index) except ValueError: print arglist[0],"is not a number"
def setPseudoCnt(self,arglist=("1.0")): "Arguments: [pseudocount]\nSet the amount of pseudocounts on matricies. Default 1.0" try: Interface.setPseudoCount(self,float(arglist[0])) except ValueError: print "Invalid pseudocount. Pseudocount not set." return
def startup(self): build.build_database().build_database() self.get_database_status() self.get_list_status() # tables.build_tables().build_tables() # self.update_all_tables() interface.view().start_up()
def addLoadedDevice(self, deviceLoad): if deviceLoad.deviceType == 'router': device = Device('router.jpg', deviceLoad.deviceName, 'router', self) else: device = Device('computer.jpg', deviceLoad.deviceName, 'computer', self) device.move(deviceLoad.position) device.show() device.deviceType = deviceLoad.deviceType device.routageTable = deviceLoad.routageTable device.interfaceList = [] for interfaceLoad in deviceLoad.interfaceList: interface = Interface('point.png', interfaceLoad.interfaceName, self, device) interface.ip = interfaceLoad.ip interface.network = interfaceLoad.network device.interfaceList.append(interface) device.drawInterface() self.deviceList.append(device) try: self.detailsWindow.updateDetails() except Exception as e: pass
class Program: """ General program template - init function for program component initialization - main loop * check events -> handle (event) * update """ def __init__(self): """ init function """ self.interface = Interface() self.engine = Engine() self.run() def run(self): """ main loop """ while True: self.check_events() self.update() def check_events(self): """ pygame event handling (edit this for more events) """ for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: mousex, mousey = event.pos response = self.interface.click(mousex,mousey) self.handle(response) def handle(self,response): """ handle responses to events """ self.engine.send(response) def update(self): """ update state of program components """ self.engine.update() self.interface.update(self.engine.get_updates())
def run(self): zip(self.words, self.weights, self.sentiments) self.interface = Interface(self.words, self.weights, self.sentiments) self.query = self.interface.get_query(self.words) self.interface.search(self.query, self.args) self.interface.score() self.interface.db.close() time.sleep(1)
def addSequence(self, arglist): "Arguments: filelist\nreads sequences from files" for filestring in arglist: filenames=glob(filestring) if filenames: Interface.addSequence(self, filenames) else: raise CommandError("file not found:"+filestring)
def main(): app = wx.App() ui = Interface() ui.initialize() app.MainLoop()
def threadJob(con): myInterface = Interface() recebe = con.recv(1024) stringincomleta = recebe.decode('latin_1') print("sugestão solicitada:" + stringincomleta) resposta = myInterface.retorne_sugestoes(stringincomleta) print("orignal do wesley:" + str(resposta)) respostaFinal = str(resposta) con.send((respostaFinal + "\n").encode())
def threadJob(con): myInterface = Interface() recebe = con.recv(1024) entradas_da_url = recebe.decode() dicio_de_entradas = parsear(entradas_da_url) lista_de_id = myInterface.devolveNprodutosRecomendados( dicio_de_entradas[0], dicio_de_entradas[1]) #idusuario idproduto string_de_ids = str(lista_de_id) con.send((string_de_ids + "\n").encode())
def align(self, arglist): """Arguments: [filename[,num_of_align,[lambda[,xi[,mu[,nu,[,nuc_per_rotation, [Seq1, Seq2]]]]]]]] aligns the computed BS or optional the BS from a gff file filename specifies a file in gff format is you want to be aligned num_of_align specifies how many alignments you want. (Default 3) lambda Bonus factor for hit (Default 2) xi Penalty factor for rotation (Default 1.0) mu Penalty factor for average distance between sites (Default 0.5) nu Penalty factor for distance difference between sites (Default 1.0) nuc_per_rotation specifies how many nucletides there are per rotation. (Default 10.4) Seq1,Seq2 Sequences to be aligned. If you want to skip a argument just write '.' for it. If you use '.' as filename the local data are aligned.""" try: [filename, num_of_align, Lambda, xi, mu, nu, nuc_per_rotation,Seq1,Seq2]=(arglist + ['.']*(9-len(arglist)))[:9] if num_of_align=='.': num_of_align=3 if Lambda=='.': Lambda=2.0 if xi=='.': xi=1.0 if mu=='.': mu=0.5 if nu=='.': nu=1.0 if nuc_per_rotation=='.': nuc_per_rotation=10.4 if Seq1=='.': Seq1=None if Seq2=='.': Seq2=None try: if not Interface.align(self, filename, int(num_of_align), float(Lambda), float(xi), float(mu), float(nu), float(nuc_per_rotation),Seq1,Seq2): print "No alignment for a reason or an other" except AttributeError,val: if len(val.args)==1 or (len(val.args)>1 and len(val.args[1])<2): print val.args[0] else: msg,seqs=val # This function is expected to be defined in subclass firstSeq,secondSeq=self.selectTwoSequences(msg,seqs) if not Interface.align(self, filename, int(num_of_align), float(Lambda), float(xi), float(mu), float(nu), float(nuc_per_rotation), firstSeq,secondSeq): print "No alignment for a reson or an another" except ValueError,e: print "Error: unallowed arguments passed to 'align'",e
def threadJob(con): myInterface = Interface() recebe = con.recv(1024) numero_de_resultados = recebe.decode() print("numero de resultados:" + numero_de_resultados) lista_de_id = myInterface.devolveRecomendacaoPaginaInicial( int(numero_de_resultados)) print("orignal do wesley:" + str(lista_de_id)) string_de_ids = str(lista_de_id) print("respota:" + string_de_ids) con.send((string_de_ids + "\n").encode())
def __init__(self): self._config = Configuration() self._config.size_puzzle = 7 # Configuration to show a correctly tablet self._interface = Interface() self._state = State() self._IA = IA() #self._interface.printJungle(self._state.matrix) print self._state.statusHash()
def getTFBSpvalue(self, arglist): """Arguments: [pvalue] computes the scores of all matrices and all sequences. Report scores better than given p-value. The default value for pvalue is 1e-6""" cutoff=1e-6 try: if(len(arglist)>0): cutoff= string.atof(arglist[0]) Interface.getTFBSpvalue(self, cutoff) except ValueError: print "getTFBSpvalue requires an numeric argument!"
def getTFBSabsolute(self, arglist): """Arguments: [cutoff] computes the scores of all matrices and all sequences which are better than cutoff. The default value for cutoff is 9.0""" cutoff=9.0 try: if(len(arglist)>0): cutoff= string.atof(arglist[0]) Interface.getTFBSAbsolute(self, cutoff) except ValueError: print "getTFBSabsolute requires an numeric argument!"
def __make_interface_files(command_line, codegen_service): sub_path0 = "src" # For each interface generate service and client .java Interface files. for key in sorted(codegen_service.interfaces): i = codegen_service.interfaces[key] __make_interface_arg_info(i) sub_path1 = __get_interface_subdirectory(i) # If client only don't generate the service files. if not command_line.client_only: temp = Interface() temp.interface = i service_path = os.path.join("Service", sub_path0, sub_path1) filename = "{0}.java".format(i.interface_name) full_filename = os.path.join(service_path, filename) __make_target_file(temp, full_filename, command_line, codegen_service) temp = ServiceImplementation() temp.interface = i service_path = os.path.join("Service", sub_path0, sub_path1) filename = "{0}Impl.java".format(i.interface_name) full_filename = os.path.join(service_path, filename) __make_target_file(temp, full_filename, command_line, codegen_service) temp = Interface() temp.interface = i client_path = os.path.join("Client", sub_path0, sub_path1) filename = "{0}.java".format(i.interface_name) full_filename = os.path.join(client_path, filename) __make_target_file(temp, full_filename, command_line, codegen_service) if i.signals: temp = ClientImplementation() temp.interface = i service_path = os.path.join("Client", sub_path0, sub_path1) filename = "{0}Impl.java".format(i.interface_name) full_filename = os.path.join(client_path, filename) __make_target_file(temp, full_filename, command_line, codegen_service) return
def ImportNewInterface(self): dataset = csv.reader(open(self.__file, 'r')) for data in dataset: nip = data[1] host = data[0] h = Host(self.__zapi, host, host_group_id=None) upd = Interface(self.__zapi, h.getHostID()) upd.setInterface(nip)
def getTFBS(self, arglist): """Arguments: [bound] computes the scores of all matrices and all sequences which are better than log2(bound) + maxscore. maxscore is the highest reachable score of the actual matrix with respect to the background The default value for bound is 0.1 i.e. ~3.3 below the maximum score.""" bound=0.1 try: if(len(arglist)>0): bound= string.atof(arglist[0]) Interface.getTFBS(self, bound) except ValueError: print "getTFBS requires an numeric argument!"
def test_dicom_download_dev(): # Test DICOM Download (also in DICOMInterface) repos = read_yaml('repos.yaml') source = Interface.factory('3dlab-dev0+dcm', repos) target = Interface.factory('3dlab-dev1', repos) w = source.find('series', {'SeriesInstanceUID': '1.2.840.113654.2.55.4303894980888172655039251025765147023'}) u = target.retrieve(w[0], source) target.copy(u[0], target, 'nlst_tmp_archive') assert os.path.getsize('nlst_tmp_archive.zip') == 176070 os.remove('nlst_tmp_archive.zip')
def tcia_mirror(): logger = logging.getLogger(tcia_tests.__name__) # Test TCIA Instantiate from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('tcia', repos) target = Interface.factory('xnat-dev', repos) fn = '/Users/derek/Desktop/tcia-all-seriesInstanceUids1438444078500.csv' import csv with open(fn, 'rbU') as csvfile: seriesreader = csv.reader(csvfile) seriesreader.next() i = 0 for row in seriesreader: i = i + 1 if i <= 0: continue if i > 5: break logger.info(', '.join(row)) group = row[0] # subject_id = row[1] series_id = row[9] item = source.series_from_id(series_id) #source.download_data(item) # Change vars for XNAT item['collection'] = group item.subject.project_id = 'tcia' #target.upload_data(item) target.do_put('data/archive/projects', item.subject.project_id, 'subjects', item.subject.subject_id.replace('.', '_'), params={ 'group': item['collection'], 'yob': item.subject['yob'], 'gender': item.subject['gender'] }) pass
def xnat_bulk_edit(): # Example of bulk editing from spreadsheet logger = logging.getLogger(xnat_bulk_edit.__name__) from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('xnat-dev', repos) import csv with open('/Users/derek/Desktop/protect3d.variables.csv', 'rbU') as csvfile: propreader = csv.reader(csvfile) propreader.next() for row in propreader: logger.info(', '.join(row)) subject_id = row[0] new_subject_id = '{num:04d}'.format(num=int(subject_id)) logger.info(new_subject_id) params = {'gender': row[1], #'age': row[2], 'src': row[3], 'label': new_subject_id} source.do_put('data/archive/projects/protect3d/subjects', subject_id, params=params)
def __init__(self, port, baud_rate=19200, parity=serial.PARITY_NONE, stop_bits=serial.STOPBITS_ONE, byte_size=serial.EIGHTBITS, timeout=1, write_timeout=5): # get logger self.log = logging.getLogger('get_UART') # get interface self.interface = Interface() # Get PICom self.pic_com = PICom() self.serial_com = None self.port = port self.baud_rate = baud_rate self.parity = parity self.stop_bits = stop_bits self.byte_size = byte_size self.timeout = timeout self.write_timeout = write_timeout
def __init__(self, tests_directory_path, local_modules_path, modules_path=None): """ You should give to this constructor following arguments: * local_modules_path = Path to puppet modules which will be scanned for test files * tests_directory_path = Output directory where files will be written * modules_path = (Optional) Use this path to modules on test host system instead of local_modules_path. Useful when path to puppet modules differ on machine where tests are made and where they are executed. """ self.interface = Interface(debuglevel=4) self.interface.debug('Starting MakeTests', 1) if not os.path.isdir(local_modules_path): self.interface.error('No such dir: ' + local_modules_path, 1) if not os.path.isdir(tests_directory_path): self.interface.error('No such dir: ' + tests_directory_path, 1) self.__local_modules_path = local_modules_path self.__modules_path = local_modules_path if modules_path: self.__modules_path = modules_path self.__tests_directory_path = tests_directory_path self.__default_template_file = 'puppet_module_test.py' self.__test_file_name_prefix = 'TestPuppetModule' self.__modules = [] self.__module_templates = {} self.__make_tests_dir = os.path.dirname(os.path.abspath(__file__)) self.setTemplatesDir('templates') self.setInternalModulesPath('/etc/puppet/modules') self.setInternalManifestsPath('/etc/puppet/manifests') self.findModules()
def generate_RPC_functions(className): interface_obj = Interface() members_list = inspect.getmembers(interface_obj, predicate=inspect.ismethod) for i in range(len(members_list)): func_name = members_list[i][0] func_parameters = inspect.getargspec(members_list[i][1]).args func_parameters = func_parameters[1:len(func_parameters)] def innerFunc(self, *param_list): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: s.connect((ip, port)) bundle_data = {} stack = traceback.extract_stack() filename, codeline, funName, text = stack[-2] func_name = text.split('(')[0].split('.')[1] bundle_data["function_name"] = func_name bundle_data["function_params"] = list(param_list) bytes_data = pickle.dumps(bundle_data) s.sendall(bytes_data) data_rcv = s.recv(1024*1024) loaded_data = pickle.loads(data_rcv) s.close() return loaded_data["response"] except: return "Error in Connection with the server!" innerFunc.__doc__ = "docstring for innerfunctions" innerFunc.__name__ = func_name setattr(className, innerFunc.__name__, innerFunc) func_parameters.clear()
def test_montage_adv(): logger = logging.getLogger(test_montage_adv.__name__) from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('montage', repos) mrn = '000019477504' q = '16397558' r = source.do_get('api/v1/index/rad/search/rad', params={ 'q': '', 'patient_mrn': mrn }) logger.debug(pprint(r)) exit() r = source.find('study', q, 'rad') # logger.debug(pprint(r)) qq = r.get('objects')[0].get('resource_uri') logger.debug(qq) r = source.do_get(qq) logger.debug(pprint(r))
def init(cls): if cls.is_init: return from Configuration import Configuration iface = Configuration.interface if type(iface) == Interface: iface = iface.name cls.original_mac = Interface.get_mac(iface)
def __init__(self, argv): self.markets = [] marketFileDefined = 0 try: opts, args = getopt.getopt(argv, "hv", ["help", "verbose", "markets=", "testmode="]) except getopt.GetoptError: self.ExitUsage(1, "Bad arguments.") for opt, arg in opts: if opt in ("-h", "--help"): self.ExitUsage() elif opt in ("-v", "--verbose"): Globales.verbose = 1 elif opt == "--markets": marketFileDefined = 1 self.marketFile = arg try: f = open(self.marketFile, "r") for line in f: infos = line.split() if infos[0][0] != '#': self.markets.append(Market(self, infos[0], infos[1], infos[2])) except IOError as e: self.ExitUsage(1, "Bad arguments. Failed to open the markets description file.") elif opt == "--testmode": Globales.testMode = 1 Globales.testModeFile = arg if marketFileDefined == 0: self.ExitUsage(1, "Bad arguments. Please define a markets description file.") self.interface = Interface(self)
def xnat_bulk_edit(): # Example of bulk editing from spreadsheet logger = logging.getLogger(xnat_bulk_edit.__name__) from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('xnat-dev', repos) import csv with open('/Users/derek/Desktop/protect3d.variables.csv', 'rbU') as csvfile: propreader = csv.reader(csvfile) propreader.next() for row in propreader: logger.info(', '.join(row)) subject_id = row[0] new_subject_id = '{num:04d}'.format(num=int(subject_id)) logger.info(new_subject_id) params = { 'gender': row[1], #'age': row[2], 'src': row[3], 'label': new_subject_id } source.do_put('data/archive/projects/protect3d/subjects', subject_id, params=params)
def main(): # Print the usage if not 3 <= len(sys.argv) <= 4: print("Usage: python Main.py <WIDTH> <HEIGHT> [<SEED>]") return # Read the width and height args width = int(sys.argv[1]) height = int(sys.argv[2]) if width <= 0 or height <= 0: print("Error: <WIDTH> and <HEIGHT> must be positive integers") return # Read the seed arg if len(sys.argv) == 4: seed = int(sys.argv[3]) if seed < 0: print("Error: <SEED> must be a non-negative integer") return random.seed(seed) # Generate an empty maze maze = [[{c: False for c in 'nesw'} for j in range(height)] for i in range(width)] interface = Interface(maze) Algo().generate(interface) if interface.success: Printer.print_to_stderr(maze)
def addMatrix(self, arglist): "Arguments: filelist\nreads matrices from files" for filestring in arglist: ## if (filestring.find("/")==-1): ## filestring = "./" + filestring ## # dividing the fiestring in path and filename ## filematch= re.match("(.*)/(.*)", filestring) ## # using the 'find' command to allow things like '*' in filename ## syscomm=('find '+filematch.group(1)+' -maxdepth 1 -xtype f -name "' ## +filematch.group(2)+'"') ## filenames= popen3(syscomm)[0].read().split() filenames=glob(filestring) if filenames: Interface.addMatrix(self, filenames) else: print "file not found:", filestring
def tcia_tests(): # The TCIA interface is very slow, so uncomment to skip this one #raise SkipTest logger = logging.getLogger(tcia_tests.__name__) # Test TCIA Instantiate from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('tcia', repos) # source = TCIAInterface(address='https://services.cancerimagingarchive.net/services/v3/TCIA', # api_key=os.environ['TCIA_API_KEY']) # Apparently API key doesn't work for NLST b/c it is a private collection # series = source.get_series_from_id('1.2.840.113654.2.55.4303894980888172655039251025765147023') # source.download_archive(series, 'nlst_tmp_archive') # Test TCIA Download series = source.get_series_from_id('1.3.6.1.4.1.9328.50.4.15567') source.download_archive(series, 'tcia_tmp_archive') assert os.path.getsize('tcia_tmp_archive.zip') == 266582 os.remove('tcia_tmp_archive.zip') # Test TCIA Copy source.copy(series, source, 'tcia_tmp_archive') assert os.path.getsize('tcia_tmp_archive.zip') == 266582 os.remove('tcia_tmp_archive.zip')
def __init__(self): """ init function """ self.interface = Interface() self.engine = Engine() self.run()
def __init__(self, game_instance): Interface.__init__(self, game_instance) PygameHelper.__init__(self) self.first_selected_square = None self.second_selected_square = None self.current_move = None self.squares = [] self.region_to_coord = {} self.coord_to_region = {} self.sprites = {} self.white_square_color = (247, 196, 145) self.black_square_color = (188, 123, 64) self.game = game_instance self.setup()
def create_interface(self, iface, mac=None, ip_list=None, linked_bridge=None, vlans=None): new_if = Interface(iface, self, mac, ip_list, linked_bridge, vlans) self.interfaces[iface] = new_if self.hyper_visor.create_interface_for_vm(self, new_if) new_if.up() new_if.config_addr() new_if.start_vlans()
def test_orthanc_juniper(): logger = logging.getLogger(orthanc_tests2.__name__) from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('deathstar+lsmaster', repos) source.all_studies()
def setupInterface(self): width = self.getConfigInt(CONFIG_WINDOW_WIDTH) height = self.getConfigInt(CONFIG_WINDOW_HEIGHT) request_size = (width, height) self.interface = Interface(self) self.interface.resize(request_size) if self.getConfigBool(CONFIG_WINDOW_FULLSCREEN): self.interface.modeFullscreen(True) self.interface.show()
def savepwbase(self, arglist): "Arguments: filename\nsaves the pairwise alignments the multiple alignment was based on" filename='' if len(arglist): filename=arglist[0] else: filename=self.getBaseSaveName()+'.pwbase' filename = Interface.savepwbase(self,filename) if filename: print"results saved in", filename
def __init__(self, width, height, pixelsize, fullscreen): Interface.__init__(self, width, height, pixelsize) glutInit() glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(self.width, self.height) self.window = glutCreateWindow("matrix Sim") glutKeyboardFunc(self.keyboardinput) if fullscreen: glutFullScreen() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glViewport(0, 0, self.width, self.height) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, self.width, 0.0, self.height, 0.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glutMainLoopEvent()
def test_montage(): logger = logging.getLogger(test_montage.__name__) # Test DICOM Q/R/DL from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('montage', repos) # Look in collection "rad" for query string "fracture" r = source.find('study', 'fracture', 'rad') assert(r['meta']['total_count'] > 1400000) # Test shared juniper session cookies source2 = Interface.factory('montage', repos) # Look in collection "rad" for query string "fracture" r = source2.find('study', 'fracture', 'rad') assert(r['meta']['total_count'] > 1400000)
def bulk_age_deduction(): logger = logging.getLogger(test_xnat.__name__) from tithonus import read_yaml repos = read_yaml('repos.yaml') source = Interface.factory('xnat-dev', repos) s = source.subject_from_id('UOCA0008A', project_id='ava') r = source.do_get('data/services/dicomdump?src=/archive/projects', s.project_id, 'subjects', s.subject_id, 'experiments', 'UOCA0008A&field=PatientAge', params={'field1': 'PatientAge', 'field': 'StudyDate'})