def main(): factory = Factory.get_instance() car_wash_repo = factory.create_car_wash_repo("json", "car_wash.json") car_repo = factory.create_car_repo("json", "car_wash.json") service = Service(car_repo, car_wash_repo) console = Console(service) console.run()
async def getRepresentations(self, dashmpd): if not dashmpd: return None try: xml_data = await self.session.get(dashmpd) j = xmltodict.parse(xml_data) adaptationSet = j['MPD']['Period']['AdaptationSet'] formats = [] for adaptation in adaptationSet: if not '@mimeType' in adaptation: continue mimeType = adaptation['@mimeType'] if 'Representation' in adaptation: representation = adaptation['Representation'] for rep in representation: fmt = {'mimeType': mimeType} if '@width' in rep: fmt['width'] = int(rep['@width']) if '@height' in rep: fmt['height'] = int(rep['@height']) if '@bandwidth' in rep: fmt['bitrate'] = int(rep['@bandwidth']) if 'BaseURL' in rep: fmt['url'] = rep['BaseURL'] formats.append(fmt) return formats except Exception as err: Console.print_red(err) return None
def markErred(self, v): try: if self.errfile: with open(self.errfile, 'a') as file: file.write(v + '\n') except Exception as err: Console.print_red(err)
def loadConfig(self): try: if os.path.isfile(self.configFile): with open(self.configFile, 'r', encoding='utf-8') as f: config = json.loads(f.read()) if not 'username' in config: config['username'] = None if not 'password' in config: config['password'] = None if not 'maxTaskNum' in config: config['maxTaskNum'] = None if not 'maxTaskCounter' in config: config['maxTaskCounter'] = None if not 'workpath' in config: config['workpath'] = './' if not 'login' in config: config['login'] = None if not 'proxy' in config: config['proxy'] = None if not 'donelist' in config: config['donelist'] = None if not 'errlist' in config: config['errlist'] = None if not 'stopfile' in config: config['stopfile'] = None if not 'logsfile' in config: config['logsfile'] = None self.config = config except Exception as err: Console.print_red(r'load config[%s] fail, err:%s' % (self.configFile, str(err)))
def isExist(self, v): try: if not os.path.isfile(self.donefile): return False with open(self.donefile, 'r') as file: return (v + '\n') in file.readlines() except Exception as err: Console.print_red(err) return False
def checkDownloadState(self, v): if self.taskCounter >= self.maxTaskCounter: Console.print_purple(r'maxTaskCounter[%d] reached! v=%s' % (self.maxTaskCounter, v)) return False if not self.canDownload(v): #Console.print_yellow('exist! v=%s'%(v), False, 1, ", " + v) return False if self.isStop(): Console.print_red('global stop!', False, 2, "stop!") return False return True
def __init__( self ): self.console = Console( parent=Tkinter.Tk(), app_instance=self ) self.shutting_down = false self.simulator = Simulator( app_instance=self ) self.environment = Environment() self.communicator = ConsoleComm( app_instance=self ) self.communicator.open() self.communicator.check_for_msgs()
def processCmd(self, cmd): cmd = cmd.strip() if cmd == '' or cmd == None: return False if cmd == 'exit': return True elif cmd[:3] == 'dl ': path = cmd[3:] # uvloop self.asyncrun(self.downloader.downloadPath(path)) else: if not self.asyncrun(self.downloader.downloadPath(cmd)): Console.print_red("no such command!")
class RoboSim: def __init__(self): self.console = Console(parent=Tkinter.Tk(), app_instance=self) self.shutting_down = false self.simulator = Simulator(app_instance=self) self.environment = Environment() self.communicator = ConsoleComm(app_instance=self) self.communicator.open() self.communicator.check_for_msgs() def run_mainloop(self): self.console.mainloop() def killapp(self): sys.exit(-1) def set_environment(self, env): self.environment = env self.console.update_environment(env) def exit_robo_sim(self): self.console.destroy() sys.exit() def initiate_shutdown(self): self.shutting_down = true self.communicator.send_killall() self.console.after(1000, self.exit_robo_sim)
async def addPlaylist(self, url): url = url.strip() print('will add playlist: ' + url) html = await self.session.get(url) try: info = self.getConfigFromHtml2(html) contiHeaders = {} try: contiHeaderInfo = self.getConfigFromHtml3(html) contiHeaders = self.getContiRequestHeaders(contiHeaderInfo) except Exception: Console.print_blue('no more') contents = await self.processPlaylistInfo(0, info, contiHeaders) vids = [ videoinfo['playlistVideoRenderer']['videoId'] for videoinfo in contents ] Console.print_yellow(url + ' | total videos:' + str(len(vids))) tasks = [ asyncio.ensure_future(self.downloadV(vid)) for vid in vids ] await asyncio.wait(tasks) except Exception as err: Console.print_red(err) Console.print_red('get playlist fail, url=' + url)
class RoboSim: def __init__( self ): self.console = Console( parent=Tkinter.Tk(), app_instance=self ) self.shutting_down = false self.simulator = Simulator( app_instance=self ) self.environment = Environment() self.communicator = ConsoleComm( app_instance=self ) self.communicator.open() self.communicator.check_for_msgs() def run_mainloop( self ): self.console.mainloop() def killapp( self ): sys.exit( -1 ) def set_environment( self, env ): self.environment = env self.console.update_environment( env ) def exit_robo_sim( self ): self.console.destroy() sys.exit() def initiate_shutdown( self ): self.shutting_down = true self.communicator.send_killall() self.console.after( 1000, self.exit_robo_sim )
async def addFilm(self, url): if url.find('list=') != -1: await self.addMix(url) try: v = self.getV(url) if v: if self.canDownload(v): if await self.downloadV(v): return else: Console.print_yellow('exist! v=%s'%(v), False, 1, ", " + v) return except Exception as err: self.logfile(err) self.logfile('download url fail: ' + url[:-1])
def gps(mode): """ Allows to invoke all required modules in order to execute GPS module. Takes `mode` as an input parameter that indicates car's motion pattern (for example, constant position `p`, constant speed `v` or random acceleration `a`). """ try: car = Car() dim = 2 # assign initial velocity. velocity, is_accel = car.default_velocity(mode, dim=dim) # ask user if default parameters should be used for modeling. is_default = console.is_default(dimension=dim) # get initial state of a car. init_data = car.initialize(dimension=dim, init_velocity=velocity, mode=mode, is_accel=is_accel, is_default=is_default) # invoke Kalman filter for processing GPS data. spa = SPA() spa.gps_kf(dimension=dim, init_data=init_data) except Exception as e: print('Exception: '.upper(), e) traceback.print_tb(e.__traceback__) init_data = None
def __call__(self): c = Console('') service = ModuleService() module = Module() module.name = c.console(intro="PyDrupal -- Create a new module", prompt="Module Name: ") module.description = c.console(prompt="Module Description: ") module.package = c.console(default=None, prompt="Module Package [None]: ") module.version = c.console(default='VERSION', prompt="Module Version [VERSION]: ") module.drupal_version = c.console(default='7.x', prompt="Supported Drupal Version [7.x]: ") if service.exists(module.name): overwrite = c.console(default='n', prompt="WARNING: This module already exists, overwrite? [y/N]: ") overwrite = overwrite.lower() overwrite = True if overwrite == 'y' else False if overwrite: service.save(module) else: print("Aye Aye Cap'n, sending this process to walk the plank") return service.save(module)
def getMaxAVWithExt(self, formats, ext): maxAudio = {} maxVideo = {} for fmt in formats: mediaType = None if 'clen' in fmt and fmt['clen'] == '0': continue if 'type' in fmt and fmt['type'] == 'FORMAT_STREAM_TYPE_OTF': continue if self.checkFmtMatch(self.getUrlFromFmt(fmt), 'audio', ext, fmt['mimeType']): mediaType = 'a' if self.checkFmtMatch(self.getUrlFromFmt(fmt), 'video', ext, fmt['mimeType']): mediaType = 'v' if not mediaType: continue if mediaType == 'a': if not bool(maxAudio): maxAudio = fmt else: try: if ('bitrate' in maxAudio) and ('bitrate' in fmt): br_o = int(maxAudio['bitrate']) br_t = int(fmt['bitrate']) maxAudio = maxAudio if br_o > br_t else fmt except Exception as err: Console.print_red(err) if mediaType == 'v': if not bool(maxVideo): maxVideo = fmt else: try: pixel_o = maxVideo['width'] * maxVideo['height'] pixel_t = fmt['width'] * fmt['height'] if pixel_o < pixel_t: maxVideo = fmt elif pixel_o == pixel_t: if ('bitrate' in maxVideo) and ('bitrate' in fmt): br_o = int(maxVideo['bitrate']) br_t = int(fmt['bitrate']) maxVideo = maxVideo if br_o > br_t else fmt except Exception as err: Console.print_red(err) return maxAudio, maxVideo
async def processPlaylistInfo(self, count, info, contiHeaders): contents = info['contents'] playlistId = '' if 'playlistId' in info: playlistId = info['playlistId'] try: contiinfo = info['continuations'][0]['nextContinuationData'] continuation = contiinfo['continuation'] itct = contiinfo['clickTrackingParams'] contiurl = self.continueurl % (continuation, continuation, itct) rsp = await self.session.getWithHeaders(contiurl, contiHeaders) json = self.getContiResponseJson(rsp) info_new = json['response']['continuationContents']['playlistVideoListContinuation'] Console.print_green('analyzing playlist - %s, contents: %d' % (playlistId, (count + len(contents)))) contents = contents + await self.processPlaylistInfo(count + len(contents), info_new, contiHeaders) except Exception: Console.print_blue('no more') pass return contents
def fuzzy(): try: is_miso = console.is_miso_fuzzy() if is_miso == True: fc = FuzzyDriverMiso() fc.call() else: fc = FuzzyDriverSiso() fc.call() except Exception as e: print('Exception: '.upper(), e) traceback.print_tb(e.__traceback__)
async def downloadPath(self, path): if path.startswith('#'): return True if path == '.': await self.addAllSelfPlayLists() return True elif path.startswith(self.prefix_v): await self.addFilm(path) return True elif path.startswith(self.prefix_channel): await self.addChannel(path) return True elif path.startswith(self.prefix_playlist): await self.addPlaylist(path) return True elif os.path.splitext(path)[1] == '.vlst': await self.addVList(path) return True else: Console.print_red('ignore unknown path:' + path) return False
def __init__(self): self.console = Console(parent=Tkinter.Tk(), app_instance=self) self.shutting_down = false self.simulator = Simulator(app_instance=self) self.environment = Environment() self.communicator = ConsoleComm(app_instance=self) self.communicator.open() self.communicator.check_for_msgs()
def fetchHandler(self, url, path, size, size_all, size_done, speed): self.speedHelper.mark(size) if self.increaseFetchHandlerCounter() % 100: return colorPrint = self.colorPrints[self.urlIndex(url) % len(self.colorPrints)] filename = os.path.split(path)[1] purename = filename[filename.find(' - ') + 3:filename. rfind(' - ')] + filename[filename.rfind('-'):] logname = purename namelength = 60 hlength = int(len(logname)) counter = 3 while self.halfWidthLen(logname) > namelength - 2: logname = logname[:hlength - counter] + '...' + logname[-hlength + counter:] counter = counter + 1 logname = logname + ' ' * (namelength - self.halfWidthLen(logname)) Console.print_blue('downloading | ', False) log = logname + ' | ' + "%4.1f%% "%(size_done*100/size_all) + '%8s' % self.sizeByte2Str(size_done) + \ ' /' + '%8s' % self.sizeByte2Str(int(size_all)) + ' | ' + self.sizeByte2Str(speed) + '/s' colorPrint(log, False) Console.print_purple(' | ', False) allSpeedLog = self.sizeByte2Str(self.speedHelper.speed()) + '/s' Console.print_yellow(allSpeedLog)
def start(self): param = (None, None) proxy = None if not self.config: self.config = {} else: if self.config['username'] and self.config['password']: param = (self.config['username'], self.config['password']) elif self.config['login']: param = self.inputUserInfo() proxy = self.config['proxy'] self.session = YoutubeSession(*param, proxy) if not self.session.username: Console.print_red('init failed! will exit.') exit() self.downloader = YoutubeDownloader(self.session) if self.config['maxTaskNum']: self.downloader.setMaxTaskNum(self.config['maxTaskNum']) if self.config['maxTaskCounter']: self.downloader.setMaxTaskCounter(self.config['maxTaskCounter']) if self.config['workpath']: self.downloader.setWorkPath(self.config['workpath']) if self.config['donelist']: self.downloader.setDonefile(self.config['donelist']) if self.config['errlist']: self.downloader.setErrfile(self.config['errlist']) if self.config['logsfile']: self.downloader.setLogsfile(self.config['logsfile']) if self.config['stopfile']: self.downloader.setStopfile(self.config['stopfile']) Console.print_green("I'm ready!") if 'cmd' in self.config: print(self.session.username + ">" + self.config['cmd']) self.processCmd(self.config['cmd']) while 1: cmd = input(self.session.username + ">") if self.processCmd(cmd): break print("end")
def getMaxAVWithExt(self, formats, ext): maxAudio = {} maxVideo = {} for fmt in formats: mediaType = None if fmt['mimeType'].startswith('audio/' + ext): mediaType = 'a' if fmt['mimeType'].startswith('video/' + ext): mediaType = 'v' if not mediaType: continue if mediaType == 'a': if not bool(maxAudio): maxAudio = fmt else: try: if ('bitrate' in maxAudio) and ('bitrate' in fmt): br_o = maxAudio['bitrate'] br_t = fmt['bitrate'] maxAudio = maxAudio if br_o > br_t else fmt except Exception as err: Console.print_red(err) if mediaType == 'v': if not bool(maxVideo): maxVideo = fmt else: try: pixel_o = maxVideo['width'] * maxVideo['height'] pixel_t = fmt['width'] * fmt['height'] if pixel_o < pixel_t: maxVideo = fmt elif pixel_o == pixel_t: if ('bitrate' in maxVideo) and ('bitrate' in fmt): br_o = maxVideo['bitrate'] br_t = fmt['bitrate'] maxVideo = maxVideo if br_o > br_t else fmt except Exception as err: Console.print_red(err) return maxAudio, maxVideo
def __init__(self, gui_bridge, params): threading.Thread.__init__(self) self.gui_bridge = gui_bridge self.params = params self.event_start = threading.Event() self.event_pause = threading.Event() self.event_stop = threading.Event() self.entities_updated = {} self.console = Console("Error") # StatItems self.current_iteration = StatItem("Iteration: ", 0) # Liste des entités à ajouter & supprimer self.entities_to_remove = [] self.entities_to_add = [] # Zones de la carte pour rayon d'interactions et positions self.areas = [] self.area_interaction_range_min = 1 # valeur de détection minimale pour les calculs de zone self.area_square_size = 0 self.area_number_height = 0 self.area_number_width = 0
def GenTmpVlst(tmppath, vlst): if not os.path.isdir(tmppath): Console.print_red('目录不存在:%s' % (tmppath)) return files = os.listdir(tmppath) baseUrl = 'https://www.youtube.com/watch?v=%s' urls = {*()} for filename in files: v = filename[filename.rfind(' - ') + 3:filename.rfind('-')] urls.add(baseUrl % (v)) with open(vlst, 'w', encoding='utf-8') as f: for url in urls: f.write(url + '\n') Console.print_yellow(url) Console.print_green('\ntotal: %d\nvlst : %s' % (len(urls), vlst))
from controller.GradeController import GradeController from controller.StudentController import StudentController from controller.UndoController import UndoController from domain.validators import GradeValidator, StudentValidator from repository.GradeRepo import GradeRepo from repository.StudentRepo import StudentRepo if __name__ == '__main__': print("App started running.") grade_validator = GradeValidator() student_validator = StudentValidator() grade_repo = GradeRepo(grade_validator) student_repo = StudentRepo(student_validator) grade_controller = GradeController(grade_repo) student_controller = StudentController(student_repo) undo_controller = UndoController(student_controller, grade_controller) console = Console(student_controller, grade_controller, undo_controller) try: console.run() except Exception: print("An error accured.") traceback.print_exc() print("That's all folks.")
#!/usr/bin/env python from console.console import Console import re if __name__ == "__main__": c = Console() last_address = None while True: contents = c.read() ip = re.findall( r"(?<=Connected to )[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,5}", contents) if ip: address = ip.pop() if not address == last_address: print("Connecting to " + address) last_address = address c.send("connect %s matchmaking" % address)
import sys from console.console import Console def GenTmpVlst(tmppath, vlst): if not os.path.isdir(tmppath): Console.print_red('目录不存在:%s' % (tmppath)) return files = os.listdir(tmppath) baseUrl = 'https://www.youtube.com/watch?v=%s' urls = {*()} for filename in files: if not filename.endswith('.tmp'): v = filename[filename.rfind(' - ') + 3:filename.rfind('-')] urls.add(baseUrl % (v)) with open(vlst, 'w', encoding='utf-8') as f: for url in urls: f.write(url + '\n') Console.print_yellow(url) Console.print_green('\ntotal: %d\nvlst : %s' % (len(urls), vlst)) if __name__ == '__main__': if len(sys.argv) != 3: Console.print_red('参数错误') exit() GenTmpVlst(sys.argv[1], sys.argv[2])
def markDownloaded(self, v): try: with open(self.donefile, 'a') as file: file.write(v + '\n') except Exception as err: Console.print_red(err)
async def downloadV(self, v): if not self.checkDownloadState(v): return self.increaseTotalCount() while self.curTaskNum >= self.maxTaskNum: leftCount = int(self.totalCount - self.doneCount) % 100 await asyncio.sleep(leftCount) # double check if not self.checkDownloadState(v): self.increaseDoneCount() return self.markDownloading(v) Console.print_cyan(r' ------ begin download v=%s ------ ' % (v)) self.curTaskNum = self.curTaskNum + 1 try: url_v = self.prefix_v + v html_v = await self.session.get(url_v) player_response, dashmpd, adaptFmt = self.getConfigFromHtml1( html_v) if not player_response: Console.print_red('get config fail, v=' + v) return False representations = await self.getRepresentations(dashmpd) videoDetails = player_response['videoDetails'] formats = [] player_url = self.getPlayerUrl(html_v) streamingData = player_response['streamingData'] if 'formats' in streamingData: formats += streamingData['formats'] if 'adaptiveFormats' in streamingData: formats += streamingData['adaptiveFormats'] if representations: formats += representations if adaptFmt: formats += self.parse_adaptive_fmts(adaptFmt) title = videoDetails['title'] pureTitle = self.removeInvalidFilenameChars(title) channel = videoDetails['channelId'] filename = channel + ' - ' + pureTitle + ' - ' + v maxAudio, maxVideo = self.getMaxAV(formats) if not bool(maxVideo): self.onVErr(v) return False try: ext = '.webm' if maxVideo['mimeType'].startswith('video/mp4'): ext = '.mp4' if not bool(maxAudio): maxAudio = maxVideo tmpPath = self.workpath + 'tmp/' if not os.path.exists(tmpPath): os.makedirs(tmpPath) videoPath = tmpPath + filename + '-video' + ext audioPath = tmpPath + filename + '-audio' + ext outptPath = self.workpath + filename + ext self.checkSig(maxVideo, v, player_url) self.checkSig(maxAudio, v, player_url) videoUrl = maxVideo['url'] audioUrl = maxAudio['url'] self.taskmap[videoUrl] = self.taskCounter self.taskCounter = self.taskCounter + 1 self.taskmap[audioUrl] = self.taskCounter self.taskCounter = self.taskCounter + 1 tasks = [ asyncio.ensure_future( self.session.fetch(videoUrl, videoPath, self.fetchHandler)) ] if videoUrl != audioUrl: tasks.append( asyncio.ensure_future( self.session.fetch(audioUrl, audioPath, self.fetchHandler))) await asyncio.wait(tasks) if self.isResultSucc(tasks): Console.print_purple('merging audio and video..') if videoUrl == audioUrl: shutil.move(videoPath, outptPath) else: mergeCmd = 'ffmpeg -loglevel quiet -nostdin -y -i \"' + audioPath + '\" -i \"' + videoPath + '\" -acodec copy -vcodec copy \"' + outptPath + '\"' os.system(mergeCmd) self.markDownloaded(v) Console.print_green( outptPath + ' is done, %4.1f%% %d/%d' % ((self.doneCount + 1) * 100 / self.totalCount, self.doneCount + 1, self.totalCount)) if os.path.exists(videoPath): os.remove(videoPath) if os.path.exists(audioPath): os.remove(audioPath) else: Console.print_red(r'network err! v=%s download fail!' % (v)) self.taskmap.pop(videoUrl) if videoUrl != audioUrl: self.taskmap.pop(audioUrl) except Exception as err: Console.print_red(err) except Exception as err: Console.print_red(err) self.onVErr(v) return False finally: self.increaseDoneCount() self.markNotDownloading(v) self.curTaskNum = self.curTaskNum - 1 return True
def onVErr(self, v): self.markErred(v) Console.print_red('get avconfig fail, v=%s, 视频已被删除' % (v))
""" Created on 29/01/2017 @author Stefan """ from console.console import Console from controller.Controller import Controller from controller.UndoController import UndoController from repository.SentenceRepository import SentenceRepository if __name__ == '__main__': sentence_repo = SentenceRepository() controller = Controller(sentence_repo) undo_controller = UndoController() console = Console(controller, undo_controller) console.run()
m_iHealth my health m_iPing my ping m_iPrimaryAmmoCount m_iPrimaryAmmoType m_iReloadMode m_iRoundsWon m_iScore my score? m_iSecondaryAmmoCount m_iSecondaryAmmoType m_iState m_iTeamNum m_iViewModelIndex Current weapon m_iWorldModelIndex Current weapon m_nViewModelIndex Old? Current weapon? pl.deadflag Me dead """ if __name__ == "__main__": c = Console() vars = {} g15 = LCD() g15.rate_update = 1 g15.start()
# Pour la gestion des exceptions import sys, traceback if __name__ == '__main__': # Copie des simulations par défaut dans le "home" de l'utilisateur # s'il n'y pas de simulations existantes if not os.path.exists(Globals.user_abs_path()): shutil.copytree(Globals.default_user_dir, Globals.user_root) # Initialisation de l'environnement graphique. application = QApplication(sys.argv) # Démarrage de la console console = Console("Launch console") console.show() console.push(Messages.main_001) exceptionOccurred = False try: # Préparation du user_data (fichier __init__.py) Builder.config_start() build_workspace() # Chargement des configurations params = Builder.get_params() console.push(Messages.main_002) console.push(Messages.main_003) except Exception as e: console.push_error("Error building simulation {}".format(Globals._simulation_name))
#!/usr/bin/env python from console.console import Console import re if __name__ == "__main__": c = Console() last_address = None while True: contents = c.read() ip = re.findall(r"(?<=Connected to )[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:[0-9]{1,5}", contents) if ip: address = ip.pop() if not address == last_address: print("Connecting to " + address) last_address = address c.send("connect %s matchmaking" % address)