def name_del_zip(s): ss = 'something wrong!' try: ss = s.replace('.zip', '') except Exception as ex: C.printEx(ex) return ss
def wait_msg(connexion): """ @do : Attend un message en boucle sur la connexion passe en parametre et l'envoi au gestionnaire de message. Gere aussi l'extinction du serveur si elle est demande ou s'il y a une erreur. @args : connexion -> Connection qu'il faut ecouter @return : None """ socket_is_open = True while socket_is_open: # Attente d'un message dao = Comm.rcv_message(connexion) action = Msg_manager.recv_handler(dao, list_of_characters, list_of_regions) # ACTION : Fermeture de l'application if (action == "exit"): print("Demande d'extinction du server\n", flush=True) socket_is_open = False Comm.close_connexion(connexion) os._exit(1) # ACTION : Plantage de l'application elif (action == "error"): print("Erreur : Fermeture du serveur\n", flush=True) socket_is_open = False Comm.close_connexion(connexion) os._exit(1)
def get_href(s): tit = '' ref = '' siz = 0 try: l = s.find_all(name='td') if (1 > len(l)): return tit, ref, siz for e in l: ll = e.find_all(name='a') if (0 < len(ll)): r1 = re.findall('href=".*"', str(e)) r2 = re.findall('>.*<', str(e)) ref = r1[0][6:-1] tit = r2[0][1:-1] else: ss = C.getText(e) if 'KB' not in ss: continue ss = ss.replace(',', '') ss = ss.replace('KB', '') ss = ss.strip() # RP-180600.zip 2018/05/23 7:57 43,9 KB # so, '43,9 KB' should be '43.9 KB' siz = int(ss) * 102 # siz = int(ss) * 1024 except Exception as ex: C.printEx(ex) return tit, ref, siz
def manualTransmit(): while True: print("Send:") x = raw_input() print("Transmitted: " + x) Comm.fnc_CommTransmit(str(x))
def wdpJurisAdminGETOpenId(request,callBackDict): # 取得获取的值 gettoken = Comm.tryTranslate(request,"token") getuserId = Comm.tryTranslate(request,"userId") if Comm.tryTranslateNull('token',gettoken,callBackDict) == False: return None if Comm.tryTranslateNull('userId',getuserId,callBackDict) == False: return None try: #userList = user.objects.filter(phone=13751042830) userList = wdpvipUser.objects.filter(loginToken = gettoken, id=getuserId) if len(userList) == 0: callBackDict['code'] = -2 callBackDict['msg'] = "用户不存在" return None # 查询出来了用户了 userObj = userList[0] if userObj.role == 0: return userObj callBackDict['code'] = -3 callBackDict['msg'] = "没有权限" return None except BaseException as e: callBackDict['code'] = -1 callBackDict['msg'] = "用户异常" logger = logging.getLogger("django") logger.info(str(e)) return None
def format_idx_file(): try: p = os.path.join(path_rfc, 'rfc-index.txt') f = open(p, 'r') l = f.readlines() f.close() r = [] rr = '' ir = 0 for i in range(len(l)): try: if (0 == ir): rsr = rfc_start(l[i]) if (1 == rsr): rr = l[i].strip() ir = 1 elif (1 == ir): rr = rr + ' ' + l[i].strip() rer = rfc_end(rr) if (1 == rer): ir = 0 rs = rfc_record(rr) r.append(rs) except Exception as ex: C.printEx(ex) continue return r except Exception as ex: C.printEx(ex) return []
def scan_rfc(): try: if not os.path.exists(path_rfc): return if not os.path.isdir(path_rfc): return l = os.listdir(path_rfc) if (1 > len(l)): return d = clean_rfc(l) if (1 > len(d)): return m = format_idx_file() if (1 > len(m)): return s = format_idx_html(m, d) if (1 > len(s)): return except Exception as ex: C.printEx(ex) return try: s = s.encode('utf-8') p = os.path.join(path_root, 'RFC_SPEC.html') f = open(p, mode = 'wb') f.write(s) f.close() except Exception as ex: C.printEx(ex) return return
def html_itut(d): sh = '' try: for e in d: sr = '' for ee in d[e][1]: if (not isinstance(d[e][1][ee], list)): continue s0 = str_tr0.format(href_=d[e][1][ee][0][2], name_=d[e][1][ee][0][0], title_=d[e][1][ee][0][1]) if (1 < len(d[e][1][ee])): for i in range(1, len(d[e][1][ee])): s1 = str_tr1.format(href_=d[e][1][ee][i][2], name_=d[e][1][ee][i][0], title_=d[e][1][ee][i][1]) s0 = s0 + s1 sr = sr + s0 st = str_table.format(series_=e, title_=d[e][0]) sh = sh + st + sr s = str_html.format(content_=sh) except Exception as ex: C.printEx(ex) return try: s = s.encode('utf-8') p = os.path.join(path_root, 'ITUT_SPEC.html') f = open(p, mode='wb') f.write(s) f.close() except Exception as ex: C.printEx(ex) return return
def get_file_name(c, e): l = [] s = '' try: l0 = C.getLabal(c, 'tr') if (1 > len(l0)): return [] for l1 in l0: l2 = C.getLabal(l1, 'td') if (3 != len(l2)): continue l3 = str(l2[2]) if ('In force' not in l3): continue l4 = str(l2[0]) r = re.findall(';parent=[^"]+"', l4) if (1 != len(r)): continue if (e in r[0]): s = r[0][8:-1] n = C.getText(l2[1]) l.append([s, n]) except Exception as ex: C.printEx(ex) return l return l
def check(code): if len(code) < 20: print('不符合698长度', code) return 1 lenth = int(code[2] + code[1], 16) # 长度 if len(code) >= lenth + 2: if code[lenth + 1] == '16': full_message = Comm.strto0x(code[1:lenth - 1]) FCS_calc = str( hex(Comm.pppfcs16(0xffff, full_message, len(full_message)))).zfill(4)[2:] if len(FCS_calc) == 3: FCS_calc = '0' + FCS_calc FCS_calc = FCS_calc[2:] + FCS_calc[0:2] if len(FCS_calc) == 2: FCS_calc = FCS_calc + '00' if FCS_calc[0] == "x": FCS_calc = '0' + FCS_calc[1:] print("FCS_calc: ", FCS_calc) FCS_rec = code[lenth - 1] + code[lenth] print("FCS_rec: ", FCS_rec) if FCS_calc == FCS_rec: print('check granted') return 0 else: print("校验错误") return 1 else: print('lenth check denied') return 1 else: print('698 check denied') return 1
def open_(self): try: file = QFileDialog.getOpenFileName( self, caption='打开文件', directory='C:/Users/Administrator/Desktop/', filter='bin文件 (*.bin)') self.ui.lineEdit.setText(file[0]) with open(file[0], 'rb') as f: message = '' while 1: c = f.read() ssss = str(binascii.b2a_hex(c))[2:-1] message = message + ssss if not c: break x = int(self.ui.comboBox_5.currentText()) old = len(message) // 2 message_ff = (((len(message) // 2 - 1) // x) + 1) * x - old print('message_ff', message_ff) self.message = Comm.makelist(message + ('ff' * message_ff)) self.CRC16 = self.CRC(self.message[4096:])[-4:] self.message = Comm.list2str(self.plus33(self.message)) print('CRC16', self.CRC16) self.ui.tableWidget.setDisabled(0) self.ui.pushButton_2.setDisabled(0) except: print_exc(file=open('bug.txt', 'a+'))
def plus33(message): newstr = '' if message is None: print('plus33 is none') else: if re.findall(',', message): # line message = message.split(',') lenth = len(message) i = 0 while lenth: new_list = [] lenth -= 1 returnvalue = Comm.makelist(message[i]) i += 1 while returnvalue: new_list.append(hex(int(returnvalue.pop(), 16) + 51)[2:]) value_str = Comm.list2str(new_list) newstr = newstr + value_str else: message = Comm.makelist(message) lenth = len(message) new_list = [] while lenth: lenth -= 1 new_list.append(hex(int(message.pop(), 16) + 51)[2:]) newstr = Comm.list2str(new_list) return newstr
def start_updata(self, add, crc): message = '68' + add + '681A00' + '683002' + crc cs = self.CS(Comm.strto0x(Comm.makelist(message))) message = message + cs + '16' print('发送采集器启动升级帧:', Comm.makestr(message)) send = '发送采集器启动升级帧:\n' + Comm.makestr(message) self._signal_text.emit(send) self.sent_time()
def __init__(self, address, port): Debugger.printAction('Initializing Khepera robot API') self.comm = Comm(address, port) software = self.readSoftwareVersion() Debugger.printAction('Khepera software: Bios ' + str(software[0]) + ', Revision ' + str(software[1])) Debugger.printAction('Initializing motors') self.initMotors()
def rfc_start(l): try: r = re.match('\d+', l) if r is None: return 0 return 1 except Exception as ex: C.printEx(ex) return 0
def close(self): try: self.s.close() except (Exception, NameError, AttributeError): pass try: Comm.onDisconnect(True) #MAY CAUSE INFINITE LOOP except (Exception, NameError, AttributeError): pass
def head(self): global SA_num self.ctrlzone = 'c3' if SA_num == 0: self.add = Comm.list2str(SA_num_len) elif SA_num == 1: self.add = '05' + Comm.list2str(Comm.makelist(self.Re_add())[::-1]) print('add', self.add) self.CA = '00' self.totallenth()
def int_html(s, d): try: i = int(s) if i not in d: return '' r = _str_href.format(href_ = d[i], name_ = s) return r except Exception as ex: C.printEx(ex) return ''
def grab_file(e): try: h = url_spec_uri + e + '/e' rt, c, ct = C.getHttp(h) if ('html' not in rt): return [] except Exception as ex: C.printEx(ex) return [] try: l = get_file_name(c, e) if (1 > len(l)): return [] except Exception as ex: C.printEx(ex) return [] r = [] for s, n in l: try: u = get_pdf_url(s) if e not in u: continue except Exception as ex: C.printEx(ex) return [] try: f = get_pdf_file(u, s) if e not in s: continue r.append([s, n, f]) except Exception as ex: C.printEx(ex) continue return r
def grab_meeting(p, t, h, n): try: if not check_meeting_num(t, n): return [] pp = os.path.join(p, t) if not (os.path.exists(pp)): os.mkdir(pp) except Exception as ex: C.printEx(ex) return [] try: rt, c, ct = C.getHttp(h) if ('html' not in rt): return [] except Exception as ex: C.printEx(ex) return [] try: l = parse_url(c, ct) if (1 > len(l)): return [] except Exception as ex: C.printEx(ex) return [] try: for ht, hh, _ in l: if (('Docs' in ht) and ('Docs' in hh)): return grab_meeting_file(pp, hh) except Exception as ex: C.printEx(ex) return []
def get_xls_file(p, h, size): try: if (not os.path.exists(p)): sz = 0 else: sz = os.path.getsize(p) if (size <= sz): return True except Exception as ex: C.printEx(ex) return False try: rt, c, _ = C.getHttp(h) if ('xls' not in rt): return False except Exception as ex: C.printEx(ex) return False try: if (len(c) <= sz): return True f = open(p, 'wb') f.write(c) f.close() C.printInfo('write ' + h) return True except Exception as ex: C.printEx(ex) return False
def get_series(s, p, lm): ls = [] try: rt, c, ct = C.getHttp(s) if ('html' not in rt): return {} except Exception as ex: C.printEx(ex) return [] try: l = parse_url(c, ct) if (1 > len(l)): return [] except Exception as ex: C.printEx(ex) return [] try: for l1, l2, _ in l: if s not in l2: continue sn = get_spec_title(l1, lm) if 1 > len(sn): continue fp = get_spec_file(p, l1, l2) C.printInfo('get ' + l2) if 0 < len(fp): ls.append([l1, sn, fp]) gc.collect() return ls except Exception as ex: C.printEx(ex) return []
def rfc_end(l): try: r0 = re.search('(DOI: \d+.\d+/RFC\d+)', l) r1 = re.search('Not Issued', l) if (r0 is None) and (r1 is None): return 0 else: return 1 except Exception as ex: C.printEx(ex) return 1
def update_contrib_info(l, d): try: for i in range(len(l)): try: s = name_del_zip(l[i][0]) if s in d: l[i][1] = d[s] except Exception as ex: C.printEx(ex) except Exception as ex: C.printEx(ex) return
def main_grab(): try: P.grab3gpp() gc.collect() except Exception as ex: C.printEx(ex) try: I.grabItut() gc.collect() except Exception as ex: C.printEx(ex) return
def Analysis(code): code = Comm.makelist(code) re = check(code) if re == 0: try: ctrlc_1(Comm.dec2bin(int(code[3], 16))) # 控制码 except: return 1 code_remain = code[4:] SA_len_num = SASign(Comm.dec2bin(int(code_remain[0], 16)).zfill(8)) global SA_num_len, LargeOAD, relen, data, data_list, frozenSign, b_w_stat, black, white relen = 0 LargeOAD = '' data = '' data_list = [] frozenSign = 0 SA_num_len = code_remain[0:1 + SA_len_num] print('SA_num_len:', SA_num_len) global black_white_SA_address black_white_SA_address = Comm.list2str(SA_num_len[::-1][0:SA_len_num]) print('black_white_SA_address', black_white_SA_address) if b_w_stat == 1: for add in black: if add == black_white_SA_address: return 1 pass elif b_w_stat == 2: for add in white: if add == black_white_SA_address: return 1 pass CA = code_remain[1 + SA_len_num:][0] HCS = code_remain[1 + SA_len_num:][1] + code_remain[1 + SA_len_num:][2] APDU = code_remain[1 + SA_len_num:][3:-3] Information(APDU[0], APDU[1], APDU[2:]) s = LargeOAD LargeOAD = '' data_list = [] data = '' relen = 0 frozenSign = 0 return s else: print('非698,尝试645') text = Meter645_core.deal_receive(code) if text[0] == 0: print('645解析失败') return 1 global OI OI = text[1:] return text[0]
def grab_series_info(): try: rt, c, ct = C.getHttp(url_spec_ref) if ('html' not in rt): return {} except Exception as ex: C.printEx(ex) return {} try: d = parse_series_info(c) except Exception as ex: C.printEx(ex) return d
def rfc_record(l): try: r = re.findall('\([^\)]+\)', l) if r is None: return '' s = l for e in r: if (('Format' in e) or ('DOI' in e)): s = s.replace(e, '') return s.strip() except Exception as ex: C.printEx(ex) return ''
def parse_series_info(c): r = {} try: l = C.getLabal(c, 'a') if (1 > len(l)): return {} for e in l: s, t = get_ref_info(e) if (1 == len(s)): r[s] = t except Exception as ex: C.printEx(ex) return r
def open__(self, message, x): try: old = len(message) // 2 message_ff = (((len(message) // 2 - 1) // x) + 1) * x - old print('message_ff', message_ff) self.message = Comm.makelist(message + ('ff' * message_ff)) self.CRC16 = self.CRC(self.message[4096:]) self.message = Comm.list2str(self.plus33(self.message)) print('CRC16', self.CRC16) MainWindow.ui.pushButton_2.setDisabled(0) except: print_exc(file=open('bug.txt', 'a+'))
def __init__(self, # uDict, # phiDict, # testSpaceDict, # matType, # dofBoundaryConditionsDict, # dofBoundaryConditionsSetterDict, # coefficients, # elementQuadrature, # elementBoundaryQuadrature, # fluxBoundaryConditionsDict=None, # advectiveFluxBoundaryConditionsSetterDict=None, # diffusiveFluxBoundaryConditionsSetterDictDict=None, # stressTraceBoundaryConditionsSetterDictDict=None, # stabilization=None, # shockCapturing=None, # conservativeFluxDict=None, # numericalFluxType=None, # TimeIntegrationClass=None, # massLumping=False, # reactionLumping=False, options=None, # name='defaultName', # reuse_trial_and_test_quadrature=True, # sd = True, # movingDomain=False comm=None, adh_ns=None, adhInput=None, runname=None, petscMatrix=False):#, #use this approach to make sure mpifinalize has not been called before adh wrappers go out of scope if comm != None: self.comm = comm else: self.comm = Comm.get() #make sure we have adh global variables if adh_ns == None: self.adh_ns = ADH_NumericalSolution(adhInput=adhInput,runname=runname,comm=self.comm,opts=options,petscMatrix=petscMatrix,adh_oneLevelTransport=self) self.owns_adh_ns = True else: self.adh_ns = adh_ns self.owns_adh_ns = False self.coefficients = self.adh_ns.coefficients self.mesh = self.adh_ns.mesh self.nd = self.adh_ns.nd self.nc = self.adh_ns.cadh_transport.nc self.t0 = self.adh_ns.cadh_transport.t0 self.t = self.t0 self.nSpace_global = self.adh_ns.adhMesh.nSpace_global ###finite element solutions self.trialSpaceDict = {}; self.u = {}; #for now need a separate array for plotting vector valued components because of memory layout issues #with adh arrays of x,y,z structs self.u_arrays_for_plotting = {} self.buildFiniteElementFunctions() self.petscMatrix = petscMatrix if petscMatrix: self.cadh_petsc_interface = cadh.cADH_PETSc_Interface(self.adh_ns.cadh_transport) self.cadh_petsc_interface.update()
def calculate(self): import Comm comm = Comm.get() if self.firstCall: self.firstCall = False self.filename = os.path.join(Profiling.logDir,self.filename) self.fineGridModel=self.model.levelModelList[-1] comm.beginSequential() print "writing for dof processsor ",comm.rank() print "opening dof and node files for processsor ",comm.rank() if comm.isMaster(): doffile=open(self.filename+"_dof.txt","w") nodefile=open(self.filename+"_node.txt","w") else: doffile=open(self.filename+"_dof.txt","a") nodefile=open(self.filename+"_node.txt","a") for j in range(self.fineGridModel.nc): print "writing dof for component ",j self.fineGridModel.u[j].dof.tofile(doffile,sep='\n',format='%21.16e') doffile.write('\n') print "writing nodes for processor ",comm.rank() self.fineGridModel.mesh.nodeArray.tofile(nodefile,sep='\n',format='%21.16e') nodefile.write('\n') print "closing dof and node files for processsor ",comm.rank() doffile.close() nodefile.close() comm.endSequential()
def __init__(self, address, port): Debugger.printAction('Initializing Khepera robot API' ) self.comm = Comm(address, port) software = self.readSoftwareVersion() Debugger.printAction('Khepera software: Bios ' + str( software[0]) + ', Revision ' + str( software[1]) ) Debugger.printAction('Initializing motors') self.initMotors()
def __init__(self,filename): import Comm self.comm = Comm.get() AV_base.__init__(self) self.massFile = open(filename+"massLS",'w') self.massErrorFile = open(filename+"massErrorLS",'w') self.fluxFile = open(filename+"flux",'w') self.timeFile = open(filename+"time",'w')
def close(self): try: self.exitflag = True self.s.close() except (Exception, NameError, AttributeError): pass try: pr("Closing server...") self.serv.close() pr("Server closed.") except (Exception, NameError, AttributeError): pass try: Comm.onDisconnect(True) # Was worried about infinite loop here except (Exception, NameError, AttributeError): pass
def run(self): try: #normally we'd maybe make a new thread here self.serv.setblocking(False) while True: try: if self.exitflag: self.serv.close() return c, addr = self.serv.accept() #Throws exception if no client break except Exception as ex: pass time.sleep(0.01) self.setSock( c ) self.s.setblocking(True) #Hmm no difference? pr("Received connection from: " + str(addr)) Comm.srOnConnect() pr("Entering message watch loop") while ( True ) : pr("Server waiting for message...") resp = self.recv_end() #1024 if not resp: break elif resp == "ENDCONNECTION": pr("Closing Client: " + str(self.s)) self.s.close() break else: self.parseMessage(resp) pr("sGotMessage: " + str(resp)) #c.send("Got you: " +resp) except Exception as ex: pr("Serve Problem: " + str(ex)) #self.close() finally: pr("Ended Server.") self.close()
class Khepera: def __init__(self, address, port): Debugger.printAction('Initializing Khepera robot API' ) self.comm = Comm(address, port) software = self.readSoftwareVersion() Debugger.printAction('Khepera software: Bios ' + str( software[0]) + ', Revision ' + str( software[1]) ) Debugger.printAction('Initializing motors') self.initMotors() def setMotorSpeeds(self, left, right): s = self.comm.sendCommand('D,l'+str(left)+',l'+str(right)) return True def getGroundSensors(self): """Returns Ground Ambient sensors value, right then left""" return self.getProximitySensors()[9:11] def getProximitySensors(self): """val sens back left, val sens left 90, val sens left 45, val sens front left, val sens front right, val sens right 45, val sens right 90, val sens back right, val sens back, val sens ground right, val sens ground left, time stamp""" s = self.comm.sendCommand('N') return s.split(',')[1:] def getFrontProximitySensors(self): """First left then right""" return self.getProximitySensors()[3:5] def enableDiode(self, enabled): if enabled == True: v = 1 else: v = 0 self.comm.sendCommand('K,0,'+str(v)) return def initMotors(self): s = self.comm.sendCommand('M') def readSoftwareVersion(self): s = self.comm.sendCommand('B') return s.split(',')[1:]
def __init__(self,ghosted_csr_mat,par_bs,par_n,par_N,par_nghost,subdomain2global,blockVecType="simple",pde=None): self.pde = pde p4pyPETSc.Mat.__init__(self) self.ghosted_csr_mat=ghosted_csr_mat self.blockVecType = blockVecType assert self.blockVecType == "simple", "petsc4py wrappers require self.blockVecType=simple" self.create(p4pyPETSc.COMM_WORLD) blockSize = max(1,par_bs) if blockSize >= 1 and blockVecType != "simple": ## \todo fix block aij in ParMat_petsc4py self.setType('baij') self.setSizes([[blockSize*par_n,blockSize*par_N],[blockSize*par_n,blockSize*par_N]],bsize=blockSize) self.setBlockSize(blockSize) self.subdomain2global = subdomain2global #no need to include extra block dofs? else: self.setType('aij') self.setSizes([[par_n*blockSize,par_N*blockSize],[par_n*blockSize,par_N*blockSize]],bsize=1) if blockSize > 1: #have to build in block dofs subdomain2globalTotal = numpy.zeros((blockSize*subdomain2global.shape[0],),'i') for j in range(blockSize): subdomain2globalTotal[j::blockSize]=subdomain2global*blockSize+j self.subdomain2global=subdomain2globalTotal else: self.subdomain2global=subdomain2global import Comm comm = Comm.get() logEvent("ParMat_petsc4py comm.rank= %s blockSize = %s par_n= %s par_N=%s par_nghost=%s par_jacobian.getSizes()= %s " % (comm.rank(),blockSize,par_n,par_N,par_nghost,self.getSizes())) self.csr_rep = ghosted_csr_mat.getCSRrepresentation() blockOwned = blockSize*par_n self.csr_rep_owned = ghosted_csr_mat.getSubMatCSRrepresentation(0,blockOwned) self.petsc_l2g = p4pyPETSc.LGMap() self.petsc_l2g.create(self.subdomain2global) self.colind_global = self.petsc_l2g.apply(self.csr_rep_owned[1]) #prealloc needs global indices self.setPreallocationCSR([self.csr_rep_owned[0],self.colind_global,self.csr_rep_owned[2]]) self.setUp() self.setLGMap(self.petsc_l2g) self.setFromOptions()
def __init__(self,filename): import Comm self.comm = Comm.get() self.filename=filename AV_base.__init__(self)
Tools for n-dimensional linear algebra Vectors are just numpy arrays, as are dense matrices. Sparse matrices are CSR matrices. Parallel vector and matrix are built on top of those representations using PETSc. \todo LinearAlgebraTools: make better use of numpy.linalg and petsc4py to provide the needed functionality and add test suite """ import numpy from superluWrappers import * import flcbdfWrappers from Profiling import logEvent #PETSc import, forces comm init if not already done from petsc4py import PETSc as p4pyPETSc import Comm Comm.set_isInitialized() #end PETSc import class ParVec: """ A parallel vector built on top of daetk's wrappers for petsc """ def __init__(self,array,blockSize,n,N,nghosts=None,subdomain2global=None,blockVecType="simple"):#"block" import flcbdfWrappers self.dim_proc=n*blockSize if nghosts==None: if blockVecType=="simple": self.cparVec=flcbdfWrappers.ParVec(blockSize,n,N,-1,None,array,0) else: self.cparVec=flcbdfWrappers.ParVec(blockSize,n,N,-1,None,array,1) else:
# import pstats usage = "usage: %prog [options] pFile.py [nFile.py]" parser = optparse.OptionParser(usage=usage) parser.add_option("-P", "--petsc-options", help="Options for PETSc", action="store", type="string", dest="petscOptions", default=None) (opts,args) = parser.parse_args() if opts.petscOptions != None: sys.argv = sys.argv[:-1]+opts.petscOptions.split() print sys.argv Comm.argv = sys.argv comm = Comm.init() #cmesh = cmeshTools.CMesh() # multilevelMesh = MeshTools.MultilevelEdgeMesh(3,1,1, # 1.0,1.0,1.0, # 5) # mesh = multilevelMesh.meshList[-1] # print 'done' # #mesh.buildFromC(cmesh) # print ("nElements_global, ",mesh.nElements_global,'\n', # "nNodes_global, ",mesh.nNodes_global,'\n', # "nNodes_element, ",mesh.nNodes_element,'\n', # "nNodes_elementBoundary, ",mesh.nNodes_elementBoundary,'\n', # "nElementBoundaries_element, ",mesh.nElementBoundaries_element,'\n', # "nElementBoundaries_global, ",mesh.nElementBoundaries_global,'\n', # "nInteriorElementBoundaries_global, ",mesh.nInteriorElementBoundaries_global,'\n',
# Tools import jinja2 import os import Comm JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + "/templates/"), extensions=['jinja2.ext.autoescape']) def render(self, template_values, template_url): template = JINJA_ENVIRONMENT.get_template(template_url) self.response.write(template.render(template_values)) errorTemplate = "error.html" def renderError(self, code, message): template = JINJA_ENVIRONMENT.get_template(errorTemplate) self.response.write(template.render({'code': code, 'message': message})) stream_manager = Comm.streamer()
def __init__(self,so=None,pList=None,nList=None,sList=None,opts=None,simFlagsList=None,adhInput=None,runname=None,comm=None,petscMatrix=False,adh_oneLevelTransport=None): #set the adh input filename and runname if adhInput != None: self.adhInput = adhInput elif so != None: self.adhInput = so.name elif pList != None: self.adhInput = pList[0].name if runname == None: runname = "default_runname" #get a comm reference to make sure mpifinalize has not been called before adh wrappers go out of scope if comm != None: self.comm = comm else: self.comm = Comm.get() #allocate the C extensions including the cADH global variables self.cadh_ns = cadh.cADH_NumericalSolution(self.adhInput,runname,comm) #construct archiver if so == None: self.so = default_so else: self.so = so #build a PyADH representation of the cADH mesh self.adhMesh = cadh.cADH_Mesh() #self.nd = self.adhMesh.nSpace_global #self.mesh = self.adhMesh.generateMeshToolsMesh() #todo control partitionMesh so that it matches adh partition #self.mesh.partitionMesh(nLayersOfOverlap=1,parallelPartitioningType=MeshTools.MeshParallelPartitioningTypes.node) self.mesh = None self.buildMesh(self.adhMesh) #build one level transport objects some of this below could be #rearranged and some of the stuff that currently happens in #ADH_OneLevelTransport should probably happen here and have #the result passed in. I'm not going to mess with it right now self.cadh_transport = cadh.cADH_OneLevelTransport(self.cadh_ns) #Archiver self.ar = {0:Archiver.XdmfArchive(opts.dataDir, adhInput, useTextArchive=opts.useTextArchive, gatherAtClose=opts.gatherArchive, hotStart=opts.hotStart)} self.archiveFlag= default_so.archiveFlag self.p = default_p vectorComponents_adh = self.cadh_transport.getVectorSolutionComponentIds() vectorComponents = None if len(vectorComponents_adh) > 0: vectorComponents = vectorComponents_adh self.p.coefficients = ADH_TransportCoefficients(self.cadh_transport.nc,['adh_u%s' % i for i in range(self.cadh_transport.nc)],vectorComponents=vectorComponents) self.coefficients = self.p.coefficients if adh_oneLevelTransport == None: self.adh_transport = ADH_OneLevelTransport(adh_ns = self,petscMatrix=petscMatrix) self.owns_adh_transport = True #adh_transport ctor should be completed self.u = self.adh_transport.u self.t = self.adh_transport.t else: self.adh_transport = adh_oneLevelTransport self.owns_adh_transport = False #may not be through with adh_transport's ctor self.u = None self.t = None self.nc = self.cadh_transport.nc#adh_transport grabs this from adh_ns.cadh_transport self.adh_transport.nc self.mlvt = ADH_MultilevelTransport(self.adh_transport) self.viewer = Viewers.V_base(p=self.p)
def __createWidget(self): self.inComm = Comm("COM4",57600) self.outComm = Comm("COM5",57600) self.inComm.start() self.outComm.start() self.conv = Convert(23,1.21,0)
class WinApp(Tk): def __init__(self): Tk.__init__(self) self.bind('<Destroy>',self.__onDestory) self.startBtn = Button(self,text = "START",command = self.__startFn) self.startBtn.pack() self.stopBtn = Button(self,text = "STOP",command = self.__stopFn) self.stopBtn.pack() self.__createWidget() self.t = threading.Thread(target = self.__running) self.__stop = False self.__terminate = False self.t.start() def __onDestory(self,evnet): self.inComm.terminate() self.outComm.terminate() self.__terminate = True def __createWidget(self): self.inComm = Comm("COM4",57600) self.outComm = Comm("COM5",57600) self.inComm.start() self.outComm.start() self.conv = Convert(23,1.21,0) def __startFn(self): ret,msg = self.inComm.open() ret,msg = self.outComm.open() self.__stop = False def __stopFn(self): self.__stop = True time.sleep(0.5) self.inComm.close() self.outComm.close() def __running(self): while not self.__terminate: if self.__stop: continue ret,data = self.inComm.recv(3) if not ret: continue ret,data = self.conv.conv(data) if not ret: continue self.outComm.send((str(data)+'\n').encode('utf8'))