def _exct_cmd(): t = s.TimeNow() def complete_print(strDesc): print( ' Set %-13s for Engine "%s" Completely...\ ' % ('"%s"' % strDesc, self._host)) time.sleep(0.25) try: # Set Time if self._TN_Conn.exctCMD('rtc set time %d %d %d' % (t.h(), t.mi(), t.s())): complete_print('Time') # Set Date if self._TN_Conn.exctCMD('rtc set date %d %d %d' % (t.y() - 2000, t.mo(), t.d())): complete_print('Date') # Set Day of the Week DoW = t.wd() + 2 if DoW == 8: DoW - 7 if self._TN_Conn.exctCMD('rtc set day %d' % DoW): complete_print('Day_of_Week') except Exception as E: s.ShowErr( self.__class__.__name__, sys._getframe().f_code.co_name, 'rtc Set Faild for Engine "{}" with Error:'.format( self._host), '"{}"'.format(E))
def sphericalReflector() : # source ppos = [0,0,0] pdir = [0,0,1] s0 = Source("light source",Placement(ppos,pdir)) s0.exampleRays(0.04) # spherical reflector ppos = [0,0,0.20] pdir = [0,0,1] pdim = [0.05,0.05,0.01] sr = SphericalSurface("spherical", Volume.circ,pdim,Placement(ppos,pdir),Material(Material.mirror,1.0),-0.10) # plane stop ppos = [0,0,0.1] pdir = [0,0,-1] pdim = [0.05,0.05,0.01] ss = PlaneSurface("stop",Volume.circ,pdim,Placement(ppos,pdir),Material(Material.refract,1.0)) s = System() s.append(s0) s.append(sr) s.append(ss) r = s.propagate() d = Display3D.Display3D(s,r) d.Draw()
def NYS_Regularizer(ls_data, ls_lb_tr, int_Kg, int_sampling, int_Knn, str_file, ls_lb_tl): ls_lb_nu = src.copy_list(ls_lb_tr) ls_lb_tlnu = src.copy_list(ls_lb_tl) flo_timestart = time() mtx_lb_pr = src.NystromIsomapKNN(ls_data, ls_lb_nu, int_Kg, int_sampling, int_Knn) flo_timefinal = time() - flo_timestart # Getting Results ls_lb_pr = src.convert_to_list(mtx_lb_pr) ls_lb_prflo = src.float_list_normalization(ls_lb_pr) ls_temp_lb = ls_lb_prflo np.savetxt("Pr" + str_file, (tuple(ls_temp_lb) + tuple(ls_lb_tlnu))) ls_lb_alpha = src.generalizeAlphaCut(np.array(ls_lb_pr), 0.5, 0, 1) ls_lb_alphaint = src.int_list_normalization(ls_lb_alpha) flo_acc = src.accuracyTest(ls_lb_alphaint, ls_lb_tlnu) flo_TP, flo_TN, flo_FP, flo_FN = src.confussionMatrix( ls_lb_alphaint, ls_lb_tlnu) np.savetxt("Rs" + str_file, (flo_TP, flo_TN, flo_FP, flo_FN, flo_acc, flo_timefinal)) print str_file + " done!" return ls_lb_pr
def __init__(self): self.currentTime = 0 self.eventList = [] self.id = 'Scheduler' # Crear objectos del CASO 1: Tres colas intercambiables, cada una asignada a un Server self.source1 = Source(self, 'Supermercado1') self.Queue1 = Queue(self, 'Cola1') self.Queue2 = Queue(self, 'Cola2') self.Queue3 = Queue(self, 'Cola3') self.source1.crearConnexio(self.Queue1) self.source1.crearConnexio(self.Queue2) self.source1.crearConnexio(self.Queue3) self.Queue1.conectarAmbCua(self.Queue2) self.Queue1.conectarAmbCua(self.Queue3) self.Queue2.conectarAmbCua(self.Queue1) self.Queue2.conectarAmbCua(self.Queue3) self.Queue3.conectarAmbCua(self.Queue1) self.Queue3.conectarAmbCua(self.Queue2) self.Caja1 = Server(self, 'Caja1') self.Caja2 = Server(self, 'Caja2') self.Caja3 = Server(self, 'Caja3') self.Caja1.afegirInput(self.Queue1) self.Caja2.afegirInput(self.Queue2) self.Caja3.afegirInput(self.Queue3) # Crear objectos del CASO 2: Una única cola, asignada a 3 Servers distintos self.source2 = Source(self, 'Supermercado2') self.Queue4 = Queue(self, 'ColaUnica') self.Caja4 = Server(self, 'Caja4') self.Caja5 = Server(self, 'Caja5') self.Caja6 = Server(self, 'Caja6') self.source2.crearConnexio(self.Queue4) self.Caja4.afegirInput(self.Queue4) self.Caja5.afegirInput(self.Queue4) self.Caja6.afegirInput(self.Queue4) self.simulationStart = Event(self, 'SIMULATION_START', 0, None) self.eventList.append(self.simulationStart) self.latestPercentage = -100 self.percentageStep = 0.5
def __init__(self): # Recollim paràmetres de configuració # Nombre d'arribades print("") print("Volume of arrivals (1, 2 o 3):") print("1. Low") print("2. Medium") print("3. High") numarribades = int(input()) # Tipus de clients print("") print( "Specify the probability of customers with few products with an integer from 1 to 100:" ) probcapdubte = int(input()) print( "Specify the probability of customers with lots of products with an integer from 1 to 100:" ) probmoltsdubtes = int(input()) probpocsdubtes = 100 - (probmoltsdubtes + probcapdubte) # Temps de simulació print("Simulation time in minutes:") self.simulationtime = int(input()) # Imprimim els paràmetres escollits print("") print("SELECTED PARAMETERS:") print("Volume of arrivals: Level" + str(numarribades)) print("Customers with few products: " + str(probcapdubte) + "%") print("Customers with some products: " + str(probpocsdubtes) + "%") print("Customers with lots of products: " + str(probmoltsdubtes) + "%") print("Simulation time: " + str(self.simulationtime) + " minutes") # Creació dels objectes que composen el meu model self.source = Source(self, numarribades, probcapdubte, probpocsdubtes, probmoltsdubtes) self.server1 = Server(self) self.server2 = Server(self) self.server3 = Server(self) self.server4 = Server(self) self.source.creaConnexions(self.server1, self.server2, self.server3, self.server4) self.queue = Queue() # Estadístic self.clientsperduts = 0 self.staytime = 0 # Iniciem simulació simstart = Event('SIMULATION_START', 0, None) self.eventList.append(simstart)
def GetSources(self): """Retrieve and return the Source objects containted in urpmi.cfg.""" def get_source_name(line): """Extract the source name from the line of the file.""" prev_chr = line[0] name = line[0] for c in line[1:-1]: if c == ' ': if prev_chr == '\\': name += ' ' else: break elif c != '\\': name += c prev_chr = c return name file = open('/etc/urpmi/urpmi.cfg') sources = [] word = '' flag0 = False flag1 = False name_flag = False while 1: c = file.read(1) if c == '': break elif c == '{': if flag0 == False: flag0 = True else: name_flag = False name = get_source_name(word) source = Source(name) source.hdlist = czfind(commands.getoutput('find /var/lib/urpmi/ | grep cz | grep ' + name)) print 'HL:', source.hdlist if source.hdlist != '': sources.append(source) word = '' elif c == '}': if flag1 == False: flag1 = True name_flag = True else: name_flag = True elif name_flag == True and c not in ['\\', '\n']: word += c return sources
def main(): geoMan = Geometry.GeometryManager() partMan = ParticleManager() partMan.addGeometry(geoMan) a = Source.SourceManager() b = Source.Source() b.setLocation() b.setEnergy() b.setDirection() b.setParticleType() b.setPopulation(100) a.addSource(b) partMan.addParticles(source=a) print("length of list of all particles :", len(partMan.allParticles)) print(type(partMan.allParticles[0])) print("Successfully completed \a")
def update_error(self, vec_x): int_t1 = len(self.__vector) int_t2 = len(vec_x) if (int_t1 == int_t2): self.__error = self.__error + src.distance(self.__vector, vec_x) else: print "ERROR (Neuron.update_error): input vector of wrong size -> ", int_t2
def __init__(self, dataSet): self.dataSet = dataSet self.cardType = CardType.createType(self.generateList('type'), self.model) self.cardTypes = CardTypes.createTypes(self.generateList('types'), self.model) self.cmc = Cmc.createCmc(self.generateList('cmc'), self.model) self.colorIdentity = ColorIdentity.createColorIdentity(self.generateList('colorIdentity'), self.model) self.colors = Colors.createColors(self.generateList('colors'), self.model) self.hand = Hand.createHand(self.generateList('hand'), self.model) self.imageName = ImageName.createImageName(self.generateList('imageName'), self.model) self.layouts = Layouts.createLayouts(self.generateList('layout'), self.model) self.legalities = Legalities.createLegalities(self.generateList('legalities'), self.model) self.life = Life.createLife(self.generateList('life'), self.model) self.loyalty = Loyalty.createLoyalty(self.generateList('loyalty'), self.model) self.manaCost = ManaCost.createManaCost(self.generateList('manaCost'), self.model) self.name = Name.createName(self.generateList('name'), self.model) self.names = Names.createNames(self.generateList('names'), self.model) self.power = Power.createPower(self.generateList('power'), self.model) self.printings = Printings.createPrintings(self.generateList('printings'), self.model) self.rulings = Rulings.createRulings(self.generateList('rulings'), self.model) self.source = Source.createSource(self.generateList('source'), self.model) self.starter = Starter.createStarter(self.generateList('starter'), self.model) self.cardSubTypes = CardSubTypes.createSubTypes(self.generateList('subtypes'), self.model) self.cardSuperTypes = CardSuperTypes.createSuperTypes(self.generateList('supertypes'), self.model) self.text = Text.createText(self.generateList('text'), self.model) self.toughness = Toughness.createToughness(self.generateList('toughness'), self.model)
def GetData(mt_data, mt_label, int_tam, int_per): int_dt_tr = int(int_tam * int_per / 100) int_dt_cl = int(int_dt_tr / 2) int_dt_tl = int(int_tam / 2) ls_data, ls_lb_tl, ls_lb_tr = src.filterDataRandomly( mt_data, mt_label, 1, int_dt_cl, int_dt_cl, int_dt_tl, int_dt_tl) return (ls_data, ls_lb_tl, ls_lb_tr)
def _init_csv_file(self): """ Parser file source with the list of geocatalogs Test: >>> globalData = GlobalData.get_instance() >>> globalData.list_geocatalog_sources != [] True """ self.list_geocatalog_sources = list() try: (options, args) = self.parser.parse_args() source_file = open(options.sources) except: Log.get_instance().insert_error('GlobalData', 'Unable to open : %s' % options.sources) raise NameError('Error CSV file Name : %s' % options.sources) for source in source_file.readlines(): if source[0] != '#': num = source.split(',')[0] name = source.split(',')[1] begin_record = int(source.split(',')[2]) end_record = int(source.split(',')[3]) MAXR = int(source.split(',')[4]) url = source.split(',')[5] url_csw = source.split(',')[6].strip('\n') self.list_geocatalog_sources.append(Source(num, name, begin_record, end_record, MAXR, url, url_csw))
def __init__(self, width = 1280, height = 720): config = Settings.Config() if config.DisplayFullscreen is False: os.environ['SDL_VIDEO_CENTERED'] = '1' self.screen = pygame.display.set_mode((width, height)) else: self.screen = pygame.display.set_mode((width, height), pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF) pygame.init() self.Background = TileImage("img/bg-dark.gif", self.screen) self.screen.blit(self.Background, (0,0)) pygame.mouse.set_visible(False) pygame.display.flip() checks = UpdateChecks() checks.AddTimer('page_delay', config.PageInterval) checks.AddTimer('source_update', config.UpdateInterval) checks.Update('page_delay') checks.AddState('dirty_source', True) checks.AddState('dirty_screen', True) checks.AddState('dirty_page', False) checks.AddState('error', False) self.DrawArrivals = True if config.DisplayScreen == 'departures': self.DrawArrivals = False self.CurrentPage = 1 self.RowsPerPage = 10 # 12 rows minus the header self.FirstRow = 0 # First row to draw # FIXME: proper error handling and checking needed here. if config.SourceURI[-4:] == '.xml': self.Source = ds.JSONSource() Debug('XML source found.') else: self.Source = ds.XMLSource() Debug('JSON source found.') self.CachedList = Data.BusList() self.List = Data.BusList() self.ArrivalHeader = HeaderRow(Data.BusArrival("Company", "City", "Time", "Status")) self.DepartureHeader = HeaderRow(Data.BusDeparture("Company", "City", "Time", "Status", "Gate", "Bus #")) self.ErrorScreen = None
def _isPort(s): if type(s) == int: return True if type(s) == str: if s.isdigit(): if type(eval(s)) == int: return True return False
def GetDataVar(mt_data, mt_label, int_tam_pos, int_tam_neg, int_per): int_dt_tr = int(int_tam * int_per / 100) int_dt_cl_pos = int(int_tam_pos * int_per / 100) int_dt_cl_neg = int(int_tam_neg * int_per / 100) ls_data, ls_lb_tl, ls_lb_tr = src.filterDataRandomly( mt_data, mt_label, 1, int_dt_cl_pos, int_dt_cl_neg, int_tam_pos, int_tam_neg) return (ls_data, ls_lb_tl, ls_lb_tr)
def digitalToggle(gv, LnRs485, payload): assert type(payload) == bytearray logger = Ln.SetLogger(package=__package__) # puntamento ai fieldNames _fld = LnRs485._fld # puntamento ai comandi e sottocomandi _mainCmd = gv.iniFile.MAIN_COMMAND _subCmd = gv.iniFile.SUB_COMMAND C.printColored(color=C.yellowH, text='... press ctrl-c to stop the process.', tab=8) # =================================================== # = RS-485 preparazione del comando # =================================================== payload[_fld.SEQNO_H], payload[_fld.SEQNO_L] = LnRs485.getSeqCounter() payload[_fld.RCODE] = 0 # 0 per la TX payload[_fld.DEST_ADDR] = int(gv.args.slave_address) payload[_fld.CMD] = int(_mainCmd.DIGITAL_CMD, 16) # COMMAND payload[_fld.SUB_CMD] = int(_subCmd.TOGGLE_PIN, 16) # SubCOMMAND payload[_fld.PIN_NO] = gv.args.pin_number # pinNO # --------------------------------------------------------------------- # - invio del messaggio al Relay ed attesa dello stesso come echo # - Se non lo riceviamo vuol diche che c'è un problema # --------------------------------------------------------------------- Prj.SendToRelay(LnRs485, payload) # --------------------------------------------------------------------- # - Attesa risposta... # --------------------------------------------------------------------- fDEBUG = False while True: try: raw, payload = LnRs485._rs485Read(timeoutValue=2000, FORMAT=True) # return bytearray if raw.data: if fDEBUG: print(raw.hexm) if payload.data: if fDEBUG: print(payload.hexm) print( payload.dict.printTree( header='ricezione dati dallo slave: {}'.format( payload.data[LnRs485._fld.SRC_ADDR]), whatPrint='KV')) # whatPrint='LTKV' print('\n' * 2) break except (KeyboardInterrupt) as key: print(__name__, "Keybord interrupt has been pressed") LnRs485.Close() sys.exit()
def __init__(self): self.currentTime = 0 self.eventList = [] self.statistics = Statistics() self.source = Source(self) self.cua_unica = MyQueue("cua_unica") self.caixer_cua_unica1 = Server(self, "caixer_cua_unica1") self.caixer_cua_unica2 = Server(self, "caixer_cua_unica2") self.caixer_cua_unica3 = Server(self, "caixer_cua_unica3") self.cua_unica.crearConnexio([ self.caixer_cua_unica1, self.caixer_cua_unica2, self.caixer_cua_unica3 ]) self.caixer_cua_unica1.crearConnexio(self.cua_unica) self.caixer_cua_unica2.crearConnexio(self.cua_unica) self.caixer_cua_unica3.crearConnexio(self.cua_unica) self.cua_caixer4 = MyQueue("cua_caixer4") self.caixer4 = Server(self, "caixer4") self.cua_caixer4.crearConnexio([self.caixer4]) self.caixer4.crearConnexio(self.cua_caixer4) self.cua_caixer5 = MyQueue("cua_caixer5") self.caixer5 = Server(self, "caixer5") self.cua_caixer5.crearConnexio([self.caixer5]) self.caixer5.crearConnexio(self.cua_caixer5) self.cua_caixer6 = MyQueue("cua_caixer6") self.caixer6 = Server(self, "caixer6") self.cua_caixer6.crearConnexio([self.caixer6]) self.caixer6.crearConnexio(self.cua_caixer6) self.source.crearConnexio([ self.cua_unica, self.cua_caixer4, self.cua_caixer5, self.cua_caixer6 ]) self.simulationStart = Event(self, TYPE_EVENT['start'], self.currentTime, None) self.eventList.append(self.simulationStart)
def _conn(): try: ftp.connect(self._host, self._port, self._timeout) self._connected = ftp return True except Exception as E: s.ShowErr(self.__class__.__name__, sys._getframe().f_code.co_name, 'FTP Connect to "{}" Failed with Error:'.format( self._host), '"{}"'.format(E))
def job_update_interval(intInterval): t = s.Timing() db = DB_collHAAP() def do_it(): n = datetime.datetime.now() do_update = db.haap_insert(n, get_HAAP_status_list()) #print('update complately...@ %s' % n) return do_update t.add_interval(do_it, intInterval) t.stt()
def _getporterrshow(self): try: self._SWConn = SSHConn(self._host, self._port, self._username, self._password, self._timeout) self._strAllPortError = self._SWConn.exctCMD('porterrshow') return True except Exception as E: s.ShowErr( self.__class__.__name__, sys._getframe().f_code.co_name, 'Get PortErrorInfo for "{}" Fail with Error:'.format( self._host), '"%s"' % E)
def _login(): try: ftp.login(self._username, self._password) self._logined = ftp return True except Exception as E: # print(E) s.ShowErr(self.__class__.__name__, sys._getframe().f_code.co_name, 'FTP Login to "{}" Failed with Error:'.format( self._host), '"{}"'.format(E))
def main(): # Home Page turtle.clear() sc = Source('Home Page') set_window(title='TURTLE RACE') sc.logo(pos=(0, 0)) sc.bottom_ballon(color='#a7a4da') write_text('Aurthor: Escape', pos=(300, 300), color='white', font=('Times', 12)) write_text('TURTLE RACE', pos=(0, 200), color='white', font=("Times", 30, "bold")) write_text("press spacebar to start game", pos=(0, -300), color='white', font=("Courier", 16, "bold")) turtle.hideturtle() # The game start once press spacebar turtle.onkey(play, "space") turtle.listen() turtle.done() return "EVENTLOOP"
def general_info(): lstDesc = ('EngineIP', 'Uptime', 'AH', 'Firm_Version', 'Status', 'Master', 'Mirror') for strDesc in lstDesc: print(strDesc.center(14), end=''), print() for i in info_lst: for s in i: if s is not None: print(s.center(14), end=''), else: print("None".center(14), end=''), print()
def backup(self, strBaseFolder): s.GotoFolder(strBaseFolder) connFTP = self._FTP_Conn lstCFGFile = ['automap.cfg', 'cm.cfg', 'san.cfg'] for strCFGFile in lstCFGFile: if connFTP.GetFile('bin_conf', '.', strCFGFile, 'backup_{}_{}'.format(self._host, strCFGFile)): print('{} Backup Completely for {}'.format( strCFGFile.ljust(12), self._host)) continue else: print('{} Backup Failed for {}'.format(strCFGFile.ljust(12), self._host)) break time.sleep(0.25)
def _connect(self): try: objSSHClient = paramiko.SSHClient() objSSHClient.set_missing_host_key_policy(paramiko.AutoAddPolicy()) objSSHClient.connect(self._host, port=self._port, username=self._username, password=self._password, timeout=self._timeout) self._client = objSSHClient return True except Exception as E: s.ShowErr(self.__class__.__name__, sys._getframe().f_code.co_name, 'SSH Connect to "{}" Failed with Error:'.format( self._host), '"%s"' % E)
def periodic_check(self, lstCommand, strResultFolder, strResultFile): tn = self._TN_Conn s.GotoFolder(strResultFolder) if tn.exctCMD('\n'): with open(strResultFile, 'w') as f: for strCMD in lstCommand: time.sleep(0.25) strResult = tn.exctCMD(strCMD) if strResult: print(strResult) f.write(strResult) else: strErr = '\n*** Execute Command "{}" Failed\n'.format( strCMD) # print(strErr) f.write(strErr)
def createcreateConvertWidget(self): global obj_analysis self.convertWindow = QtGui.QWidget() self.analysisTab = QtGui.QScrollArea() obj_analysis = Analysis.Analysis(self.clarg1) self.analysisTab.setWidget(obj_analysis) #self.analysisTabLayout = QtGui.QVBoxLayout(self.analysisTab.widget()) self.analysisTab.setWidgetResizable(True) global obj_source self.sourceTab = QtGui.QScrollArea() obj_source = Source.Source(sourcelist, sourcelisttrack, self.clarg1) self.sourceTab.setWidget(obj_source) #self.sourceTabLayout = QtGui.QVBoxLayout(self.sourceTab.widget()) self.sourceTab.setWidgetResizable(True) global obj_model self.modelTab = QtGui.QScrollArea() obj_model = Model.Model(schematicInfo, modelList, self.clarg1) self.modelTab.setWidget(obj_model) #self.modelTabLayout = QtGui.QVBoxLayout(self.modelTab.widget()) self.modelTab.setWidgetResizable(True) global obj_devicemodel self.deviceModelTab = QtGui.QScrollArea() obj_devicemodel = DeviceModel.DeviceModel(schematicInfo, self.clarg1) self.deviceModelTab.setWidget(obj_devicemodel) self.deviceModelTab.setWidgetResizable(True) global obj_subcircuitTab self.subcircuitTab = QtGui.QScrollArea() obj_subcircuitTab = SubcircuitTab.SubcircuitTab( schematicInfo, self.clarg1) self.subcircuitTab.setWidget(obj_subcircuitTab) self.subcircuitTab.setWidgetResizable(True) self.tabWidget = QtGui.QTabWidget() #self.tabWidget.TabShape(QtGui.QTabWidget.Rounded) self.tabWidget.addTab(self.analysisTab, "Analysis") self.tabWidget.addTab(self.sourceTab, "Source Details") self.tabWidget.addTab(self.modelTab, "NgSpice Model") self.tabWidget.addTab(self.deviceModelTab, "Device Modeling") self.tabWidget.addTab(self.subcircuitTab, "Subcircuits") self.mainLayout = QtGui.QVBoxLayout() self.mainLayout.addWidget(self.tabWidget) #self.mainLayout.addStretch(1) self.convertWindow.setLayout(self.mainLayout) self.convertWindow.show() return self.convertWindow
def _connect(self): try: objTelnetConnect = telnetlib.Telnet( self._host, self._port, self._timeout) objTelnetConnect.read_until( self._strLoginPrompt.encode(encoding="utf-8"), timeout=2) objTelnetConnect.write(self._password.encode(encoding="utf-8")) objTelnetConnect.write(b'\r') objTelnetConnect.read_until( self._strMainMenuPrompt.encode(encoding="utf-8"), timeout=2) self._Connection = objTelnetConnect return True except Exception as E: s.ShowErr(self.__class__.__name__, sys._getframe().f_code.co_name, 'Telnet Connect to "{}" Failed with Error:'.format( self._host), '"{}"'.format(E))
def _getfile(): try: ftp = self._Connection # print(ftp.getwelcome()) ftp.cwd(strRemoteFolder) objOpenLocalFile = open('{}/{}'.format( strLocalFolder, strLocalFileName), "wb") if FTPtype == 'bin': ftp.retrbinary('RETR {}'.format(strRemoteFileName), objOpenLocalFile.write) elif FTPtype == 'asc': ftp.retrlines('RETR {}'.format(strRemoteFileName), objOpenLocalFile.write) objOpenLocalFile.close() ftp.cwd('/') return True except Exception as E: s.ShowErr(self.__class__.__name__, sys._getframe().f_code.co_name, 'FTP Download "{}" Failed with Error:'.format( self._host), '"{}"'.format(E))
def _putfile(): try: ftp = self._Connection # print(ftp.getwelcome()) ftp.cwd(strRemoteFolder) objOpenLocalFile = open('{}/{}'.format( strLocalFolder, strLocalFileName), 'rb') if FTPtype == 'bin': ftp.storbinary('STOR {}'.format(strRemoteFileName), objOpenLocalFile, intBufSize) elif FTPtype == 'asc': ftp.storlines('STOR {}'.format( strRemoteFileName), objOpenLocalFile) ftp.set_debuglevel(0) objOpenLocalFile.close() return True except Exception as E: s.ShowErr(self.__class__.__name__, sys._getframe().f_code.co_name, 'FTP Upload "{}" Failed with Error:'.format( self._host), '"{}"'.format(E))
def play(): turtle.onkey(None, 'space') turtle.clear() # Game Page sc = Source('Game Page') set_window(title='TURTLE RACE') sc.bottom_ballon(color='#a7a4da') sc.finish_line() sc.runway() write_text('TURTLE RACE', pos=(0, 200), color='white', font=("Times", 30, "bold")) # Create turtle players and name them the way your like turtle_list = [] color_list = ['Crimson', 'DarkslateBlue', 'SeaGreen', 'orange'] name_list = ['China', 'America', 'Italy', 'Japan'] turtle.tracer(False) for i in range(4): turtle_list.append( set_turtle((-250, 100 - i * 50), color=color_list[i], name=name_list[i])) # MAIN LOOP current_leader = turtle_list[0] info_list = Turtle() turtle.tracer(True) while current_leader.xcor() < 200: new_turtle_list = list(map(TurtleRacer.move, turtle_list)) current_leader = max(new_turtle_list, key=lambda x: x.xcor()) update_game_info(new_turtle_list, info_list) # Output game result write_text("{} won the game!".format(current_leader.name), pos=(0, -250), color='Cornsilk', font=("Times", 24, "bold"))
import numpy as np import pandas as pd import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go import Source import Wave sources_info = Source.parse_source("sources.csv") waves_info = Wave.parse_wave("waves.csv") sources_df = pd.DataFrame(t.__dict__ for t in sources_info) waves_df = pd.DataFrame(t.__dict__ for t in waves_info) def map_source_country(): sources_by_country = pd.DataFrame( {'count': sources_df['country_s'].value_counts()}) map1 = px.choropleth(sources_by_country, locations=sources_by_country.index, locationmode='country names', color_continuous_scale=[[0, 'yellow'], [0.1, 'rgb(255,145,0)'], [0.2, 'red'], [0.3, 'rgb(247,0,255)'], [0.6, 'blue'], [1, 'green']], hover_data=['count'], color='count', title="Number of sources by country", labels={"count": "Sources number"}) map1.update_layout(title={'x': 0.5, 'xanchor': 'center'})
def tickers(self): pairs = FxUtils.split_to_usd_crosses(self.asset) return [Ticker(Source.quandl_code(p), FxUtils.is_inverted(p)) for p in pairs]
def SystemTest() : print "System:SystemTest>" # source ppos = [0,0,0] pdir = [0,0,1] s0 = Source("light source",Placement(ppos,pdir)) s0.exampleRays(0.04) # curved surface ppos = [0,0,0.05] pdir = [0,0,1] pdim = [0.05,0.05,0.01] s1 = SphericalSurface("spherical 1", Volume.circ,pdim,Placement(ppos,pdir),Material(Material.refract,1.4),0.08) # plane surface ppos = [0,0,0.07] pdir = [0,0,1] pdim = [0.05,0.05,0.01] s2 = PlaneSurface("plane 1",Volume.circ,pdim,Placement(ppos,pdir),Material(Material.refract,1.0)) # plane surface ppos = [0,0,0.40] pdir = [0,0,1] pdim = [0.05,0.05,0.01] s3 = PlaneSurface("plane 2",Volume.circ,pdim,Placement(ppos,pdir),Material(Material.refract,1.4)) # curved surface ppos = [0,0,0.42] pdir = [0,0,1] pdim = [0.05,0.05,0.01] s4 = SphericalSurface("spherical 2", Volume.circ,pdim,Placement(ppos,pdir),Material(Material.refract,1.0),-0.08) # plane surface ppos = [0,0,0.50] pdir = pl.array([0,-1,1]) pdir = pdir/pl.linalg.norm(pdir) pdim = [0.05,0.05,0.01] s5 = PlaneSurface("plane 3",Volume.circ,pdim,Placement(ppos,pdir),Material(Material.mirror,1.0)) # plane surface ppos = [0,0.15,0.50] pdir = [0,1,0] pdim = [0.05,0.05,0.01] s6 = PlaneSurface("plane 4",Volume.circ,pdim,Placement(ppos,pdir),Material(Material.refract,1.0)) # system s = System() s.append(s0) s.append(s1) s.append(s2) s.append(s3) s.append(s4) s.append(s5) s.append(s6) return s # ray trace through system # rl = s.propagate() # # while r != None : # rl.append(r) # r1 = s[1].propagate(s[0],r) # print r # print r1[0] # r = s[0].nextRay() # # d = Display3D(s,rl) # d.Draw() return s