Example #1
0
File: main.py Project: parpg/parpg
def main(parser):

    opts, args = parser.parse_args()

    levels = {'debug': logging.DEBUG,
              'info': logging.INFO,
              'warning': logging.WARNING,
              'error': logging.ERROR,
              'critical': logging.CRITICAL}

    #TODO: setup formating
    logging.basicConfig(filename=opts.logfile, level=levels[opts.loglevel])
    logger = logging.getLogger('parpg')

    try:
        old_path = sys.path
        if opts.fife_path:
            sys.path = [opts.fife_path]
        import fife
    except ImportError:
        logger.critical("Could not import fife module. Please install fife or set the --fife-path command line value")
        parser.print_help()
        sys.exit(1)
    finally:
        sys.path = old_path


    from fife.extensions.fife_settings import Setting

    settings = Setting(settings_file="settings.xml")
    
    data_dir =  abspath(settings.get("parpg","DataPath"))
    settings.set("parpg", "DataPath", data_dir)
    settings.set("FIFE", "WindowIcon", data_dir + "/" + settings.get("FIFE", "WindowIcon"))
    settings.set("FIFE", "Font", data_dir + "/" + settings.get("FIFE", "Font"))
   
    from parpg.application import PARPGApplication
    from parpg.common import utils
    
    # enable psyco if available and in settings file
    try:
        import psyco
        psyco_available = True
    except ImportError:
        logger.warning('Psyco Acceleration unavailable')
        psyco_available = False
    
    if settings.get("fife", "UsePsyco"):
        if psyco_available:
            psyco.full()
            logger.info('Psyco Acceleration enabled')
        else:
            logger.warning('Please install psyco before attempting to use it'
                            'Psyco Acceleration disabled')
    else:
        logger.info('Psycho Acceleration disabled')
    
    # run the game
    app = PARPGApplication(settings)
    app.run()
Example #2
0
 def _activatePsyco(self):        
    """Import Psyco if available"""
    try:
        import psyco
        psyco.full()
    except ImportError:
        pass
Example #3
0
def main():
    try:
        import psyco
        psyco.full()
    except Exception:
        pass
    parser = OptionParser(usage="%prog [options] <input files>")
    parser.add_option(
        "-d", "--tmdb", dest="tmdb_file", default="tm.db",
        help="translation memory database file (default: tm.db)")
    parser.add_option(
        "-s", "--import-source-lang", dest="source_lang", default="en",
        help="source language of translation files (default: en)")
    parser.add_option(
        "-t", "--import-target-lang", dest="target_lang",
        help="target language of translation files")
    (options, args) = parser.parse_args()

    if not options.target_lang:
        parser.error('No target language specified.')

    if len(args) < 1:
        parser.error('No input file(s) specified.')

    Builder(options.tmdb_file, options.source_lang, options.target_lang, args)
Example #4
0
def main():
	import re, sys
	
	for arg in sys.argv:
		if re.search('-help', arg, re.IGNORECASE):
			gotFeedAlready = True
			usage()
			sys.exit()
	
	iPXSettings.progName = 'iPodderX'
	for arg in sys.argv:
		if re.search('-progName', arg, re.IGNORECASE):
			progNameSplit = arg.split('==')
			iPXSettings.progName = progNameSplit[len(progNameSplit)-1]
	
	firstInit()
	for arg in sys.argv:
		if arg == '-debug':
			printMSG( '--- DEBUG ENABLED ---')
			iPXSettings.DEBUG = 1
		elif arg == '-superdebug':
			printMSG( '--- SUPER DEBUG ENABLED ---')
			import httplib
			httplib.HTTPConnection.debuglevel = 1
			iPXSettings.DEBUG = 1
			iPXSettings.SUPERDEBUG = 1

	try:
		import psyco
		logIt('Enabling Psyco JIT Compiler...')
		psyco.full()
		print passed
	except Exception, msg:
		pass
Example #5
0
def main(args):
    psyco.full()
    list_nodes = [str(n) for n in xrange(1,201)]
#    test_list = [random.sample(list_nodes, 200) for i in xrange(100)]
    edges = get_edges_from_file("./benchmarks/brock200_3.clq")
#    edges = get_edges_from_file("./benchmarks/In200_40_13_0.txt")
#    edges = get_edges_from_file("./benchmarks/MANN_a9.clq")
    start = time.time()
    graph = Graph(edges)
    print "graph: elapsed time - ", time.time() - start
#    psyco.cannotcompile(graph.induced_subgraph_2)
#    print "graph: elapsed time - ", time.time() - start
    start = time.time()
    copy = graph.dcopy()
    print "copy: elapsed time - ", time.time() - start
    start = time.time()
    for i in xrange(1, 201):
        subgraph = graph.induced_subgraph(str(i)) 
    print "subgraph: elapsed time - ", time.time() - start
#    start = time.time()
#    for i in xrange(1, 201):
#        subgraph = graph.induced_subgraph_2(str(i)) 
#    print "subgraph_c: elapsed time - ", time.time() - start
    start = time.time()
    graph.remove_nodes(list_nodes)
    print "remove: elapsed time - ", time.time() - start
Example #6
0
def install_psyco():
    "Install the psyco optimizer."
    try:
        import psyco
        psyco.full()
    except ImportError:
        logging.warning("Could not enable psyco.")
Example #7
0
 def simulationTestAllThread(self):
     self.lock = Lock()
     
     import psyco
     psyco.full()
     
     settingsToRun = {}
     settings = dir(Global)
     settingsToRunLen = []
     for setting in settings:
         if setting.endswith("TESTSET"):
             a = getattr(Global, setting)
             settingName = setting.split("TESTSET")[0]
             settingsToRun[settingName] = a
             settingsToRunLen.append(len(a))
     #settingsToRun contains all set data to run
     if len(settingsToRunLen) < 1:
         settingsCount = 1
     else:
         settingsCount = reduce(lambda x,y: x*y, settingsToRunLen)
     self.testToRunCount = settingsCount * len(Config.GetConfigs()) * len(Global.RandomSeeds)
     self.currentTestIndex = 0
     self.testRunStarted = time.time()
     
     self.simulationTestAllRecursive(settingsToRun)
def main_run():
    global cm, coords, WIDTH, HEIGHT

    coords = [(random.randint(0, WIDTH), random.randint(0, HEIGHT))
              for i in xrange(CITIES)]
    cm = cartesian_matrix(coords)
    genome = G1DList.G1DList(len(coords))

    genome.evaluator.set(lambda chromosome: tour_length(cm, chromosome))
    genome.crossover.set(Crossovers.G1DListCrossoverEdge)
    genome.initializator.set(G1DListTSPInitializator)

    # 3662.69
    ga = GSimpleGA.GSimpleGA(genome)
    ga.setGenerations(200000)
    ga.setMinimax(Consts.minimaxType["minimize"])
    ga.setCrossoverRate(1.0)
    ga.setMutationRate(0.02)
    ga.setPopulationSize(80)

    # This is to make a video
    ga.stepCallback.set(evolve_callback)
    # 21666.49
    import psyco
    psyco.full()

    ga.evolve(freq_stats=500)
    best = ga.bestIndividual()

    if PIL_SUPPORT:
        write_tour_to_img(coords, best, "tsp_result.png")
    else:
        print "No PIL detected, cannot plot the graph !"
Example #9
0
 def process_request(self, request):
     try:
         import psyco
         psyco.full()
     except ImportError:
         pass
     return None
def mutate(gens, settings=DEFAULT_SETTINGS, progress=__printProgress):
    global best_pred, best_prey

    try:
        import psyco
        psyco.full()
    except ImportError:
        pass

    for i in range(gens):
        progress(i, gens) #Update the progress

        #preds, preys = MutateAndScore()
        preds, preys = MultiThreadedMutateAndScore()

        #Find the best Pred Mask
        best = 0
        best_pred_mask = {}
        for s, mask in preds:
            if s > best:
                best = s
                best_pred_mask = mask

        #Find the best Prey Mask
        best = 0
        best_prey_mask = {}
        for s, mask in preys:
            if s > best:
                best = s
                best_prey_mask = mask

        #Smash the mask into the best pdf
        for k,v in best_pred_mask.iteritems(): best_pred[k] = v
        for k,v in best_prey_mask.iteritems(): best_prey[k] = v
    progress(gens,gens)#deniz was here
Example #11
0
def doctests():
    try:
        import psyco
        psyco.full()
    except ImportError:
        pass
    import sys
    from timeit import default_timer as clock
    filter = []
    for i, arg in enumerate(sys.argv):
        if '__init__.py' in arg:
            filter = [sn for sn in sys.argv[i+1:] if not sn.startswith("-")]
            break
    import doctest
    globs = globals().copy()
    for obj in globs: #sorted(globs.keys()):
        if filter:
            if not sum([pat in obj for pat in filter]):
                continue
        sys.stdout.write(str(obj) + " ")
        sys.stdout.flush()
        t1 = clock()
        doctest.run_docstring_examples(globs[obj], {}, verbose=("-v" in sys.argv))
        t2 = clock()
        print(round(t2-t1, 3))
Example #12
0
    def postOptions(self):
        self['_origdir'] = os.getcwd()
        # Want to do this stuff as early as possible
        _setUpTestdir()
        _setUpLogging(self)

        def _mustBeInt():
            raise usage.UsageError("Argument to --random must be a positive integer")
            
        if self['random'] is not None:
            try:
                self['random'] = long(self['random'])
            except ValueError:
                _mustBeInt()
            else:
                if self['random'] < 0:
                    _mustBeInt()
                elif self['random'] == 0:
                    self['random'] = long(time.time() * 100)

        if not self.has_key('tbformat'):
            self['tbformat'] = 'default'

        if self['psyco']:
            try:
                import psyco
                psyco.full()
            except ImportError:
                print "couldn't import psyco, so continuing on without..."

        if self['nopm']:
            if not self['debug']:
                raise usage.UsageError, "you must specify --debug when using --nopm "
            failure.DO_POST_MORTEM = False
Example #13
0
    def __init__(self, bot_class, universe_class=Universe, planet_class=Planet, fleet_class=Fleet, timeout=0.95):
        options, _ = parser.parse_args()

        self.logging_enabled = bool(options.logfile)
        self.universe = universe_class(self, planet_class=planet_class, fleet_class=fleet_class)
        self.bot = bot_class(self.universe)
        self.timeout = timeout
        self.turn_count = 0
        self._fleets_to_send = {}

        if self.logging_enabled:
            logging.basicConfig(filename=options.logfile, 
                                filemode='w', 
                                level=getattr(logging, options.loglevel), 
                                format="%(asctime)s %(levelname)s: %(message)s",
                                datefmt='%H:%M:%S',)
            
        log.info("----------- GAME START -----------")

        self.has_alarm = True
        try:
            signal.signal(signal.SIGALRM, timeout_handler)
        except AttributeError:
            # signal.SIGALRM not supported on this platform
            self.has_alarm = False
        try:
            #noinspection PyUnresolvedReferences
            import psyco
            psyco.full()
        except ImportError:
            pass
        self.main()
Example #14
0
 def __init__(self,input,logger=None,verbose=True):       
     """
     Initialize the ShelxC process
     
     input   is whatever is passed in
     pipe    is the communication back to the calling process
     verbose is to set the level of output
     logger  is logging for debugging.
     """
     psyco.full()
     logger.info('ShelxC.__init__')
  
     self.input                              = input
     self.verbose                            = verbose
     self.logger                             = logger
     
     #Setting up data input
     self.setup                              = self.input[1]
     self.header                             = self.input[2]        
     self.preferences                        = self.input[3]   
     self.data                               = self.input[4]     
     self.controller_address                 = self.input[-1]
     self.shelx_log                          = []
     self.shelx_results                      = {}
     self.cell                               = False
     self.sca                                = False
     
     multiprocessing.Process.__init__(self,name='ShelxC')        
     #starts the new process
     self.start()
Example #15
0
def main(*argv):

  try:   # Import Psyco if available
    import psyco
    psyco.full()
  except ImportError:
    print "psyco not available"

  mainwindow = gtk.Window()
  mainwindow.connect("delete_event", delete_event)  

  mainwindow.set_default_size(WIDTH, HEIGHT)
  mainwindow.add(TheWorld)
  mainwindow.show()

  TheWorld.create_width = WIDTH
  TheWorld.create_height = HEIGHT
  TheWorld.show()  
  TheEden.populate()

  # choose one
  TheSpaceTime.timer_id = gobject.idle_add(TheSpaceTime.tick)
  #TheSpaceTime.start()

  gtk.gdk.threads_enter()        
  gtk.main()
  gtk.gdk.threads_leave()        
Example #16
0
def main(testlist, verbose=0, use_resources=None):
    if use_resources is None:
        use_resources = []
    test_support.verbose = verbose      # Tell tests to be moderately quiet
    test_support.use_resources = use_resources
    
    if type(testlist) == type(""):
        testlist = [testlist]
    if not verbose:
        testlist = filter(python_check, testlist)

    # Psyco selective compilation is only activated here
    psyco.log(LOGFILE, 'a')
    for test in testlist:
        psyco.logger.write('with test ' + test, 1)
    psyco.full()
    #print "sleeping, time for a Ctrl-C !..."
    #import time; time.sleep(1.5)


    for test in testlist:
        for i in range(repeat_counter):
            print '%s, Psyco iteration %d' % (test, i+1)
            ok = regrtest.runtest(test, 0, verbose, 0)
            special_cleanup()
            if ok == 0:
                return 0
            elif ok < 0:
                break
    return 1
Example #17
0
def makeService(config):

    # Use psyco if available
    try:
        import psyco
        psyco.full()
    except ImportError:
        pass

    # configuration file
    configfile = yaml.load(file(config['config'], 'rb').read())
    # database
    dbpool = Database(configfile).pool
    application = service.MultiService()

    collector = CollectorService(configfile, dbpool)
    collector.setServiceParent(application)

    web = internet.TCPServer(int(config['port']),
                             appserver.NevowSite(MainPage(configfile,
                                                      dbpool,
                                                      collector)),
                             interface=config['interface'])
    web.setServiceParent(application)
    return application
Example #18
0
def getopts():
    '''parse options'''
    from optparse import OptionParser
    usage = "dumping the details of similarity calculation"
    parser = OptionParser(usage=usage)
    parser.add_option("-i", "--input",
                      dest="input", default="",
                      help="input file")
    parser.add_option("-o", "--output",
                      dest="output", default="",
                      help="output file")
    parser.add_option("-f", "--format",
                      dest="format", default="",
                      help="convert to format: svm/arff/cluto/triplet")
    parser.add_option("-l", "--label",
                      dest="label", default="",
                      help="label file")
    parser.add_option("-d", "--dict",
                      dest="dict", default="",
                      help="dict file")
    parser.add_option("-e", "--encoding", dest="encoding", default="utf8", 
            help="default system encoding, utf8 by default")
    parser.add_option("-p", "--psyco", action='store_true', 
                    dest="psyco", default=False,
                    help="to enable psyco")
    options = parser.parse_args()[0]
    if not options.input or not options.output or not options.format:
        print "-h to see usage"
        sys.exit(-1)
    if options.psyco:
        import psyco
        psyco.full()
    return options.input, options.output, options.format, options.label, options.dict, options.encoding
Example #19
0
def run_or_profile(suite):
    runner = unittest.TextTestRunner(verbosity=2)

    args = sys.argv[1:]

    if '-P' in args or '-PP' in args:
        try:
            import psyco
            if '-PP' in sys.argv[1:]:
                psyco.profile()
            else:
                psyco.full()
            print "Using Psyco."
        except:
            pass

    if '-p' in args:
        import os, hotshot, hotshot.stats
        LOG_FILE="profile.log"

        profiler = hotshot.Profile(LOG_FILE)
        profiler.runcall(runner.run, suite)
        profiler.close()

        stats = hotshot.stats.load(LOG_FILE)
        stats.strip_dirs()
        stats.sort_stats('time', 'calls')
        stats.print_stats(60)

        try:
            os.unlink(LOG_FILE)
        except:
            pass
    else:
        runner.run(suite)
Example #20
0
def main():
    psyco.full()
    usage = "usage: %prog [options] arm_program"
    parser = OptionParser(usage=usage)
    parser.add_option(
        "-e", "--entry", dest="entry_point", default=0, help="Entry point where te program starts, default 0"
    )
    parser.add_option("-l", "--loadaddr", dest="load_addr", default=0, help="Load addr of the program, default 0")
    parser.add_option(
        "-m", "--memsize", dest="memory_size", default=128 * 1024, help="Size of memory in bytes, default 131072 (128k)"
    )
    parser.add_option(
        "-H", "--halt", dest="halt", default=False, action="store_true", help="Dont run the program automatically"
    )
    (options, args) = parser.parse_args()

    if len(args) != 1:
        parser.print_help()
        return
    else:
        try:
            programName = args[0]
            program = open(programName, "r")
        except IOError:
            print "ARM Program %s does not exist" % programName
            return

    init(program, options)
Example #21
0
	def __init__(self):
		pygamesman.export(
			gInitialPosition = long(self.gInitialPosition),
			gNumberOfPositions = long(self.gNumberOfPositions),
			kBadPosition = long(self.kBadPosition),
			kGameSpecificMenu = bool(self.kGameSpecificMenu),
			kPartizan = bool(self.kPartizan),
			kDebugMenu = bool(self.kDebugMenu),
			kTieIsPossible = bool(self.kTieIsPossible),
			kLoopy = bool(self.kLoopy),
			kDebugDetermineValue = bool(self.kDebugDetermineValue),
			kAuthorName = str(self.kAuthorName),
			kGameName = str(self.kGameName),
			kHelpGraphicInterface = str(self.kHelpGraphicInterface),
			kHelpTextInterface = str(self.kHelpTextInterface),
			kHelpOnYourTurn = str(self.kHelpOnYourTurn),
			kHelpStandardObjective = str(self.kHelpStandardObjective),
			kHelpReverseObjective = str(self.kHelpReverseObjective),
			kHelpTieOccursWhen = str(self.kHelpTieOccursWhen),
			kHelpExample = str(self.kHelpExample),
			kDBName = str(self.kDBName))
		# Import psyco for JIT compilation, if available
		try:
			import psyco
			psyco.full()
		except ImportError:
			pass
		pygamesman.initialize(sys.argv, self.call)
Example #22
0
    def __init__(self, parent):
        self._init_ctrls(parent)
        psyco.full()
        self.laserscanner = HokuyoLaserScanner()
        self.localisation = Localisation(400)
        self.naofinder = NAOFinder(self.localisation)
        self.network = Network()
        
        ## control variables
        self.control = numpy.zeros(3)
        # automatic
        self.state = 'init'         # states: init, chase, position, lost
        self.statecount = 0
        self.targetnumber = 0
        #self.targets = [[250, -100], [250, 100], [50, 100], [50, -100]]
        #self.targets = [[275, -10], [275, 10], [50, 10], [50, -10]]
        self.targets = [[275, 0], [50, 0]]

        # manual
        self.up = False             # set these to true when the key is pressed!
        self.down = False
        self.left = False
        self.right = False
        
        self.distance = 0
        self.bearing = 0
        self.orientation = 0
        
        self.CartesianPanel.setNaoFinder(self.naofinder)
        self.NaoPanel.setNaoFinder(self.naofinder)
        self.NaoPanel.setLocalisation(self.localisation)
        self.closed = False
Example #23
0
def main():
    ''' Main test script
    '''
    try:
        import psyco
        psyco.full()
    except ImportError:
        pass
Example #24
0
def start():
    
    import garlicsim
    import garlicsim_wx
    
    if use_psyco:
        psyco.full()
    garlicsim_wx.start()
Example #25
0
def use_psyco():
    """Use Psyco (if available) to speed things up."""
    try:
        import psyco

        psyco.full()  # pragma: nocover
    except ImportError:
        pass
Example #26
0
def install_psyco():
    """ 使用psyco包,提高速度,但在linux下,很耗内存 """
    try:
        import psyco
        psyco.full()
        log('***psyco installed.')
    except ImportError:
        pass
Example #27
0
def main():
  try:
    import psyco
    psyco.full()
  except:
    errlog.warn("psyco not available -- the server will be more efficient if psyco is installed")
  x = SwitzerlandMasterServer(SwitzerlandConfig(getopt=True))
  x.accept_connections()
Example #28
0
def main():
        try:
                import psyco
                psyco.full()
        except ImportError:
                pass
                
        unittest.main()
Example #29
0
    def __init__(self, buff) :
        try :
            import psyco
            psyco.full()
        except ImportError :
            pass

        self.__buff = buff
        self.__idx = 0
Example #30
0
def main():
	# initialize psyco
	try:
		import psyco
		psyco.full()
	except ImportError: pass
	# main loop
	Application().MainLoop()
	prefs.Commit()
Example #31
0
def main():
    global opts, extra

    parser = optparse.OptionParser()
    pathGroup = optparse.OptionGroup(
        parser, "Path Arguments",
        r"All path arguments must be absolute paths and use either forward slashes (/) or two backward slashes (\\). All of these can also be set in the ini (where  you can also use relative paths) and if set in both cmd line takes precedence."
    )
    pathGroup.add_option(
        '-o',
        '--falloutPath',
        action='store',
        type='string',
        default='',
        dest='falloutPath',
        help=
        'Specifies the FalloutNV directory (the one containing FalloutNV.exe). Use this argument if Bash is located outside of the FalloutNV directory.'
    )
    userPathGroup = optparse.OptionGroup(
        parser, "'User Directory Arguments",
        'These arguments allow you to specify your user directories in several ways.'
        ' These are only useful if the regular procedure for getting the user directory fails.'
        ' And even in that case, the user is probably better off installing win32com.'
    )
    userPathGroup.add_option(
        '-p',
        '--personalPath',
        action='store',
        type='string',
        default='',
        dest='personalPath',
        help=
        'Specify the user\'s personal directory. (Like "C:\\\\Documents and Settings\\\\Wrye\\\\My Documents\") '
        'If you need to set this then you probably need to set -l too')
    userPathGroup.add_option(
        '-u',
        '--userPath',
        action='store',
        type='string',
        default='',
        dest='userPath',
        help=
        'Specify the user profile path. May help if HOMEDRIVE and/or HOMEPATH'
        ' are missing from the user\'s environment')
    userPathGroup.add_option(
        '-l',
        '--localAppDataPath',
        action='store',
        type='string',
        default='',
        dest='localAppDataPath',
        help='Specify the user\'s local application data directory.'
        'If you need to set this then you probably need to set -p too.')
    backupGroup = optparse.OptionGroup(
        parser, "'Backup and Restore Arguments",
        'These arguments allow you to do backup and restore settings operations.'
    )
    backupGroup.add_option(
        '-b',
        '--backup',
        action='store_true',
        default=False,
        dest='backup',
        help=
        'Backup all Bash settings to an archive file before the app launches. Either specify the filepath with  the -f/--filename options or Wrye Bash will prompt the user for the backup file path.'
    )
    backupGroup.add_option(
        '-r',
        '--restore',
        action='store_true',
        default=False,
        dest='restore',
        help=
        'Backup all Bash settings to an archive file before the app launches. Either specify the filepath with  the -f/--filename options or Wrye Bash will prompt the user for the backup file path.'
    )
    backupGroup.add_option(
        '-f',
        '--filename',
        action='store',
        default='',
        dest='filename',
        help=
        'The file to use with the -r or -b options. Must end in \'.7z\' and be a valid path and for -r exist and for -b not already exist.'
    )
    backupGroup.add_option(
        '-q',
        '--quiet-quit',
        action='store_true',
        default=False,
        dest='quietquit',
        help=
        'Close Bash after creating or restoring backup and do not display any prompts or message dialogs.'
    )
    parser.set_defaults(backup_images=0)
    backupGroup.add_option(
        '-i',
        '--include-changed-images',
        action='store_const',
        const=1,
        dest='backup_images',
        help=
        'Include changed images from mopy/bash/images in the backup. Include any image(s) from backup file in restore.'
    )
    backupGroup.add_option(
        '-I',
        '--include-all-images',
        action='store_const',
        const=2,
        dest='backup_images',
        help=
        'Include all images from mopy/bash/images in the backup/restore (if present in backup file).'
    )
    parser.add_option(
        '-d',
        '--debug',
        action='store_true',
        default=False,
        dest='debug',
        help=
        'Useful if bash is crashing on startup or if you want to print a lot of '
        'information (e.g. while developing or debugging).')
    parser.add_option('--no-psyco',
                      action='store_false',
                      default=True,
                      dest='Psyco',
                      help='Disables import of Psyco')
    parser.set_defaults(mode=0)
    parser.add_option(
        '-C',
        '--Cbash-mode',
        action='store_const',
        const=2,
        dest='mode',
        help='enables CBash and uses CBash to build bashed patch.')
    parser.add_option(
        '-P',
        '--Python-mode',
        action='store_const',
        const=1,
        dest='mode',
        help='disables CBash and uses python code to build bashed patch.')
    parser.set_defaults(unicode='')
    parser.add_option(
        '-U',
        '--Unicode',
        action='store_true',
        dest='unicode',
        help='enables Unicode mode, overriding the ini if it exists.')
    parser.add_option(
        '-A',
        '--Ansi',
        action='store_false',
        dest='unicode',
        help='disables Unicode mode, overriding the ini if it exists.')
    parser.add_option('--restarting',
                      action='store_true',
                      default=False,
                      dest='restarting',
                      help=optparse.SUPPRESS_HELP)
    parser.add_option('--genHtml', default=None, help=optparse.SUPPRESS_HELP)

    parser.add_option_group(pathGroup)
    parser.add_option_group(userPathGroup)
    parser.add_option_group(backupGroup)

    opts, extra = parser.parse_args()
    if len(extra) > 0:
        parser.print_help()
        return

    bolt.deprintOn = opts.debug

    if opts.Psyco:
        try:
            import psyco
            psyco.full()
        except:
            pass
    if opts.unicode != '':
        bolt.bUseUnicode = int(opts.unicode)
    #--Initialize Directories and some settings
    #  required before the rest has imported
    SetUserPath('bash.ini', opts.userPath)

    try:
        bolt.CBash = opts.mode
        import bosh
        bosh.initBosh(opts.personalPath, opts.localAppDataPath,
                      opts.falloutPath)
        bosh.exe7z = bosh.dirs['compiled'].join(bosh.exe7z).s

        # if HTML file generation was requested, just do it and quit
        if opts.genHtml is not None:
            print "generating HTML file from: '%s'" % opts.genHtml
            import belt
            bolt.WryeText.genHtml(opts.genHtml)
            print "done"
            return

        import basher
        import barb
        import balt
    except bolt.PermissionError, e:
        if opts.debug:
            if hasattr(sys, 'frozen'):
                app = basher.BashApp()
            else:
                app = basher.BashApp(False)
            bolt.deprintOn = True
        else:
            app = basher.BashApp()
        balt.showError(None, str(e))
        app.MainLoop()
        raise
Example #32
0
#!/usr/bin/python
import sys, psyco
from bisect import bisect
psyco.full()


def conv(times, T):
    for i, v in enumerate(times):
        times[i] = [int(x) for x in v.replace(":", " ").split()]
        times[i] = ( times[i][0]*60 + times[i][1], \
            times[i][2]*60 + times[i][3] + T )
        #if times[i][1] > 1440: del times[i]


def train(t1, t2):
    #print "trainCall!"
    p1, p2 = t1, t2
    j = 0
    i = 0
    f = "A"
    while 0 <= j < len(p1):
        t = p1[j]
        del p1[j]
        j = bisect(p2, (t[1], 0))
        p1, p2 = p2, p1

        #debug
        if f == "A":
            f = "B"
        else:
            f = "A"
Example #33
0
class CommandInterface:
    def open(self, aport='COM21', abaudrate=115200) :
        self.sp = serial.Serial(
            port=aport,
            baudrate=abaudrate,     # baudrate
            bytesize=8,             # number of databits
            parity=serial.PARITY_NONE,
            stopbits=1,
            xonxoff=0,              # enable software flow control
            rtscts=0,               # disable RTS/CTS flow control
            timeout=5               # set a timeout value, None for waiting forever
        )


    def _wait_for_ask(self, info = ""):
        # wait for ask
        try:
            ask = ord(self.sp.read())
        except:
            raise CmdException("Can't read port or timeout")
        else:
            if ask == 0x79:
                # ACK
                return 1
            else:
                if ask == 0x1F:
                    # NACK
                    raise CmdException("NACK "+info)
                else:
                    # Unknow responce
                    raise CmdException("Unknow response. "+info+": "+hex(ask))


    def reset(self):
        self.sp.setDTR(0)
        time.sleep(0.1)
        self.sp.setDTR(1)
        time.sleep(0.5)

    def initChip(self):
        # Set boot
        self.sp.setRTS(0)
        self.reset()
#        self.sp.write("a")
#        data = self.sp.read(69)
#        print "Readback" +data
#        self.sp.write("\x7F")       # Syncro
#        return self._wait_for_ask("Syncro")

    def releaseChip(self):
        self.sp.setRTS(1)
        self.reset()

    def cmdGeneric(self, cmd):
        self.sp.write(chr(cmd))
        self.sp.write(chr(cmd ^ 0xFF)) # Control byte
        return self._wait_for_ask(hex(cmd))

    def cmdGet(self):
        if self.cmdGeneric(0x00):
            mdebug(10, "*** Get command");
            len = ord(self.sp.read())
            version = ord(self.sp.read())
            mdebug(10, "    Bootloader version: "+hex(version))
            dat = map(lambda c: hex(ord(c)), self.sp.read(len))
            mdebug(10, "    Available commands: "+str(dat))
            self._wait_for_ask("0x00 end")
            return version
        else:
            raise CmdException("Get (0x00) failed")

    def cmdGetVersion(self):
        if self.cmdGeneric(0x01):
            mdebug(10, "*** GetVersion command")
            version = ord(self.sp.read())
            self.sp.read(2)
            self._wait_for_ask("0x01 end")
            mdebug(10, "    Bootloader version: "+hex(version))
            return version
        else:
            raise CmdException("GetVersion (0x01) failed")

    def cmdGetID(self):
        if self.cmdGeneric(0x02):
            mdebug(10, "*** GetID command")
            len = ord(self.sp.read())
            id = self.sp.read(len+1)
            self._wait_for_ask("0x02 end")
            return id
        else:
            raise CmdException("GetID (0x02) failed")


    def _encode_addr(self, addr):
        byte3 = (addr >> 0) & 0xFF
        byte2 = (addr >> 8) & 0xFF
        byte1 = (addr >> 16) & 0xFF
        byte0 = (addr >> 24) & 0xFF
        crc = byte0 ^ byte1 ^ byte2 ^ byte3
        return (chr(byte0) + chr(byte1) + chr(byte2) + chr(byte3) + chr(crc))


    def cmdReadMemory(self, addr, lng):
        assert(lng <= 256)
        if self.cmdGeneric(0x11):
            mdebug(10, "*** ReadMemory command")
            self.sp.write(self._encode_addr(addr))
            self._wait_for_ask("0x11 address failed")
            N = (lng - 1) & 0xFF
            crc = N ^ 0xFF
            self.sp.write(chr(N) + chr(crc))
            self._wait_for_ask("0x11 length failed")
            return map(lambda c: ord(c), self.sp.read(lng))
        else:
            raise CmdException("ReadMemory (0x11) failed")


    def cmdGo(self, addr):
        if self.cmdGeneric(0x21):
            mdebug(10, "*** Go command")
            self.sp.write(self._encode_addr(addr))
            self._wait_for_ask("0x21 go failed")
        else:
            raise CmdException("Go (0x21) failed")


    def cmdWriteMemory(self, addr, data):
        assert(len(data) <= 256)
        if self.cmdGeneric(0x31):
            mdebug(10, "*** Write memory command")
            self.sp.write(self._encode_addr(addr))
            self._wait_for_ask("0x31 address failed")
            #map(lambda c: hex(ord(c)), data)
            lng = (len(data)-1) & 0xFF
            mdebug(10, "    %s bytes to write" % [lng+1]);
            self.sp.write(chr(lng)) # len really
            crc = 0xFF
            for c in data:
                crc = crc ^ c
                self.sp.write(chr(c))
            self.sp.write(chr(crc))
            self._wait_for_ask("0x31 programming failed")
            mdebug(10, "    Write memory done")
        else:
            raise CmdException("Write memory (0x31) failed")

	
    def cmdEraseMemory(self, sectors = None):
        if self.cmdGeneric(0x43):
            mdebug(10, "*** Erase memory command")
            if sectors is None:
                # Global erase
                self.sp.write(chr(0xFF))
                self.sp.write(chr(0x00))
            else:
                # Sectors erase
                self.sp.write(chr((len(sectors)-1) & 0xFF))
                crc = 0xFF
                for c in sectors:
                    crc = crc ^ c
                    self.sp.write(chr(c))
                self.sp.write(chr(crc))
            self._wait_for_ask("0x43 erasing failed")
            mdebug(10, "    Erase memory done")
        else:
            raise CmdException("Erase memory (0x43) failed")

    def cmdWriteProtect(self, sectors):
        if self.cmdGeneric(0x63):
            mdebug(10, "*** Write protect command")
            self.sp.write(chr((len(sectors)-1) & 0xFF))
            crc = 0xFF
            for c in sectors:
                crc = crc ^ c
                self.sp.write(chr(c))
            self.sp.write(chr(crc))
            self._wait_for_ask("0x63 write protect failed")
            mdebug(10, "    Write protect done")
        else:
            raise CmdException("Write Protect memory (0x63) failed")

    def cmdWriteUnprotect(self):
        if self.cmdGeneric(0x73):
            mdebug(10, "*** Write Unprotect command")
            self._wait_for_ask("0x73 write unprotect failed")
            self._wait_for_ask("0x73 write unprotect 2 failed")
            mdebug(10, "    Write Unprotect done")
        else:
            raise CmdException("Write Unprotect (0x73) failed")

    def cmdReadoutProtect(self):
        if self.cmdGeneric(0x82):
            mdebug(10, "*** Readout protect command")
            self._wait_for_ask("0x82 readout protect failed")
            self._wait_for_ask("0x82 readout protect 2 failed")
            mdebug(10, "    Read protect done")
        else:
            raise CmdException("Readout protect (0x82) failed")

    def cmdReadoutUnprotect(self):
        if self.cmdGeneric(0x92):
            mdebug(10, "*** Readout Unprotect command")
            self._wait_for_ask("0x92 readout unprotect failed")
            self._wait_for_ask("0x92 readout unprotect 2 failed")
            mdebug(10, "    Read Unprotect done")
        else:
            raise CmdException("Readout unprotect (0x92) failed")


# Complex commands section

    def readMemory(self, addr, lng):
        data = []
        if usepbar:
            widgets = ['Reading: ', Percentage(),', ', ETA(), ' ', Bar()]
            pbar = ProgressBar(widgets=widgets,maxval=lng, term_width=79).start()
        
        while lng > 256:
            if usepbar:
                pbar.update(pbar.maxval-lng)
            else:
                mdebug(5, "Read %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
            data = data + self.cmdReadMemory(addr, 256)
            addr = addr + 256
            lng = lng - 256
        if usepbar:
            pbar.update(pbar.maxval-lng)
            pbar.finish()
        else:
            mdebug(5, "Read %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
        data = data + self.cmdReadMemory(addr, lng)
        return data

    def writeMemory(self, addr, data):
        lng = len(data)
        mdebug(5,"File length %(len)d bytes" %{'len':lng})
        if usepbar:
            widgets = ['Writing: ', Percentage(),' ', ETA(), ' ', Bar()]
            pbar = ProgressBar(widgets=widgets, maxval=lng, term_width=79).start()
        
        offs = 0
        while lng > 256:
            if usepbar:
                pbar.update(pbar.maxval-lng)
            else:
                mdebug(5, "Write %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
            self.cmdWriteMemory(addr, data[offs:offs+256])
            offs = offs + 256
            addr = addr + 256
            lng = lng - 256
        if usepbar:
            pbar.update(pbar.maxval-lng)
            pbar.finish()
        else:
            mdebug(5, "Write %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
        self.cmdWriteMemory(addr, data[offs:offs+lng] + ([0xFF] * (256-lng)) )

	def uart_raw_write(self,data):
#		assert(len(data) <= 256)
		for c in data:
			self.sp.write(c)
			#self.sp.write(chr(c))
#			print "%s(%s)" %(chr(c),c)
		print "data write complete!"



	def __init__(self) :
        pass


def usage():
    print """Usage: %s [-hqVewvr] [-l length] [-p port] [-b baud] [-a addr] [file.bin]
    -h          This help
    -q          Quiet
    -V          Verbose
    -e          Erase
    -w          Write
    -v          Verify
    -r          Read
    -l length   Length of read
    -p port     Serial port (default: /dev/tty.usbserial-ftCYPMYJ)
    -b baud     Baud speed (default: 115200)
    -a addr     Target address

    ./stm32loader.py -e -w -v example/main.bin

    """ % sys.argv[0]


if __name__ == "__main__":
    
    # Import Psyco if available
    try:
        import psyco
        psyco.full()
        print "Using Psyco..."
    except ImportError:
        pass

    conf = {
            'port': 'COM21',
            'baud': 115200,
            'address': 0x00001000,
            'erase': 0,
            'write': 0,
            'verify': 0,
            'read': 0,
            'len': 1000,
            'fname':'',
        }

# http://www.python.org/doc/2.5.2/lib/module-getopt.html

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hqVewvrp:b:a:l:")
    except getopt.GetoptError, err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)

    QUIET = 5

    for o, a in opts:
        if o == '-V':
            QUIET = 10
        elif o == '-q':
            QUIET = 0
        elif o == '-h':
            usage()
            sys.exit(0)
        elif o == '-e':
            conf['erase'] = 1
        elif o == '-w':
            conf['write'] = 1
        elif o == '-v':
            conf['verify'] = 1
        elif o == '-r':
            conf['read'] = 1
        elif o == '-p':
            conf['port'] = a
        elif o == '-b':
            conf['baud'] = eval(a)
        elif o == '-a':
            conf['address'] = eval(a)
        elif o == '-l':
            conf['len'] = eval(a)
#        elif o == '-f':
#            conf['fname'] = a
        else:
            assert False, "unhandled option"

    cmd = CommandInterface()
    cmd.open(conf['port'], conf['baud'])
    mdebug(10, "Open port %(port)s, baud %(baud)d" % {'port':conf['port'], 'baud':conf['baud']})

    print args[0]
    data = map(lambda c: ord(c), file(args[0],'rb').read())
 	cmd.uart_raw_write(data)
def main():
  if os.name == "nt":
    full = 0
    double = 0
  else:
    full = 0
    double = 1

  displayFlags = HWSURFACE

  # Get commandline options
  if len(sys.argv)!= 1:
    for i in range(1, len(sys.argv)):
      if sys.argv[i].upper() == "--RESOLUTION":
        # Get the resolution
        if i != len(sys.argv)-1 and sys.argv[i+1].upper() == "640X480":
          misc.zoom = 0.625
        elif i != len(sys.argv)-1 and sys.argv[i+1].upper() == "320X240":
          misc.zoom = 0.3125
      if sys.argv[i].upper() == "--FULLSCREEN":
        full = 1
      if sys.argv[i].upper() == "--DOUBLEBUF":
        double = 1
      if sys.argv[i].upper() == "--NODOUBLEBUF":
        double = 0
      if sys.argv[i].upper() == "--NOSOUND":
        misc.music = 0
      if sys.argv[i].upper() == "--HELP" or sys.argv[i].upper() == "-H":
        print("USAGE: Speedlust.py [--resolution 640x480|320x240] [--fullscreen] [--doublebuf|--nodoublebuf] [--nosound] [--help|-h] [--version]")
        print()
        print("  --resolution   Change resolution (default is 1024x768)")
        print( "  --fullscreen   Enable fullscreen display")
        print("  --doublebuf    Enable double buffering display (DEFAULT on other platform than Windows)")
        print("  --nodoublebuf  Disable double buffering display (DEFAULT on Windows)")
        print("  --nosound      Disable Sound")
        print("  --help|-h      Display this help and exit")
        print("  --version      Output version information and exit")
        sys.exit(0)
      if sys.argv[i].upper() == "--VERSION":
        print("Speedlust version " + misc.VERSION + ", Copyright (C) 2018 Harshit <*****@*****.**>")
        print()
        print("Speedlust comes with ABSOLUTELY NO WARRANTY.")
        print("This is free software, and you are welcome to redistribute it")
        print("under certain conditions; see the COPYING file for details.")
        sys.exit(0)
      
  if full == 1 and double == 1:
    displayFlags = displayFlags|DOUBLEBUF|FULLSCREEN
  elif full == 1 and double == 0:
    displayFlags = displayFlags|FULLSCREEN
  elif full == 0 and double == 1:
    displayFlags = displayFlags|DOUBLEBUF
  elif full == 0 and double == 0:
    displayFlags = displayFlags

  try:
    pygame.init()
  except:
    print("Cannot initialize pyGame:")
    sys.exit(-1)

  if pygame.display.mode_ok((int(1024*misc.zoom), int(768*misc.zoom)), displayFlags, 24) == 0:
     print("Speedlust cannot initialize display...")
     sys.exit(-1)
  else:
    misc.screen = pygame.display.set_mode((int(1024*misc.zoom), int(768*misc.zoom)), displayFlags, 24)

  pygame.display.set_caption("Speedlust v" + misc.VERSION)
  pygame.display.set_icon(pygame.image.load(os.path.join("sprites", "SpeedlustIcon.bmp")))

  if misc.music == 1:
    pygame.mixer.music.load(os.path.join("sounds", "start.ogg"))
    pygame.mixer.music.play()

  try:
    import psyco
    psyco.full() 
  except:
    print("Cannot use psyCo...")
    pass
  
  pygame.mouse.set_visible(0)

  misc.init()

  select1 = 1

  while select1 != -1:
    menu1 = menu.SimpleMenu(misc.titleFont, "Speedlust v" + misc.VERSION, 20*misc.zoom, misc.itemFont, ["Single Race", "Tournament", "Hi Scores", "Credits", "License"])
    select1 = menu1.getInput()

    # Single Race
    if select1 == 1:
      race = game.Game("singleRace")

      menu2 = menu.ChooseTrackMenu(misc.titleFont, "singleRace: Track", 2*misc.zoom, misc.itemFont)
      select2 = menu2.getInput()
      if select2 != -1:
        race.listTrackName = [[select2[0], select2[1]] ]

        menu3 = menu.ChooseValueMenu(misc.titleFont, "singleRace: Laps", 0, misc.itemFont, 1, 10)
        select3 = menu3.getInput()
        if select3 != -1:
          race.maxLapNb = select3

          menu4 = menu.ChooseValueMenu(misc.titleFont, "singleRace: HumanPlayers", 0, misc.itemFont, 0, 4)
          select4 = menu4.getInput()
          if select4 != -1:

            isExit = 0
            race.listPlayer = []
            for i in range(1, select4+1):
              menu5 = menu.ChooseHumanPlayerMenu(misc.titleFont, "singleRace: HumanPlayer" + str(i), 5*misc.zoom, misc.itemFont)
              thePlayer = menu5.getInput()
              if thePlayer == -1:
                isExit = 1
                break
              race.listPlayer.append(thePlayer)

            # If there's no exit during enter of player
            if isExit == 0:
              # If there's no Human player, there should exist at least a Bot player
              if select4 == 0:
                minBot = 1
              else:
                minBot = 0
              menu6 = menu.ChooseValueMenu(misc.titleFont, "singleRace: RobotPlayers", 0, misc.itemFont, minBot, 4)
              select6 = menu6.getInput()
              if select6 != -1:
                isExit = 0
                for i in range(1, select6+1):
                  menu7 = menu.ChooseRobotPlayerMenu(misc.titleFont, "singleRace: RobotPlayer" + str(i), 5*misc.zoom, misc.itemFont)
                  thePlayer = menu7.getInput()
                  if thePlayer == -1:
                    isExit = 1
                    break
                  race.listPlayer.append(thePlayer)
 
                # If there's no exit during enter of player
                if isExit == 0:
                  race.play()

    # Tournament
    elif select1 == 2:
      tournament = game.Game("tournament")

      tournament.listTrackName = []

      # Get all tracks to put in the tournament
      listAvailableTrackNames = track.getAvailableTrackNames()

      for trackName in listAvailableTrackNames:
        tournament.listTrackName.append([trackName, 0])

      # Also Reverse tracks
      for trackName in listAvailableTrackNames:
        tournament.listTrackName.append([trackName, 1])

      menu2 = menu.ChooseValueMenu(misc.titleFont, "tournament: Laps", 0, misc.itemFont,1 ,10)
      select2 = menu2.getInput()
      if select2 != -1:
        tournament.maxLapNb = select2

        menu3 = menu.ChooseValueMenu(misc.titleFont, "tournament: HumanPlayers", 0, misc.itemFont, 0, 4)
        select3 = menu3.getInput()
        if select3 != -1:

          isExit = 0
          tournament.listPlayer = []
          for i in range(1, select3+1):
            menu4 = menu.ChooseHumanPlayerMenu(misc.titleFont, "tournament: HumanPlayer" + str(i), 5*misc.zoom, misc.itemFont)
            thePlayer = menu4.getInput()
            if thePlayer == -1:
              isExit = 1
              break
            tournament.listPlayer.append(thePlayer)

          # If there's no exit during enter of player
          if isExit == 0:
            # If there's no Human player, there should exist at least a Bot player
            if select3 == 0:
              minBot = 1
            else:
              minBot = 0
            menu6 = menu.ChooseValueMenu(misc.titleFont, "tournament: RobotPlayers", 0, misc.itemFont, minBot, 4)
            select6 = menu6.getInput()
            if select6 != -1:
              isExit = 0
              for i in range(1, select6+1):
                menu7 = menu.ChooseRobotPlayerMenu(misc.titleFont, "tournament: RobotPlayer" + str(i), 5*misc.zoom, misc.itemFont)
                thePlayer = menu7.getInput()
                if thePlayer == -1:
                  isExit = 1
                  break
                tournament.listPlayer.append(thePlayer)

           
          # If there's no exit during enter of player
          if isExit == 0:
            tournament.play()

    elif select1 == 3:
      hiscoresMenu = menu.MenuHiscores(misc.titleFont, "hiscores", 10*misc.zoom, misc.smallItemFont)
      hiscoresMenu.getInput()
    elif select1 == 4:
      creditsMenu = menu.MenuCredits(misc.titleFont, "credits", 10*misc.zoom, misc.itemFont)
      misc.wait4Key()
    elif select1 == 5:
      licenseMenu = menu.MenuLicense(misc.titleFont, "license", 10*misc.zoom, misc.smallItemFont)
      misc.wait4Key()
Example #35
0
def main(argv):
    usage = "Usage: %prog [options] --map_file <map file>  bot1 ... botN\n\nYou must specify a map file."
    parser = OptionParser(usage=usage)

    # map to be played
    # number of players is determined by the map file
    parser.add_option("-m",
                      "--map_file",
                      dest="map",
                      help="Name of the map file")

    # maximum number of turns that the game will be played
    parser.add_option("-t",
                      "--turns",
                      dest="turns",
                      default=1000,
                      type="int",
                      help="Number of turns in the game")

    parser.add_option("--serial",
                      dest="serial",
                      action="store_true",
                      help="Run bots in serial, instead of parallel.")

    parser.add_option("--turntime",
                      dest="turntime",
                      default=1000,
                      type="int",
                      help="Amount of time to give each bot, in milliseconds")
    parser.add_option("--loadtime",
                      dest="loadtime",
                      default=3000,
                      type="int",
                      help="Amount of time to give for load, in milliseconds")
    parser.add_option("-r",
                      "--rounds",
                      dest="rounds",
                      default=1,
                      type="int",
                      help="Number of rounds to play")
    parser.add_option("--player_seed",
                      dest="player_seed",
                      default=None,
                      type="int",
                      help="Player seed for the random number generator")
    parser.add_option("--engine_seed",
                      dest="engine_seed",
                      default=None,
                      type="int",
                      help="Engine seed for the random number generator")

    parser.add_option('--strict',
                      dest='strict',
                      action='store_true',
                      default=False,
                      help='Strict mode enforces valid moves for bots')
    parser.add_option('--capture_errors',
                      dest='capture_errors',
                      action='store_true',
                      default=False,
                      help='Capture errors and stderr in game result')
    parser.add_option('--end_wait',
                      dest='end_wait',
                      default=0,
                      type="float",
                      help='Seconds to wait at end for bots to process end')
    parser.add_option('--secure_jail',
                      dest='secure_jail',
                      action='store_true',
                      default=False,
                      help='Use the secure jail for each bot (*nix only)')
    parser.add_option(
        '--fill',
        dest='fill',
        action='store_true',
        default=False,
        help='Fill up extra player starts with last bot specified')
    parser.add_option('-p',
                      '--position',
                      dest='position',
                      default=0,
                      type='int',
                      help='Player position for first bot specified')

    # asteroids specific game options
    game_group = OptionGroup(
        parser, "Game Options",
        "Options that affect the game mechanics for asteroids")
    game_group.add_option("--kill_points",
                          dest="kill_points",
                          default=2,
                          type="int",
                          help="Points awarded for killing a hill")
    game_group.add_option(
        "--cutoff_turn",
        dest="cutoff_turn",
        type="int",
        default=150,
        help="Number of turns cutoff percentage is maintained to end game early"
    )
    game_group.add_option(
        "--cutoff_percent",
        dest="cutoff_percent",
        type="float",
        default=0.85,
        help="Number of turns cutoff percentage is maintained to end game early"
    )
    game_group.add_option("--scenario",
                          dest="scenario",
                          action='store_true',
                          default=False)
    parser.add_option_group(game_group)

    # the log directory must be specified for any logging to occur, except:
    #    bot errors to stderr
    #    verbose levels 1 & 2 to stdout and stderr
    #    profiling to stderr
    # the log directory will contain
    #    the replay or stream file used by the visualizer, if requested
    #    the bot input/output/error logs, if requested
    log_group = OptionGroup(parser, "Logging Options",
                            "Options that control the logging")
    log_group.add_option("-g",
                         "--game",
                         dest="game_id",
                         default=0,
                         type='int',
                         help="game id to start at when numbering log files")
    log_group.add_option("-l",
                         "--log_dir",
                         dest="log_dir",
                         default=None,
                         help="Directory to dump replay files to.")
    log_group.add_option('-R',
                         '--log_replay',
                         dest='log_replay',
                         action='store_true',
                         default=False),
    log_group.add_option('-S',
                         '--log_stream',
                         dest='log_stream',
                         action='store_true',
                         default=False),
    log_group.add_option("-I",
                         "--log_input",
                         dest="log_input",
                         action="store_true",
                         default=False,
                         help="Log input streams sent to bots")
    log_group.add_option("-O",
                         "--log_output",
                         dest="log_output",
                         action="store_true",
                         default=False,
                         help="Log output streams from bots")
    log_group.add_option("-E",
                         "--log_error",
                         dest="log_error",
                         action="store_true",
                         default=False,
                         help="log error streams from bots")
    log_group.add_option('-e',
                         '--log_stderr',
                         dest='log_stderr',
                         action='store_true',
                         default=False,
                         help='additionally log bot errors to stderr')
    log_group.add_option('-o',
                         '--log_stdout',
                         dest='log_stdout',
                         action='store_true',
                         default=False,
                         help='additionally log replay/stream to stdout')
    # verbose will not print bot input/output/errors
    # only info+debug will print bot error output
    log_group.add_option("-v",
                         "--verbose",
                         dest="verbose",
                         action='store_true',
                         default=False,
                         help="Print out status as game goes.")
    log_group.add_option("--profile",
                         dest="profile",
                         action="store_true",
                         default=False,
                         help="Run under the python profiler")
    parser.add_option("--nolaunch",
                      dest="nolaunch",
                      action='store_true',
                      default=False,
                      help="Prevent visualizer from launching")
    log_group.add_option("--html",
                         dest="html_file",
                         default=None,
                         help="Output file name for an html replay")
    parser.add_option_group(log_group)

    (opts, args) = parser.parse_args(argv)
    if opts.map is None or not os.path.exists(opts.map):
        parser.print_help()
        return -1
    try:
        if opts.profile:
            # put profile file into output dir if we can
            prof_file = "asteroids.profile"
            if opts.log_dir:
                prof_file = os.path.join(opts.log_dir, prof_file)
            # cProfile needs to be explitly told about out local and global context
            print("Running profile and outputting to {0}".format(prof_file, ),
                  file=stderr)
            cProfile.runctx("run_rounds(opts,args)", globals(), locals(),
                            prof_file)
        else:
            # only use psyco if we are not profiling
            # (psyco messes with profiling)
            try:
                import psyco
                psyco.full()
            except ImportError:
                pass
            run_rounds(opts, args)
        return 0
    except Exception:
        traceback.print_exc()
        return -1
    v = motion.getJointVelocityGlobal(0, lastFrame-finiteDiff, lastFrame)
    a = motion.getJointAccelerationGlobal(0, lastFrame-finiteDiff, lastFrame)
    t = 1/motion.fps

    # integration
    extended = ym.JointMotion([motion[-1].copy() for i in range(extendLength)])
    for i in range(extendLength):
        p += v * t
        v += a * t
        extended[i].rootPos = p.copy()
        extended[i].updateGlobalT()

    return extended

if __name__=='__main__':
    import psyco; psyco.full()
    from fltk import *
    import Motion.ysMotion as ym
    import Resource.ysMotionLoader as yf
    import Renderer.ysRenderer as yr
    import GUI.ysSimpleViewer as ysv


    def test_repeatCycle():
        bvhFilePath = '../samples/wd2_WalkSameSame00.bvh'
        jointMotion = yf.readBvhFile(bvhFilePath, .01)

#        bvhFilePath = '../samples/wd2_n_kick.bvh'
#        jointMotion = yf.readBvhFile(bvhFilePath, .01*2.53)
        
        lFoot = jointMotion[0].skeleton.getElementIndex('LeftFoot')
Example #37
0
    def __init__(self, content, logger, key_set):
##============================================================================
        self.version = '0.0.1a'
        self.objects = []
        self.logger = logger
        self.logger.log.info('Init Game and Game Screen.')
        self.debug_level = 'debug'  # prints errors verbosely to the game screen
                                    # On release, just a confirmation menu
                                    # Also affects the use of the python interpreter
                                    # in the console, disabled on release

        '''try:
            self.logger.log.debug('Init gEngine...')
            import cEngine as gEngine  # Try importing the pyd
            self.logger.log.debug('gEngine pyd/so imported')
        except ImportError, err:  # if that fails, import the python prototype
            sys.path.append(os.path.join(sys.path[0], 'gEngine'))
            self.logger.log.debug('gEngine pyd/so import failed, using python prototype')
            self.logger.log.exception(err)
            import gEngine.gEngine as gEngine'''
        import gEngine.gEngine as gEngine
            
        try:
            self.logger.log.debug("Importing Psyco.")
            import psyco
            psyco.full()
            psyco.log()
            psyco.profile()
            self.logger.log.debug('Psyco full used.')
        except ImportError:
            self.logger.log.debug("Importing Psyco failed.")
            pass

        #libtcod.console_set_keyboard_repeat(250,250)
        self.gEngine = gEngine.gEngine(SCREEN_WIDTH, SCREEN_HEIGHT, 'Ascension 0.0.1a', False, LIMIT_FPS)
        try:
            font = os.path.join(sys.path[0], 'terminal10x10_gs_tc.png')
            self.gEngine.console_set_custom_font(font, libtcod.FONT_LAYOUT_TCOD | libtcod.FONT_TYPE_GREYSCALE)
        except:
            pass
        self.gEngine.init_root()
        self.con = self.gEngine.console_new(MAP_WIDTH, MAP_HEIGHT)
        self.panel = self.gEngine.console_new(SCREEN_WIDTH, PANEL_HEIGHT)

        self.toolbar = self.gEngine.console_new(SCREEN_WIDTH, 5)

        x = 32/2
        x = SCREEN_WIDTH/2 - x
        self.hotbar = HotBar(x, 0, self.gEngine, self.toolbar)
        z=1
        index = ord('1')
        for i in range(10):
            if index == ord(':'):
                index = ord('0')
            s = HotBarSlot(None, z+x, PANEL_Y-4, z, chr(index), self.gEngine)
            self.hotbar.add_slot(s)
            z += 3
            index += 1
        self.message = Message(self.panel, MSG_HEIGHT, MSG_WIDTH, MSG_X, self.logger, self.debug_level)
        self.build_objects = GameObjects(content)        
        self.ticker = Ticker()
        
        self.Map = map.Map(MAP_HEIGHT, MAP_WIDTH, ROOM_MIN_SIZE, ROOM_MAX_SIZE,
            MAX_ROOMS, MAX_ROOM_MONSTERS, MAX_ROOM_ITEMS, self.logger)

        self.keys = key_set
        self.setup_keys()
        self.current_dungeon = []  # an array that holds all off the dungeon levels
        #self.console = console.Console(self, SCREEN_WIDTH-2, SCREEN_HEIGHT/2, self.debug_level)
        self.depth = None
        self.game_state = None
        self.dev_mode = dev_mode.DevMode(self.gEngine, self.Map)

        #libtcod.console_set_keyboard_repeat(50, 50)
        libtcod.sys_set_renderer(libtcod.RENDERER_GLSL)
Example #38
0
def main():

    locale.setlocale(locale.LC_ALL, "")

    # Get defaults for command line options from global config.
    cfgsec = pology_config.section("pomtrans")

    showservs = list()
    showservs.sort()

    # Setup options and parse the command line.
    usage = _("@info command usage",
              "%(cmd)s [OPTIONS] TRANSERV PATHS...",
              cmd="%prog")
    desc = _("@info command description",
             "Perform machine translation of PO files.")
    ver = _("@info command version", u"%(cmd)s (Pology) %(version)s\n"
            u"Copyright © 2009, 2010 "
            u"Chusslove Illich (Часлав Илић) &lt;%(email)s&gt;",
            cmd="%prog",
            version=version(),
            email="*****@*****.**")

    opars = ColorOptionParser(usage=usage, description=desc, version=ver)
    opars.add_option("-a",
                     "--accelerator",
                     dest="accel",
                     metavar=_("@info command line value placeholder", "CHAR"),
                     help=_(
                         "@info command line option description",
                         "Accelerator marker character used in messages. "
                         "Detected from catalogs if not given."))
    opars.add_option("-c",
                     "--parallel-compendium",
                     dest="parcomp",
                     metavar=_("@info command line value placeholder", "FILE"),
                     help=_(
                         "@info command line option description",
                         "Translate from translation to another language, "
                         "found in compendium file at the given path."))
    opars.add_option("-l",
                     "--list-transervs",
                     action="store_true",
                     dest="list_transervs",
                     default=False,
                     help="List available translation services.")
    opars.add_option("-m",
                     "--flag-%s" % _flag_mtrans,
                     action="store_true",
                     dest="flag_mtrans",
                     default=False,
                     help=_("@info command line option description",
                            "Add '%(flag)s' flag to translated messages.",
                            flag=_flag_mtrans))
    opars.add_option(
        "-M",
        "--translation-mode",
        dest="tmode",
        metavar=_("@info command line value placeholder", "MODE"),
        help=_(
            "@info command line option description",
            "Translation mode for the chosen translation service. "
            "Overrides the default translation mode constructed "
            "based on source and target language. "
            "Mode string format is translation service dependent."))
    opars.add_option("-n",
                     "--no-fuzzy-flag",
                     action="store_false",
                     dest="flag_fuzzy",
                     default=True,
                     help=_(
                         "@info command line option description",
                         "Do not add '%(flag)s' flag to translated messages.",
                         flag="fuzzy"))
    opars.add_option(
        "-p",
        "--parallel-catalogs",
        dest="parcats",
        metavar=_("@info command line value placeholder", "SEARCH:REPLACE"),
        help=_(
            "@info command line option description",
            "Translate from translation to another language "
            "found in parallel catalogs. "
            "For given target catalog path, the path to parallel catalog "
            "is constructed by replacing once SEARCH with REPLACE."))
    opars.add_option("-s",
                     "--source-lang",
                     dest="slang",
                     metavar=_("@info command line value placeholder", "LANG"),
                     help=_(
                         "@info command line option description",
                         "Source language code. "
                         "Detected from catalogs if not given."))
    opars.add_option("-t",
                     "--target-lang",
                     dest="tlang",
                     metavar=_("@info command line value placeholder", "LANG"),
                     help=_(
                         "@info command line option description",
                         "Target language code. "
                         "Detected from catalogs if not given."))
    opars.add_option("-T",
                     "--transerv-bin",
                     dest="transerv_bin",
                     metavar=_("@info command line value placeholder", "PATH"),
                     help=_(
                         "@info command line option description",
                         "Custom path to translation service executable "
                         "(where applicable)."))
    opars.add_option(
        "-d",
        "--data-directory",
        dest="data_directory",
        metavar=_("@info command line value placeholder", "FOLDER"),
        help=_(
            "@info command line option description",
            "Custom path to a translation data directory (where applicable)."))

    (op, free_args) = opars.parse_args(str_to_unicode(sys.argv[1:]))

    # Could use some speedup.
    try:
        import psyco
        psyco.full()
    except ImportError:
        pass

    if op.list_transervs:
        report("\n".join(sorted(_known_transervs.keys())))
        sys.exit(0)

    if len(free_args) < 1:
        error(_("@info", "Translation service not specified."))
    transervkey = free_args.pop(0)
    if transervkey not in _known_transervs:
        error(
            _("@info",
              "Translation service '%(serv)s' not known.",
              serv=transervkey))

    tsbuilder_wopts = _known_transervs[transervkey]
    tsbuilder = lambda slang, tlang: tsbuilder_wopts(slang, tlang, op)

    paths = free_args
    if not op.parcomp and not op.parcats:
        translate_direct(paths, tsbuilder, op)
    else:
        translate_parallel(paths, tsbuilder, op)
Example #39
0
				if r.files is None or r.files=='*':
					# this is a special case meaning "everything", including all directories and subdirectories
					r.files=[f.path for f in ez.getAll()]
					r.files.append(ez.path)
				elif r.files.find('*')>=0 or r.files.find('?')>=0:
					r.files=[f.path for f in ez.glob(r.files)]
				else:
					r.files=[r.files]
				#print 'FILES IN SET:',r.files
		# do the replacement!
		ez.walk(self._replaceFileWalker,context=None,algo='DEAPTH-FIRST')


if __name__ == '__main__':
	import sys
	# Use the Psyco python accelerator if available
	# See:
	# 	http://psyco.sourceforge.net
	try:
		import psyco
		psyco.full() # accelerate this program
	except ImportError:
		pass
	if len(sys.argv)<3:
		print('USEAGE:')
		print('   newfiles templateName location')
	else:
		print('Template:',sys.argv[1])
		print('Location:',sys.argv[2])
		n=Template(sys.argv[1])
		n.create(sys.argv[2])
Example #40
0
# Application :    Noethys, gestion multi-activités
# Site internet :  www.noethys.com
# Auteur:           Ivan LUCAS
# Copyright:       (c) 2010-11 Ivan LUCAS
# Licence:         Licence GNU GPL
#------------------------------------------------------------------------


import Chemins
from Utils.UTILS_Traduction import _
import wx
from Ctrl import CTRL_Bouton_image
from Ctrl import CTRL_Bandeau
from Ol import OL_Types_vaccins

try: import psyco; psyco.full()
except: pass


class Dialog(wx.Dialog):
    def __init__(self, parent):
        wx.Dialog.__init__(self, parent, -1, style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER|wx.MAXIMIZE_BOX|wx.MINIMIZE_BOX|wx.THICK_FRAME)
        self.parent = parent
        
        intro = _(u"Vous pouvez ici saisir, modifier ou supprimer des vaccins. Lorsque vous saisissez un nouveau vaccin, pensez à y associer la ou les maladies qu'il est sensé vacciné.")
        titre = _(u"Gestion des vaccins")
        self.ctrl_bandeau = CTRL_Bandeau.Bandeau(self, titre=titre, texte=intro, hauteurHtml=30, nomImage="Images/32x32/Seringue.png")
        self.ctrl_listview = OL_Types_vaccins.ListView(self, id=-1, style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_SINGLE_SEL|wx.LC_HRULES|wx.LC_VRULES)
        self.ctrl_listview.MAJ()
        self.ctrl_recherche = OL_Types_vaccins.CTRL_Outils(self, listview=self.ctrl_listview)
        
Example #41
0
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "xeho:vt:iq:f:l:du:", ["verbose","help", "output=", "ticker=", "quote=","file=","lang=","user="******"nopsyco","nowxversion"])
    except getopt.GetoptError:
        # print help information and exit:
        usage()
        sys.exit(2)

    # default values
    output = None
    quote = None
    file = None
    wx = True
    nopsyco = False
    nowxversion = False;

    vticker = None
    vquote  = None

    lang = gMessage.getAutoDetectedLang('us')
    for o, a in opts:

        if o == "-d":
            itrade_config.setDisconnected(True)

        if o == "-v" or o == "--verbose":
            itrade_config.verbose = True
            print 'Verbose mode : ON'

        if o == "-x":
            itrade_config.experimental = True

        if o == "-e":
            itrade_portfolio.cmdline_evaluatePortfolio()
            wx = False

        if o == "-i":
            if quote:
                if file:
                    itrade_import.cmdline_importQuoteFromFile(quote,file)
                else:
                    itrade_import.cmdline_importQuoteFromInternet(quote)
            else:
                matrix = itrade_matrix.createMatrix()
                if file:
                    itrade_import.cmdline_importMatrixFromFile(matrix,file)
                else:
                    itrade_import.cmdline_importMatrixFromInternet(matrix)
            wx = False

        if o == "-h" or o == "--help":
            usage()
            sys.exit()

        if o == "-o" or o == "--output":
            output = a

        if o == "-u" or o == "--user":
            itrade_config.dirUserData = a
            if not os.path.exists(itrade_config.dirUserData):
                print 'userdata folder %s not found !' % a
                sys.exit()

        if o  == "--nopsyco":
            nopsyco = True

        if o  == "--nowxversion":
            itrade_config.nowxversion = True

        if o == "-f" or o == "--file":
            file = a

        if o == "-l" or o == "--lang":
            lang = a
            itrade_config.lang = 255

        if o == "-t" or o == "--ticker":
            vticker = a

        if o == "-q" or o == "--quote":
            vquote = a

    # Import Psyco if available
    if not nopsyco:
        try:
            import psyco
            psyco.full()
            print 'Psyco is running'
        except ImportError:
            print 'Psyco is not running (library not found)'
    else:
        print 'Psyco is not running (forced by command line)'

    # load configuration
    itrade_config.loadConfig("itrade.py")
    if itrade_config.verbose:
        print "*** Proxy server:",itrade_config.proxyHostname, "- Proxy auth:",itrade_config.proxyAuthentication,"- Connection timeout:",itrade_config.connectionTimeout

    # load extensions
    itrade_ext.loadExtensions(itrade_config.fileExtData,itrade_config.dirExtData)

    # init modules
    itrade_quotes.initQuotesModule()
    itrade_portfolio.initPortfolioModule()

    # use the correct pack language
    if itrade_config.lang == 255:
        gMessage.setLang(lang)
        gMessage.load()

    # commands
    if vticker:
        quote = itrade_quotes.quotes.lookupTicker(vticker)
        if not quote:
            print 'ticker %s not found !' % vticker
            sys.exit()

    if vquote:
        quote = itrade_quotes.quotes.lookupKey(vquote)
        if not quote:
            print 'quote %s not found ! format is : <ISINorTICKER>.<EXCHANGE>.<PLACE>' % vquote
            sys.exit()

    if wx:
        import itrade_wxmain
        itrade_wxmain.start_iTradeWindow()

    if quote:
        portfolio = itrade_portfolio.loadPortfolio()
        quote.update()
        quote.compute()
        quote.printInfo()
Example #42
0
class CommandInterface:
    extended_erase = 0

    def open(self, aport='/dev/ttyAMA0', abaudrate=115200) :
        self.sp = serial.Serial(
            port=aport,
            baudrate=abaudrate,     # baudrate
            bytesize=8,             # number of databits
            parity=serial.PARITY_EVEN,
            stopbits=1,
            xonxoff=0,              # don't enable software flow control
            rtscts=0,               # don't enable RTS/CTS flow control
            timeout=5               # set a timeout value, None for waiting forever
        )


    def _wait_for_ask(self, info = ""):
        # wait for ask
        try:
            ask = ord(self.sp.read())
        except:
            raise CmdException("Can't read port or timeout")
        else:
            if ask == 0x79:
                # ACK
                return 1
            else:
                if ask == 0x1F:
                    # NACK
                    raise CmdException("NACK "+info)
                else:
                    # Unknown responce
                    raise CmdException("Unknown response. "+info+": "+hex(ask))

    def setPin(self, pin, value):
        val_fd = open(pin,"w")
        val_fd.write(str(value))
        val_fd.close()

    def reset(self):
        self.setPin(conf['pin_reset'], 1)
        time.sleep(0.1)
        self.setPin(conf['pin_reset'], 0)
        time.sleep(0.5)

    def initChip(self):
        # Set boot
        self.setPin(conf['pin_boot0'], 1)
        self.reset()
        self.sp.flushInput()
        self.sp.flushOutput()

        self.sp.write("\x7F")       # Syncro
        return self._wait_for_ask("Syncro")

    def releaseChip(self):
        self.setPin(conf['pin_boot0'],0)
        self.reset()

    def cmdGeneric(self, cmd):
        self.sp.write(chr(cmd))
        self.sp.write(chr(cmd ^ 0xFF)) # Control byte
        return self._wait_for_ask(hex(cmd))

    def cmdGet(self):
        if self.cmdGeneric(0x00):
            mdebug(10, "*** Get command");
            len = ord(self.sp.read())
            version = ord(self.sp.read())
            mdebug(10, "    Bootloader version: "+hex(version))
            dat = map(lambda c: hex(ord(c)), self.sp.read(len))
            if '0x44' in dat:
                self.extended_erase = 1
            mdebug(10, "    Available commands: "+", ".join(dat))
            self._wait_for_ask("0x00 end")
            return version
        else:
            raise CmdException("Get (0x00) failed")

    def cmdGetVersion(self):
        if self.cmdGeneric(0x01):
            mdebug(10, "*** GetVersion command")
            version = ord(self.sp.read())
            self.sp.read(2)
            self._wait_for_ask("0x01 end")
            mdebug(10, "    Bootloader version: "+hex(version))
            return version
        else:
            raise CmdException("GetVersion (0x01) failed")

    def cmdGetID(self):
        if self.cmdGeneric(0x02):
            mdebug(10, "*** GetID command")
            len = ord(self.sp.read())
            id = self.sp.read(len+1)
            self._wait_for_ask("0x02 end")
            return reduce(lambda x, y: x*0x100+y, map(ord, id))
        else:
            raise CmdException("GetID (0x02) failed")


    def _encode_addr(self, addr):
        byte3 = (addr >> 0) & 0xFF
        byte2 = (addr >> 8) & 0xFF
        byte1 = (addr >> 16) & 0xFF
        byte0 = (addr >> 24) & 0xFF
        crc = byte0 ^ byte1 ^ byte2 ^ byte3
        return (chr(byte0) + chr(byte1) + chr(byte2) + chr(byte3) + chr(crc))


    def cmdReadMemory(self, addr, lng):
        assert(lng <= 256)
        if self.cmdGeneric(0x11):
            mdebug(10, "*** ReadMemory command")
            self.sp.write(self._encode_addr(addr))
            self._wait_for_ask("0x11 address failed")
            N = (lng - 1) & 0xFF
            crc = N ^ 0xFF
            self.sp.write(chr(N) + chr(crc))
            self._wait_for_ask("0x11 length failed")
            return map(lambda c: ord(c), self.sp.read(lng))
        else:
            raise CmdException("ReadMemory (0x11) failed")


    def cmdGo(self, addr):
        if self.cmdGeneric(0x21):
            mdebug(10, "*** Go command")
            self.sp.write(self._encode_addr(addr))
            self._wait_for_ask("0x21 go failed")
        else:
            raise CmdException("Go (0x21) failed")


    def cmdWriteMemory(self, addr, data):
        assert(len(data) <= 256)
        if self.cmdGeneric(0x31):
            mdebug(10, "*** Write memory command")
            self.sp.write(self._encode_addr(addr))
            self._wait_for_ask("0x31 address failed")
            #map(lambda c: hex(ord(c)), data)
            lng = (len(data)-1) & 0xFF
            mdebug(10, "    %s bytes to write" % [lng+1]);
            self.sp.write(chr(lng)) # len really
            crc = 0xFF
            for c in data:
                crc = crc ^ c
                self.sp.write(chr(c))
            self.sp.write(chr(crc))
            self._wait_for_ask("0x31 programming failed")
            mdebug(10, "    Write memory done")
        else:
            raise CmdException("Write memory (0x31) failed")


    def cmdEraseMemory(self, sectors = None):
        if self.extended_erase:
            return cmd.cmdExtendedEraseMemory()

        if self.cmdGeneric(0x43):
            mdebug(10, "*** Erase memory command")
            if sectors is None:
                # Global erase
                self.sp.write(chr(0xFF))
                self.sp.write(chr(0x00))
            else:
                # Sectors erase
                crc = 0x0

                sec_len = (len(sectors)-1) & 0xff
                crc ^= sec_len
                self.sp.write(chr(sec_len))

                for c in sectors:
                    crc ^= c
                    self.sp.write(chr(c))
                self.sp.write(chr(crc))
            self._wait_for_ask("0x43 erasing failed")
            mdebug(10, "    Erase memory done")
        else:
            raise CmdException("Erase memory (0x43) failed")

    def cmdExtendedEraseMemory(self):
        if self.cmdGeneric(0x44):
            mdebug(10, "*** Extended Erase memory command")
            # Global mass erase
            self.sp.write(chr(0xFF))
            self.sp.write(chr(0xFF))
            # Checksum
            self.sp.write(chr(0x00))
            tmp = self.sp.timeout
            self.sp.timeout = 30
            print "Extended erase (0x44), this can take ten seconds or more"
            self._wait_for_ask("0x44 erasing failed")
            self.sp.timeout = tmp
            mdebug(10, "    Extended Erase memory done")
        else:
            raise CmdException("Extended Erase memory (0x44) failed")

    def cmdWriteProtect(self, sectors):
        if self.cmdGeneric(0x63):
            mdebug(10, "*** Write protect command")
            self.sp.write(chr((len(sectors)-1) & 0xFF))
            crc = 0xFF
            for c in sectors:
                crc = crc ^ c
                self.sp.write(chr(c))
            self.sp.write(chr(crc))
            self._wait_for_ask("0x63 write protect failed")
            mdebug(10, "    Write protect done")
        else:
            raise CmdException("Write Protect memory (0x63) failed")

    def cmdWriteUnprotect(self):
        if self.cmdGeneric(0x73):
            mdebug(10, "*** Write Unprotect command")
            self._wait_for_ask("0x73 write unprotect failed")
            self._wait_for_ask("0x73 write unprotect 2 failed")
            mdebug(10, "    Write Unprotect done")
        else:
            raise CmdException("Write Unprotect (0x73) failed")

    def cmdReadoutProtect(self):
        if self.cmdGeneric(0x82):
            mdebug(10, "*** Readout protect command")
            self._wait_for_ask("0x82 readout protect failed")
            self._wait_for_ask("0x82 readout protect 2 failed")
            mdebug(10, "    Read protect done")
        else:
            raise CmdException("Readout protect (0x82) failed")

    def cmdReadoutUnprotect(self):
        if self.cmdGeneric(0x92):
            mdebug(10, "*** Readout Unprotect command")
            # first (N)ACK is already read as part of cmdGeneric()
            self._wait_for_ask("0x92 readout unprotect 2 failed")
            mdebug(10, "    Read Unprotect done")
            # there does not appear to be a way to be notified when the
            # mass erase is complete... boo. hopefully this will be rare, i guess.
            time.sleep(20)

            # following readout unprotect, the system resets, so we must init once again.
            self.initChip()

        else:
            raise CmdException("Readout unprotect (0x92) failed")


# Complex commands section

    def readMemory(self, addr, lng):
        data = []
        if usepbar:
            widgets = ['Reading: ', Percentage(),', ', ETA(), ' ', Bar()]
            pbar = ProgressBar(widgets=widgets,maxval=lng, term_width=79).start()

        while lng > 256:
            if usepbar:
                pbar.update(pbar.maxval-lng)
            else:
                mdebug(5, "Read %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
            data = data + self.cmdReadMemory(addr, 256)
            addr = addr + 256
            lng = lng - 256
        if usepbar:
            pbar.update(pbar.maxval-lng)
            pbar.finish()
        else:
            mdebug(5, "Read %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
        data = data + self.cmdReadMemory(addr, lng)
        return data

    def writeMemory(self, addr, data):
        lng = len(data)
        if usepbar:
            widgets = ['Writing: ', Percentage(),' ', ETA(), ' ', Bar()]
            pbar = ProgressBar(widgets=widgets, maxval=lng, term_width=79).start()

        offs = 0
        while lng > 256:
            if usepbar:
                pbar.update(pbar.maxval-lng)
            else:
                mdebug(5, "Write %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
            self.cmdWriteMemory(addr, data[offs:offs+256])
            offs = offs + 256
            addr = addr + 256
            lng = lng - 256
        if usepbar:
            pbar.update(pbar.maxval-lng)
            pbar.finish()
        else:
            mdebug(5, "Write %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
        self.cmdWriteMemory(addr, data[offs:offs+lng] + ([0xFF] * (256-lng)) )




	def __init__(self) :
        pass


def usage():
    print """Usage: %s [-hqVewvr] [-l length] [-p port] [-b baud] [-a addr] [-g addr] [-n pin] [-m pin] [file.bin]
    -h          This help
    -q          Quiet
    -V          Verbose
    -e          Erase
    -w          Write
    -v          Verify
    -r          Read
    -l length   Length of read
    -p port     Serial port (default: /dev/ttyAMA0)
    -b baud     Baud speed (default: 115200)
    -a addr     Target address
    -g addr     Address to start running at (0x08000000, usually)
    -n pin      Pin file name for reset (default: /sys/class/gpio_sw/PA8/data)
    -m pin      Pin file name for boot0 (default: /sys/class/gpio_sw/PA7/data)

    ./stm32loader.py -e -w -v example/main.bin

    """ % sys.argv[0]


if __name__ == "__main__":

    # Import Psyco if available
    try:
        import psyco
        psyco.full()
        print "Using Psyco..."
    except ImportError:
        pass

    conf = {
            'port': '/dev/ttyS3',
            'baud': 115200,
            'address': 0x08000000,
            'erase': 0,
            'write': 0,
            'verify': 0,
            'read': 0,
            'go_addr':-1,
            'pin_reset': 'PA8',
            'pin_boot0': 'PA7'
        }

# http://www.python.org/doc/2.5.2/lib/module-getopt.html

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hqVewvrs:p:b:a:l:g:n:m:")
    except getopt.GetoptError, err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)

    QUIET = 5

    for o, a in opts:
        if o == '-V':
            QUIET = 10
        elif o == '-q':
            QUIET = 0
        elif o == '-h':
            usage()
            sys.exit(0)
        elif o == '-e':
            conf['erase'] = 1
        elif o == '-s':
            conf['erase-sectors'] = a
        elif o == '-w':
            conf['write'] = 1
        elif o == '-v':
            conf['verify'] = 1
        elif o == '-r':
            conf['read'] = 1
        elif o == '-p':
            conf['port'] = a
        elif o == '-b':
            conf['baud'] = eval(a)
        elif o == '-a':
            conf['address'] = eval(a)
        elif o == '-g':
            conf['go_addr'] = eval(a)
        elif o == '-l':
            conf['len'] = eval(a)
        elif o == '-n':
            conf['pin_reset'] = a
        elif o == '-m':
            conf['pin_boot0'] = a
        else:
            assert False, "unhandled option"

    cmd = CommandInterface()
    cmd.open(conf['port'], conf['baud'])
    mdebug(10, "Open port %(port)s, baud %(baud)d" % {'port':conf['port'], 'baud':conf['baud']})
    try:
        try:
            cmd.initChip()
        except:
            print "Can't init. Ensure that BOOT0 is enabled and reset device"


        bootversion = cmd.cmdGet()
        mdebug(0, "Bootloader version %X" % bootversion)
        id = cmd.cmdGetID()
        mdebug(0, "Chip id: 0x%x (%s)" % (id, chip_ids.get(id, "Unknown")))
#    cmd.cmdGetVersion()
#    cmd.cmdGetID()
#    cmd.cmdReadoutUnprotect()
#    cmd.cmdWriteUnprotect()
#    cmd.cmdWriteProtect([0, 1])

        if (conf['write'] or conf['verify']):
            data = map(lambda c: ord(c), file(args[0], 'rb').read())

        try:
            if conf['erase']:
                cmd.cmdEraseMemory()
            elif 'erase-sectors' in conf:
                # cmdEraseMemory() accepts a list of sectors,
                # we treat the arg as a sector count, at offset 0
                sectors = range(int(conf['erase-sectors']))
                cmd.cmdEraseMemory(sectors)

        except CmdException:
            # assumption: erase failed due to readout protection.
            # this was observed once as a process problem in production,
            # there may be other reasons for this failure in the future.
            mdebug(0, "EraseMemory failed, disabling readout protection")
            cmd.cmdReadoutUnprotect()

        if conf['write']:
            cmd.writeMemory(conf['address'], data)

        if conf['verify']:
            verify = cmd.readMemory(conf['address'], len(data))
            if(data == verify):
                print "Verification OK"
            else:
                print "Verification FAILED"
                print str(len(data)) + ' vs ' + str(len(verify))
                imax = len(data)
                if imax > 100:
                    imax = 100
                for i in xrange(0, imax):
                    if data[i] != verify[i]:
                        print hex(i) + ': ' + hex(data[i]) + ' vs ' + hex(verify[i])
                raise VerifyException("Verification FAILED")

        if not conf['write'] and conf['read']:
            rdata = cmd.readMemory(conf['address'], conf['len'])
            file(args[0], 'wb').write(''.join(map(chr,rdata)))

        if conf['go_addr'] != -1:
            cmd.cmdGo(conf['go_addr'])

    finally:
        cmd.releaseChip()
Example #43
0
            print '%s<%s>' % (sdepth, child.name)
            xmlify(child, verbose, depth + 1)
            print '%s</%s>' % (sdepth, child.name)
        else:
            if "\n" in child.get_value() or "\r" in child.get_value():
                print sdepth + '<' + child.name + '>' + \
            '<![CDATA[' + child.get_value() + ']]>' + '</' + child.name + '>'
            else:
                print sdepth + '<' + child.name + '>' + \
            escape(child.get_value())  + '</' + child.name + '>'

if __name__ == "__main__":
    import argparse, subprocess
    try: import psyco
    except ImportError: pass
    else: psyco.full()

    # Hack to make us not crash when we encounter characters that aren't ASCII
    sys.stdout = __import__("codecs").getwriter('utf-8')(sys.stdout)

    argumentparser = argparse.ArgumentParser("usage: %(prog)s [options]")
    argumentparser.add_argument("-p", "--path",  help = "specify wesnoth data path")
    argumentparser.add_argument("-C", "--color", action = "store_true",
        help = "use colored output")
    argumentparser.add_argument("-u", "--userpath",  help = "specify userdata path")
    argumentparser.add_argument("-e", "--execute",  help = "execute given WML")
    argumentparser.add_argument("-v", "--verbose", action = "store_true",
        help = "make the parser very verbose")
    argumentparser.add_argument("-n", "--no-macros", action = "store_true",
        help = "do not expand any macros")
    argumentparser.add_argument("-c", "--contents", action = "store_true",
Example #44
0
def main(argv, klass=MetaFile, xopts='', xoptf=None):
    """Simple driver for class MetaFile.

    Usage:
    	script [options] [key=value ...] "meta" ...
        
    Options and key=value pairs contribute to the
    dictionary passed to MetaFile.

    -S "SRCTOP"
		add "SRCTOP" to the "SRCTOPS" list.

    -C "CURDIR"
    
    -O "OBJROOT"
    		add "OBJROOT" to the "OBJROOTS" list.

    -m "MACHINE"

    -a "MACHINE_ARCH"

    -H "HOST_TARGET"

    -D "DPDEPS"
    
    -d	bumps debug level

    """
    import getopt

    # import Psyco if we can
    # it can speed things up quite a bit
    have_psyco = 0
    try:
        import psyco
        psyco.full()
        have_psyco = 1
    except:
        pass

    conf = {
        'SRCTOPS': [],
        'OBJROOTS': [],
    }

    try:
        machine = os.environ['MACHINE']
        if machine:
            conf['MACHINE'] = machine
        machine_arch = os.environ['MACHINE_ARCH']
        if machine_arch:
            conf['MACHINE_ARCH'] = machine_arch
        srctop = os.environ['SB_SRC']
        if srctop:
            conf['SRCTOPS'].append(srctop)
        objroot = os.environ['SB_OBJROOT']
        if objroot:
            conf['OBJROOTS'].append(objroot)
    except:
        pass

    debug = 0
    output = True

    opts, args = getopt.getopt(argv[1:], 'a:dS:C:O:R:m:D:H:qT:' + xopts)
    for o, a in opts:
        if o == '-a':
            conf['MACHINE_ARCH'] = a
        elif o == '-d':
            debug += 1
        elif o == '-q':
            output = False
        elif o == '-H':
            conf['HOST_TARGET'] = a
        elif o == '-S':
            if a not in conf['SRCTOPS']:
                conf['SRCTOPS'].append(a)
        elif o == '-C':
            conf['CURDIR'] = a
        elif o == '-O':
            if a not in conf['OBJROOTS']:
                conf['OBJROOTS'].append(a)
        elif o == '-R':
            conf['RELDIR'] = a
        elif o == '-D':
            conf['DPDEPS'] = a
        elif o == '-m':
            conf['MACHINE'] = a
        elif o == '-T':
            conf['TARGET_SPEC'] = a
        elif xoptf:
            xoptf(o, a, conf)

    conf['debug'] = debug

    # get any var=val assignments
    eaten = []
    for a in args:
        if a.find('=') > 0:
            k, v = a.split('=')
            if k in ['SRCTOP', 'OBJROOT', 'SRCTOPS', 'OBJROOTS']:
                if k == 'SRCTOP':
                    k = 'SRCTOPS'
                elif k == 'OBJROOT':
                    k = 'OBJROOTS'
                if v not in conf[k]:
                    conf[k].append(v)
            else:
                conf[k] = v
            eaten.append(a)
            continue
        break

    for a in eaten:
        args.remove(a)

    debug_out = getv(conf, 'debug_out', sys.stderr)

    if debug:
        print("config:", file=debug_out)
        print("psyco=", have_psyco, file=debug_out)
        for k, v in list(conf.items()):
            print("%s=%s" % (k, v), file=debug_out)

    for a in args:
        if a.endswith('.meta'):
            m = klass(a, conf)
        elif a.startswith('@'):
            # there can actually multiple files per line
            for line in open(a[1:]):
                for f in line.strip().split():
                    m = klass(f, conf)

    if output:
        print(m.dirdeps())

        print(m.src_dirdeps('\nsrc:'))

        dpdeps = getv(conf, 'DPDEPS')
        if dpdeps:
            m.file_depends(open(dpdeps, 'wb'))

    return m
Example #45
0
def execute(parser, opts, args, pycam):
    # try to change the process name
    pycam.Utils.setproctitle("pycam")

    if len(args) > 0:
        inputfile = pycam.Utils.URIHandler(args[0])
    else:
        inputfile = None

    if opts.debug:
        log.setLevel(logging.DEBUG)
    elif opts.quiet:
        log.setLevel(logging.WARNING)
        # disable the progress bar
        opts.progress = "none"
        # silence all warnings
        warnings.filterwarnings("ignore")
    else:
        # silence gtk warnings
        try:
            import gtk
            warnings.filterwarnings("ignore", category=gtk.Warning)
        except ImportError:
            pass

    # show version and exit
    if opts.show_version:
        if opts.quiet:
            # print only the bare version number
            print VERSION
        else:
            text = '''PyCAM %s
Copyright (C) 2008-2010 Lode Leroy
Copyright (C) 2010-2011 Lars Kruse

License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.''' % VERSION
            print text
        return EXIT_CODES["ok"]

    if not opts.disable_psyco:
        try:
            import psyco
            psyco.full()
            log.info("Psyco enabled")
        except ImportError:
            log.info("Psyco is not available (performance will probably " \
                    + "suffer slightly)")
    else:
        log.info("Psyco was disabled via the commandline")

    # check if server-auth-key is given -> this is mandatory for server mode
    if (opts.enable_server or opts.start_server) and not opts.server_authkey:
        parser.error("You need to supply a shared secret for server mode. " \
                + "This is supposed to prevent you from exposing your host " \
                + "to remote access without authentication.\n" \
                + "Please add the '--server-auth-key' argument followed by " \
                + "a shared secret password.")
        return EXIT_CODES["server_without_password"]

    # initialize multiprocessing
    try:
        if opts.start_server:
            pycam.Utils.threading.init_threading(
                opts.parallel_processes,
                remote=opts.remote_server,
                run_server=True,
                server_credentials=opts.server_authkey)
            pycam.Utils.threading.cleanup()
            return EXIT_CODES["ok"]
        else:
            pycam.Utils.threading.init_threading(
                opts.parallel_processes,
                enable_server=opts.enable_server,
                remote=opts.remote_server,
                server_credentials=opts.server_authkey)
    except socket.error, err_msg:
        log.error("Failed to connect to remote server: %s" % err_msg)
        return EXIT_CODES["connection_error"]
Example #46
0
class CommandInterface:
    def open(self, aport='/dev/rfcomm0', abaudrate=115200) :
#        self.sp = open(aport,'rb+')
        self.sp=serial.Serial(
            port=aport,
            baudrate=abaudrate,     # baudrate
            bytesize=8,             # number of databits
            parity=serial.PARITY_EVEN,
            stopbits=1,
            xonxoff=0,              # enable software flow control
            rtscts=0,               # disable RTS/CTS flow control
            timeout=5               # set a timeout value, None for waiting forever
        )


    def _wait_for_ask(self, info = ""):
        # wait for ask
        try:
            ask = ord(self.sp.read())
        except:
            raise CmdException("Can't read port or timeout")
        else:
            if ask == 0x79 or ask == 0x69:
                # ACK
                return 1
            else:
                if ask == 0x1F:
                    # NACK
                    raise CmdException("NACK "+info)
                else:
                    #Unknown responce
                    raise CmdException("Unknown response. "+info+": "+hex(ask))

    def enterCMD(self):
        self.sp.timeout=0.2
        reply=""
        iterations=0
        while reply[0:3]!="CMD":
           self.sp.flushInput()
           self.sp.write("$$$")
           self.sp.flush()
           reply=self.sp.readline()
           iterations+=1
           if iterations>3:
               raise CmdException("RN41/2 CMD mode entry failed:"+reply)
        self.sp.timeout=5

    def exitCMD(self):
        self.sp.timeout=0.2
        reply=""
        iterations=0
        while reply[0:3]!="END":
           self.sp.flushInput()
           self.sp.write("---\r")
           self.sp.flush()
           reply=self.sp.readline()
           iterations+=1
           if iterations>3:
               raise CmdException("RN41/2 exit CMD mode entry failed:"+reply)
        self.sp.timeout=5

    def sendCMD(self, cmd):
        self.sp.timeout=0.2
        reply=""
        iterations=0
        while reply[0:3]!="AOK":
           self.sp.flushInput()
           self.sp.write(cmd+"\r\n")
           self.sp.flush()
           reply=self.sp.readline()
           iterations+=1
           if iterations>3:
               raise CmdException("RN41/2 command "+cmd+" failed:"+reply)
        self.sp.timeout=5

    def reset(self):
        time.sleep(0.2)
        self.sendCMD("S*,0800")      #Set GPIO11 low to set Reset
        time.sleep(0.2)
        self.sendCMD("S*,0808")      #Set GPIO11 high to clear Reset
        time.sleep(0.2)

    def initChip(self):
        # Set boot
        #self.sp.write("btld")
        #time.sleep(0.5)
        self.enterCMD()
        self.sendCMD("ST,254")       #Set remote continuous config
        self.sendCMD("S@,0808")      #Set GPIO3 output to keep power enabled
        self.sendCMD("S&,0808")      #Set GPIO3 high to keep power enabled
        self.sendCMD("S*,0404")      #Set GPIO10 high to set BOOT0
        self.reset()
        self.sendCMD("S*,0400")      #Set GPIO10 low to clear BOOT0
        self.exitCMD()               #exit cmd mode
        time.sleep(0.2)
        self.sp.flushInput()
        self.sp.write("\x7F")        # Syncro
        return self._wait_for_ask("Syncro") 

    def releaseChip(self):
        self.enterCMD()
        self.reset()
        self.sendCMD("ST,60")        #Set remote 60second config
        self.sendCMD("S&,0800")      #Set GPIO3 as low to kill power on reset - note this will fail to get ACK if the logger turns off
        self.sendCMD("S@,0800")      #Set GPIO3 as input to kill power on reset
        self.exitCMD()
        self.sp.close()              #leaves the bluetooth rfcomm free for other connections - if the logger hasnt turned itself off

    def cmdGeneric(self, cmd):
        self.sp.write(chr(cmd))
        self.sp.write(chr(cmd ^ 0xFF)) # Control byte
        self.sp.flush()
        return self._wait_for_ask(hex(cmd))

    def cmdGet(self):
        if self.cmdGeneric(0x00):
            mdebug(10, "*** Get command");
            len = ord(self.sp.read())
            version = ord(self.sp.read())
            mdebug(10, "    Bootloader version: "+hex(version))
            dat = map(lambda c: hex(ord(c)), self.sp.read(len))
            mdebug(10, "    Available commands: "+str(dat))
            self._wait_for_ask("0x00 end")
            return version
        else:
            raise CmdException("Get (0x00) failed")

    def cmdGetVersion(self):
        if self.cmdGeneric(0x01):
            mdebug(10, "*** GetVersion command")
            version = ord(self.sp.read())
            self.sp.read(2)
            self._wait_for_ask("0x01 end")
            mdebug(10, "    Bootloader version: "+hex(version))
            return version
        else:
            raise CmdException("GetVersion (0x01) failed")

    def cmdGetID(self):
        if self.cmdGeneric(0x02):
            mdebug(10, "*** GetID command")
            len = ord(self.sp.read())
            id = self.sp.read(len+1)
            self._wait_for_ask("0x02 end")
            return id
        else:
            raise CmdException("GetID (0x02) failed")


    def _encode_addr(self, addr):
        byte3 = (addr >> 0) & 0xFF
        byte2 = (addr >> 8) & 0xFF
        byte1 = (addr >> 16) & 0xFF
        byte0 = (addr >> 24) & 0xFF
        crc = byte0 ^ byte1 ^ byte2 ^ byte3
        return (chr(byte0) + chr(byte1) + chr(byte2) + chr(byte3) + chr(crc))


    def cmdReadMemory(self, addr, lng):
        assert(lng <= 256)
        if self.cmdGeneric(0x11):
            mdebug(10, "*** ReadMemory command")
            self.sp.write(self._encode_addr(addr))
            self._wait_for_ask("0x11 address failed")
            N = (lng - 1) & 0xFF
            crc = N ^ 0xFF
            self.sp.write(chr(N) + chr(crc))
            self._wait_for_ask("0x11 length failed")
            return map(lambda c: ord(c), self.sp.read(lng))
        else:
            raise CmdException("ReadMemory (0x11) failed")


    def cmdGo(self, addr):
        if self.cmdGeneric(0x21):
            mdebug(10, "*** Go command")
            self.sp.write(self._encode_addr(addr))
            self._wait_for_ask("0x21 go failed")
        else:
            raise CmdException("Go (0x21) failed")


    def cmdWriteMemory(self, addr, data):
        assert(len(data) <= 256)
        if self.cmdGeneric(0x31):
            mdebug(10, "*** Write memory command")
            self.sp.write(self._encode_addr(addr))
            self._wait_for_ask("0x31 address failed")
            #map(lambda c: hex(ord(c)), data)
            lng = (len(data)-1) & 0xFF
            mdebug(10, "    %s bytes to write" % [lng+1]);
            self.sp.write(chr(lng)) # len really
            crc = 0xFF
            for c in data:
                crc = crc ^ c
                self.sp.write(chr(c))
            self.sp.write(chr(crc))
            self._wait_for_ask("0x31 programming failed")
            mdebug(10, "    Write memory done")
        else:
            raise CmdException("Write memory (0x31) failed")


    def cmdEraseMemory(self, sectors = None):
        if self.cmdGeneric(0x43):
            mdebug(10, "*** Erase memory command")
            if sectors is None:
                # Global erase
                self.sp.write(chr(0xFF))
                self.sp.write(chr(0x00))
            else:
                # Sectors erase
                self.sp.write(chr((len(sectors)-1) & 0xFF))
                crc = 0xFF
                for c in sectors:
                    crc = crc ^ c
                    self.sp.write(chr(c))
                self.sp.write(chr(crc))
            self._wait_for_ask("0x43 erasing failed")
            mdebug(10, "    Erase memory done")
        else:
            raise CmdException("Erase memory (0x43) failed")

    def cmdWriteProtect(self, sectors):
        if self.cmdGeneric(0x63):
            mdebug(10, "*** Write protect command")
            self.sp.write(chr((len(sectors)-1) & 0xFF))
            crc = 0xFF
            for c in sectors:
                crc = crc ^ c
                self.sp.write(chr(c))
            self.sp.write(chr(crc))
            self._wait_for_ask("0x63 write protect failed")
            mdebug(10, "    Write protect done")
        else:
            raise CmdException("Write Protect memory (0x63) failed")

    def cmdWriteUnprotect(self):
        if self.cmdGeneric(0x73):
            mdebug(10, "*** Write Unprotect command")
            self._wait_for_ask("0x73 write unprotect failed")
            self._wait_for_ask("0x73 write unprotect 2 failed")
            mdebug(10, "    Write Unprotect done")
        else:
            raise CmdException("Write Unprotect (0x73) failed")

    def cmdReadoutProtect(self):
        if self.cmdGeneric(0x82):
            mdebug(10, "*** Readout protect command")
            self._wait_for_ask("0x82 readout protect failed")
            self._wait_for_ask("0x82 readout protect 2 failed")
            mdebug(10, "    Read protect done")
        else:
            raise CmdException("Readout protect (0x82) failed")

    def cmdReadoutUnprotect(self):
        if self.cmdGeneric(0x92):
            mdebug(10, "*** Readout Unprotect command")
            self._wait_for_ask("0x92 readout unprotect failed")
            self._wait_for_ask("0x92 readout unprotect 2 failed")
            mdebug(10, "    Read Unprotect done")
        else:
            raise CmdException("Readout unprotect (0x92) failed")


# Complex commands section

    def readMemory(self, addr, lng):
        data = []
        if usepbar:
            widgets = ['Reading: ', Percentage(),', ', ETA(), ' ', Bar()]
            pbar = ProgressBar(widgets=widgets,maxval=lng, term_width=79).start()
        
        while lng > 256:
            if usepbar:
                pbar.update(pbar.maxval-lng)
            else:
                mdebug(5, "Read %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
            data = data + self.cmdReadMemory(addr, 256)
            addr = addr + 256
            lng = lng - 256
        if usepbar:
            pbar.update(pbar.maxval-lng)
            pbar.finish()
        else:
            mdebug(5, "Read %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
        data = data + self.cmdReadMemory(addr, lng)
        return data

    def writeMemory(self, addr, data):
        lng = len(data)
        if usepbar:
            widgets = ['Writing: ', Percentage(),' ', ETA(), ' ', Bar()]
            pbar = ProgressBar(widgets=widgets, maxval=lng, term_width=79).start()
        
        offs = 0
        while lng > 256:
            if usepbar:
                pbar.update(pbar.maxval-lng)
            else:
                mdebug(5, "Write %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
            self.cmdWriteMemory(addr, data[offs:offs+256])
            offs = offs + 256
            addr = addr + 256
            lng = lng - 256
        if usepbar:
            pbar.update(pbar.maxval-lng)
            pbar.finish()
        else:
            mdebug(5, "Write %(len)d bytes at 0x%(addr)X" % {'addr': addr, 'len': 256})
        self.cmdWriteMemory(addr, data[offs:offs+lng] + ([0xFF] * (256-lng)) )




	def __init__(self) :
        pass


def usage():
    print """Usage: %s [-hqVewvr] [-l length] [-p port] [-b baud] [-a addr] [file.bin]
    -h          This help
    -q          Quiet
    -V          Verbose
    -e          Erase
    -w          Write
    -v          Verify
    -r          Read
    -l length   Length of read
    -p port     Serial port (default: /dev/tty.usbserial-ftCYPMYJ)
    -b baud     Baud speed (default: 115200)
    -a addr     Target address

    ./stm32loader.py -e -w -v example/main.bin

    """ % sys.argv[0]


if __name__ == "__main__":
    
    # Import Psyco if available
    try:
        import psyco
        psyco.full()
        print "Using Psyco..."
    except ImportError:
        pass

    conf = {
            'port': '/dev/rfcomm0',
            'baud': 115200,
            'address': 0x08000000,
            'erase': 0,
            'write': 0,
            'verify': 0,
            'read': 0,
            'len': 1000,
            'fname':'',
        }

# http://www.python.org/doc/2.5.2/lib/module-getopt.html

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hqVewvrp:b:a:l:")
    except getopt.GetoptError, err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)

    QUIET = 5

    for o, a in opts:
        if o == '-V':
            QUIET = 10
        elif o == '-q':
            QUIET = 0
        elif o == '-h':
            usage()
            sys.exit(0)
        elif o == '-e':
            conf['erase'] = 1
        elif o == '-w':
            conf['write'] = 1
        elif o == '-v':
            conf['verify'] = 1
        elif o == '-r':
            conf['read'] = 1
        elif o == '-p':
            conf['port'] = a
        elif o == '-b':
            conf['baud'] = eval(a)
        elif o == '-a':
            conf['address'] = eval(a)
        elif o == '-l':
            conf['len'] = eval(a)
#        elif o == '-f':
#            conf['fname'] = a
        else:
            assert False, "unhandled option"

    cmd = CommandInterface()
    cmd.open(conf['port'], conf['baud'])
    mdebug(10, "Open port %(port)s, baud %(baud)d" % {'port':conf['port'], 'baud':conf['baud']})
    try:
        try:
            cmd.initChip()
        except:
            print "Can't init. Ensure that BOOT0 is enabled and reset device"
        bootversion = cmd.cmdGet()
        mdebug(0, "Bootloader version %X" % bootversion)
        mdebug(0, "Chip id `%s'" % str(map(lambda c: hex(ord(c)), cmd.cmdGetID())))
        #cmd.cmdGetVersion()
#    cmd.cmdGetID()
#    cmd.cmdReadoutUnprotect()
        #cmd.cmdWriteUnprotect()
#    cmd.cmdWriteProtect([0, 1])

        if (conf['write'] or conf['verify']):
            data = map(lambda c: ord(c), file(args[0]).read())

        if conf['erase']:
            cmd.cmdEraseMemory()

        if conf['write']:
            cmd.writeMemory(conf['address'], data)

        if conf['verify']:
            verify = cmd.readMemory(conf['address'], len(data))
            if(data == verify):
                print "Verification OK"
            else:
                print "Verification FAILED"
                print str(len(data)) + ' vs ' + str(len(verify))
                for i in xrange(0, len(data)):
                    if data[i] != verify[i]:
                        print hex(i) + ': ' + hex(data[i]) + ' vs ' + hex(verify[i])

        if not conf['write'] and conf['read']:
            rdata = cmd.readMemory(conf['address'], conf['len'])
#            file(conf['fname'], 'wb').write(rdata)
            file(args[0], 'wb').write(''.join(map(chr,rdata)))

        cmd.cmdGo(conf['address'])
    finally:
        cmd.releaseChip()
Example #47
0
def main(argv):
    usage = "Usage: %prog [options] map bot1 bot2\n\nYou must specify a map file."
    parser = OptionParser(usage=usage)

    # map to be played
    # number of players is determined by the map file
    parser.add_option("-m",
                      "--map_file",
                      dest="map",
                      help="Name of the map file")

    # maximum number of turns that the game will be played
    parser.add_option("-t",
                      "--turns",
                      dest="turns",
                      default=1000,
                      type="int",
                      help="Number of turns in the game")

    # the output directory will contain the replay file used by the visualizer
    # it will also contain the bot input/output logs, if requested
    parser.add_option("-o",
                      "--output_dir",
                      dest="output_dir",
                      help="Directory to dump replay files to.")
    parser.add_option("-j",
                      "--stdout",
                      dest="stdout",
                      help="What type of data to output on stdout.")
    parser.add_option("-I",
                      "--log_input",
                      dest="log_input",
                      action="store_true",
                      default=False,
                      help="Log input streams sent to bots")
    parser.add_option("-O",
                      "--log_output",
                      dest="log_output",
                      action="store_true",
                      default=False,
                      help="Log output streams from bots")
    parser.add_option(
        "-E",
        "--log_stderr",
        dest="log_stderr",
        default="stderr",
        help="Where to send bots' stderr output. (file, stderr, ignore)")

    parser.add_option("--serial",
                      dest="serial",
                      action="store_true",
                      help="Run bots in serial, instead of parallel.")

    parser.add_option("-v",
                      "--verbose",
                      dest="verbose",
                      action="store_true",
                      default=False,
                      help="Print out status as game goes.")

    parser.add_option("--turntime",
                      dest="turntime",
                      default=1000,
                      type="int",
                      help="Amount of time to give each bot, in milliseconds")
    parser.add_option("--loadtime",
                      dest="loadtime",
                      default=3000,
                      type="int",
                      help="Amount of time to give for load, in milliseconds")
    parser.add_option("-r",
                      "--rounds",
                      dest="rounds",
                      default=1,
                      type="int",
                      help="Number of rounds to play")
    parser.add_option("--seed",
                      dest="seed",
                      default=None,
                      type="int",
                      help="Seed for the random number generator")

    # ants specific game options
    parser.add_option(
        "--attack",
        dest="attack",
        default="damage",
        help=
        "Attack method to use for engine. (closest, power, support, damage)")
    parser.add_option(
        "--food",
        dest="food",
        default="sections",
        help="Food spawning method. (none, random, sections, symmetric)")
    parser.add_option("--viewradius2",
                      dest="viewradius2",
                      default=55,
                      type="int",
                      help="Vision radius of ants squared")
    parser.add_option("--spawnradius2",
                      dest="spawnradius2",
                      default=1,
                      type="int",
                      help="Spawn radius of ants squared")
    parser.add_option("--attackradius2",
                      dest="attackradius2",
                      default=4,
                      type="int",
                      help="Attack radius of ants squared")
    parser.add_option("--profile",
                      dest="profile",
                      action="store_true",
                      default=False,
                      help="Run under the python profiler")

    (opts, args) = parser.parse_args(argv)
    if opts.map is None or not os.path.exists(opts.map):
        parser.print_help()
        return -1
    try:
        if opts.profile:
            # put profile file into output dir if we can
            prof_file = "ants.profile"
            if opts.output_dir:
                prof_file = os.path.join(opts.output_dir, prof_file)
            # cProfile needs to be explitly told about out local and global context
            print >> sys.stderr, "Running profile and outputting to %s" % (
                prof_file, )
            cProfile.runctx("run_rounds(opts,args)", globals(), locals(),
                            prof_file)
        else:
            # only use psyco if we are not profiling
            # (psyco messes with profiling)
            try:
                import psyco
                psyco.full()
            except ImportError:
                pass
            run_rounds(opts, args)
        return 0
    except Exception:
        traceback.print_exc()
        return -1
Example #48
0
    def main(cmd_args):
        import optparse
        global options, PSYCO
        usage = "\n%prog [options] command [input-file-patterns]\n" + cmd_doc
        oparser = optparse.OptionParser(usage)
        oparser.add_option("-l",
                           "--logfilename",
                           default="",
                           help="contains error messages")
        oparser.add_option(
            "-v",
            "--verbosity",
            type="int",
            default=0,
            help="level of information and diagnostics provided")
        oparser.add_option(
            "-m",
            "--mmap",
            type="int",
            default=-1,
            help="1: use mmap; 0: don't use mmap; -1: accept heuristic")
        oparser.add_option("-e",
                           "--encoding",
                           default="",
                           help="encoding override")
        oparser.add_option(
            "-f",
            "--formatting",
            type="int",
            default=0,
            help="0 (default): no fmt info\n"
            "1: fmt info (all cells)\n",
        )
        oparser.add_option(
            "-g",
            "--gc",
            type="int",
            default=0,
            help=
            "0: auto gc enabled; 1: auto gc disabled, manual collect after each file; 2: no gc"
        )
        oparser.add_option(
            "-s",
            "--onesheet",
            default="",
            help="restrict output to this sheet (name or index)")
        oparser.add_option("-u",
                           "--unnumbered",
                           action="store_true",
                           default=0,
                           help="omit line numbers or offsets in biff_dump")
        oparser.add_option("-d",
                           "--on-demand",
                           action="store_true",
                           default=0,
                           help="load sheets on demand instead of all at once")
        oparser.add_option("-t",
                           "--suppress-timing",
                           action="store_true",
                           default=0,
                           help="don't print timings (diffs are less messy)")
        oparser.add_option("-r",
                           "--ragged-rows",
                           action="store_true",
                           default=0,
                           help="open_workbook(..., ragged_rows=True)")
        options, args = oparser.parse_args(cmd_args)
        if len(args) == 1 and args[0] in ("version", ):
            pass
        elif len(args) < 2:
            oparser.error("Expected at least 2 args, found %d" % len(args))
        cmd = args[0]
        xlrd_version = getattr(xlrd, "__VERSION__", "unknown; before 0.5")
        if cmd == 'biff_dump':
            xlrd.dump(args[1], unnumbered=options.unnumbered)
            sys.exit(0)
        if cmd == 'biff_count':
            xlrd.count_records(args[1])
            sys.exit(0)
        if cmd == 'version':
            print("xlrd: %s, from %s" % (xlrd_version, xlrd.__file__))
            print("Python:", sys.version)
            sys.exit(0)
        if options.logfilename:
            logfile = LogHandler(open(options.logfilename, 'w'))
        else:
            logfile = sys.stdout
        mmap_opt = options.mmap
        mmap_arg = xlrd.USE_MMAP
        if mmap_opt in (1, 0):
            mmap_arg = mmap_opt
        elif mmap_opt != -1:
            print('Unexpected value (%r) for mmap option -- assuming default' %
                  mmap_opt)
        fmt_opt = options.formatting | (cmd in ('xfc', ))
        gc_mode = options.gc
        if gc_mode:
            gc.disable()
        for pattern in args[1:]:
            for fname in glob.glob(pattern):
                print("\n=== File: %s ===" % fname)
                if logfile != sys.stdout:
                    logfile.setfileheading("\n=== File: %s ===\n" % fname)
                if gc_mode == 1:
                    n_unreachable = gc.collect()
                    if n_unreachable:
                        print("GC before open:", n_unreachable,
                              "unreachable objects")
                if PSYCO:
                    import psyco
                    psyco.full()
                    PSYCO = 0
                try:
                    t0 = time.time()
                    bk = xlrd.open_workbook(
                        fname,
                        verbosity=options.verbosity,
                        logfile=logfile,
                        use_mmap=mmap_arg,
                        encoding_override=options.encoding,
                        formatting_info=fmt_opt,
                        on_demand=options.on_demand,
                        ragged_rows=options.ragged_rows,
                    )
                    t1 = time.time()
                    if not options.suppress_timing:
                        print("Open took %.2f seconds" % (t1 - t0, ))
                except xlrd.XLRDError as e:
                    print("*** Open failed: %s: %s" % (type(e).__name__, e))
                    continue
                except KeyboardInterrupt:
                    print("*** KeyboardInterrupt ***")
                    traceback.print_exc(file=sys.stdout)
                    sys.exit(1)
                except BaseException as e:
                    print("*** Open failed: %s: %s" % (type(e).__name__, e))
                    traceback.print_exc(file=sys.stdout)
                    continue
                t0 = time.time()
                if cmd == 'hdr':
                    bk_header(bk)
                elif cmd == 'ov':  # OverView
                    show(bk, 0)
                elif cmd == 'show':  # all rows
                    show(bk)
                elif cmd == '2rows':  # first row and last row
                    show(bk, 2)
                elif cmd == '3rows':  # first row, 2nd row and last row
                    show(bk, 3)
                elif cmd == 'bench':
                    show(bk, printit=0)
                elif cmd == 'fonts':
                    bk_header(bk)
                    show_fonts(bk)
                elif cmd == 'names':  # named reference list
                    show_names(bk)
                elif cmd == 'name_dump':  # named reference list
                    show_names(bk, dump=1)
                elif cmd == 'labels':
                    show_labels(bk)
                elif cmd == 'xfc':
                    count_xfs(bk)
                else:
                    print("*** Unknown command <%s>" % cmd)
                    sys.exit(1)
                del bk
                if gc_mode == 1:
                    n_unreachable = gc.collect()
                    if n_unreachable:
                        print("GC post cmd:", fname, "->", n_unreachable,
                              "unreachable objects")
                if not options.suppress_timing:
                    t1 = time.time()
                    print("\ncommand took %.2f seconds\n" % (t1 - t0, ))

        return None