def main(): c = CommandLine(sys.argv) c.run() problem = Problem(c.instance()) problem.processInstanceFiles() problem.print()
def start(self): self._play_introduction_dialog() while (True): print("\nIt's your turn") print("What do you want to do?") print() command = input().lower() system('clear') CommandLine.parse(command)
def get_cmd_args(urls_local): commandline = CommandLine(sys.argv) urls_commandline = commandline.get_urls() if urls_commandline is not None: urls_local = urls_commandline return commandline.get_path_to_save(), urls_local, commandline.is_verbose( ), commandline.is_hourly()
def main(): """The pyview main entry point""" global folderHelper, window # Build command line parser cmdLine = CommandLine(LocalizedVersion()) options = cmdLine.getOptions() # Load image format plugins ImageFormats.loadImageFormatPlugins() # Get initial directory folderHelper = FolderHelper(options) folderHelper.setLastOpenedFile(options.initialFile) startDir = folderHelper.getFileDialogInitialDirectory() # Get and configure App object app = QtGui.QApplication(sys.argv) #QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Cleanlooks")) # Create and set window window = MainWindow() window.setFileDialogDirectory(startDir) window.centerWindow() # Connections window.connect(window, QtCore.SIGNAL("openFileFinished(char*, bool)"), onFileLoaded) # Show the window window.show() # Load initial file if options.initialFile: window.openFile(options.initialFile) # Start the application return app.exec_()
def __init__(self): map_number = randint(1, 3) file = open(f"map{map_number}.txt", "r") rows = 0 map = [] for line in file: map.append([]) columns = 0 for cell in line: if cell == '0': map[rows].append(Tile(rows, columns, "0")) elif cell == 'H': self._hero = Hero(rows, columns) CommandLine.add_argument("move", "-n", "--north", "Moves your character forward", self._move_forward_hero) CommandLine.add_argument("move", "-s", "--south", "Moves your character backward", self._move_backward_hero) CommandLine.add_argument("move", "-w", "--west", "Moves your character left", self._move_left_hero) CommandLine.add_argument("move", "-e", "--est", "Moves your character right", self._move_right_hero) map[rows].append(self._hero) elif cell == 'M': map[rows].append(Monster(rows, columns)) elif cell == 'D': map[rows].append(Tile(rows, columns, "D")) elif cell == 'C': map[rows].append(Tile(rows, columns, "C")) elif cell != "\n": map[rows].append(Tile(rows, columns, cell)) columns += 1 rows += 1 file.close() self._number_of_rows = rows self._number_of_columns = len(map[0]) self._map = map
def main() : commandline = CommandLine(sys.argv) e = None try : #if True : action = commandline.parse() if action == CommandLine.ACTION_DUMP : configuration = Configuration() dumpername = configuration.get_value('dumper') pluginpath = [] pluginsubpath = os.path.join('dirstat','Dumpers') if os.path.exists(sys.argv[0]) : pluginpath.append(os.path.join(os.path.dirname(sys.argv[0]),pluginsubpath)) if configuration.get_value('pluginpath') != '' : pluginpath.append(os.path.join(configuration.get_value('pluginpath'),pluginsubpath)) pluginpath.append(configuration.get_value('pluginpath')) for pathname in sys.path : pluginpath.append(os.path.join(pathname,pluginsubpath)) try : modulename = dumpername #print (modulename,pluginpath) moduleinfo = imp.find_module(modulename,pluginpath) #print (moduleinfo,) module = imp.load_module(modulename,*moduleinfo) moduleinfo[0].close() Dumper = module.Dumper Dumper().dump() except ImportError : raise ParseError('Dumper %s cannot be loaded' % (dumpername,)) elif action == CommandLine.ACTION_USAGE : print commandline.get_usage(), elif action == CommandLine.ACTION_VERSION : print commandline.get_version_text(), elif action == CommandLine.ACTION_CONFIG : config() except (ParseError,ValueError), e : print commandline.get_usage() raise e
class Main: """Main execution class. Also servers as a bridge between the View and Controller and the Model.""" def Main(self): """Initialise the system.""" self.commandLine = CommandLine(self, "> ") self.interpreter = self.MakeInterpreter() self.commandLine.Splash() self.commandLine.Run() def MakeInterpreter(self): return Interpreter( Environment(256), # Initialise the environment with 8-bit cells LambdaStack(), self.commandLine) def Quit(self, command): raise SystemExit def Reset(self, command): del self.interpreter self.interpreter = self.MakeInterpreter() self.commandLine.Log("Sucessfully reset interpreter.") def State(self, command): self.commandLine.LogState(self.interpreter.state.tape, (self.interpreter.state.pointer, self.interpreter.state.tape.leftMost, self.interpreter.state.tape.rightMost), self.interpreter.stack, command.split(' ')) def RunFile(self, command): files = command.split(' ') for file in files: try: with open(file, 'r') as scriptFile: script = scriptFile.read() except: self.commandLine.Log("Could not open file '{}'".format(file)) else: self.Run(script) def Run(self, code): try: self.interpreter.Execute(code) except Exception as e: self.commandLine.Log(e)
def generate(self, strImageName, strStyleFile, sTaxaFileName, strCircladerScript = ConstantsBreadCrumbs.c_strCircladerScript, iTerminalCladeLevel = 10, sColorFileName=None, sTickFileName=None, sHighlightFileName=None, sSizeFileName=None, sCircleFileName=None): """ This is the method to call to generate a cladogram using circlader. The default data file is an abundance table unless the getDa function is overwritten. :param strImageName: File name to save the output cladogram image :type: strImageName File name (string) :param strStyleFile: File path indicating the style file to use :type: strStyleFile File path (string) :param sTaxaFileName: File path indicating the taxa file to use :type: sTaxaFileName File path (string) :param strCircladerScript: File path to the Circlader script :type: String :param iTerminalCladeLevel: Clade level to use as terminal in plotting :type: iTerminalCladeLevel integer starting with 1 :param strColorFile: File path indicating the color file to use :type: strColorFile File path (string) :param strTickFile: File path indicating the tick file to use :type: strTickFile File path (string) :param strHighlightFile: File path indicating the highlight file to use :type: strHighlightFile File path (string) :param strSizeFile: File path indicating the size file to use :type: strSizeFile File path (string) :param sCircleFileName: File path of circlader circle file. :type: String """ if self.npaAbundance == None: print "Cladogram::generate. The data was not set so an image could not be generated" return False #Set script self.circladerScript = strCircladerScript #Set output file name self.strImageName = strImageName #Check files exist and remove files which will be written self.manageFilePaths(sTaxaFileName, strStyleFile, sColorFileName, sTickFileName, sHighlightFileName, sSizeFileName, sCircleFileName) #Get IDs lsIDs = [strId for strId in list(self.npaAbundance[self.strSampleID])] #Generate a dictionary to convert the ids to correct format #Fix unclassified names #Make numeric labels as indicated self.dictConvertIDs = self.generateLabels(lsIDs) #Remove taxa lower than the display clade level lsCladeAndAboveFeatures = [] for sFeature in lsIDs: if len(sFeature.split(self.cFeatureDelimiter)) <= iTerminalCladeLevel: lsCladeAndAboveFeatures.append(sFeature) lsIDs = lsCladeAndAboveFeatures #Filter by abundance if(self.fAbundanceFilter): lsIDs = self.filterByAbundance(lsIDs) #Update to the correct root lsIDs = self.updateToRoot(lsIDs) #Set highlights to root for consistency if(not self.strRoot == None): dictRootedHighLights = dict() if not self.dictForcedHighLights == None: for sKey in self.dictForcedHighLights.keys(): strUpdatedKey = self.updateToRoot([sKey]) dictRootedHighLights[strUpdatedKey[0]]=self.dictForcedHighLights[sKey] self.dictForcedHighLights = dictRootedHighLights #Set relabels to root for consistency if(not self.strRoot == None): dictRootedLabels = dict() if not self.dictRelabels == None: for sKey in self.dictRelabels.keys(): strUpdatedKey = self.updateToRoot([sKey]) dictRootedLabels[strUpdatedKey[0]]=self.dictRelabels[sKey] self.dictRelabels = dictRootedLabels #Filter by clade size Should be the last filter. #It is not a strong filter but cleans up images if(self.fCladeSizeFilter): lsIDs = self.filterByCladeSize(lsIDs) #Add in forced highlighting lsIDs.extend(self.dictForcedHighLights.keys()) lsIDs = list(set(lsIDs)) #Add in forced circle data for dictCircleData in self.ldictCircleData: if(dictCircleData[self.c_sForced]): lsTaxa = dictCircleData[self.c_sTaxa] lsAlpha = dictCircleData[self.c_sAlpha] lsAddTaxa = [] [lsAddTaxa.append(lsTaxa[tpleAlpha[0]]) if not tpleAlpha[1] == '0.0' else 0 for tpleAlpha in enumerate(lsAlpha)] lsIDs.extend(lsAddTaxa) lsIDs = list(set(lsIDs)) #Create circle files (needs to be after any filtering because it has a forcing option). if not self.createCircleFile(lsIDs): return False #Generate / Write Tree file if not self.createTreeFile(lsIDs): return False #Generate / Write Highlight file if not self.createHighlightFile(lsIDs): return False #Generate / write color file if(self.dictColors is not None): lsColorData = [ConstantsBreadCrumbs.c_cTab.join([sColorKey,self.dictColors[sColorKey]]) for sColorKey in self.dictColors] self.writeToFile(self.strColorFilePath, ConstantsBreadCrumbs.c_strEndline.join(lsColorData), False) self.fColorFileMade=True #Generate / write tick file if(self.llsTicks is not None): lsTickData = [ConstantsBreadCrumbs.c_cTab.join(lsTicks) for lsTicks in self.llsTicks] self.writeToFile(self.strTickFilePath, ConstantsBreadCrumbs.c_strEndline.join(lsTickData), False) self.fTickFileMade=True #Generate / Write size data if not self.createSizeFile(lsIDs): return False #Call commandline lsCommand = [self.circladerScript, self.strTreeFilePath, self.strImageName, "--style_file", self.strStyleFilePath, "--tree_format", "tabular"] if(self.fSizeFileMade): lsCommand.extend(["--size_file", self.strSizeFilePath]) if(self.fColorFileMade): lsCommand.extend(["--color_file", self.strColorFilePath]) if(self.fTickFileMade): lsCommand.extend(["--tick_file", self.strTickFilePath]) if(self.fHighlightFileMade): lsCommand.extend(["--highlight_file", self.strHighLightFilePath]) if(self.fCircleFileMade): lsCommand.extend(["--circle_file", self.strCircleFilePath]) CommandLine().runCommandLine(lsCommand)
# Test Central Log import CentralLog """ TESTS Fetch token """ core = "TestCore.json" # Valid personality core with existing token language = "EN" # Valid language try: CentralLog.GetBotToken(core); print(PASS) except Exception as e: print(FAIL + ": {}".format(e)) # Test Command Line from CommandLine import CommandLine commandLine = CommandLine(None) """ TESTS Give error """ try: commandLine.GiveError(PASS) except Exception as e: print(FAIL + ": {}".format(e)) # Test Bot Manager import CentralLog from BotManager import BotInterface """ TESTS Creating bot manager
def Main(self): """Initialise the system.""" self.commandLine = CommandLine(self, "> ") self.interpreter = self.MakeInterpreter() self.commandLine.Splash() self.commandLine.Run()
botInterface.StopBot(bot) commandLine.Display("Finalising...") raise SystemExit def Preset(name, personalityCore, functionalityCores, clean): CentralLog.NewPreset(name, personalityCore, functionalityCores, clean) def LoadPreset(name): return CentralLog.LoadPreset(name) # Global access language = "EN" commandLine = CommandLine(None) sanityChecker = SanityChecker() # Main if __name__ == "__main__": botInterface = BotInterface() managerData = { "callbacks": { "newbot": botInterface.NewBot, "stopbotbyid": botInterface.StopBotByID, "preset": Preset, "loadpreset": LoadPreset, "info": botInterface.Info, "stop": ShutDown } }
status_json = self.client.get_job(self.job_id) print("STATUS: {}".format(status_json)) job_status = status_json['jobs'][0]['status'] logging.info('Monitoring job: {}'.format(self.job_id)) logging.info('Job status: {}'.format(job_status)) while not job_status in self.end_statuses: # failed? killed? time.sleep(5) status_json = self.client.get_job(self.job_id) print(status_json) job_status = status_json['jobs'][0]['status'] logging.info('Job status: {}'.format(job_status)) return status_json if __name__ == "__main__": logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO, stream=sys.stderr) logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) import json, pprint from CommandLine import CommandLine cl = CommandLine() client = RestClient("admin", "admin") out = cl(client) if isinstance(out, dict): pprint.pprint(json.dumps(out, indent=4)) else: for o in out: pprint.pprint(o)