def process_rides(xml_tree, correct_ele=True): """ Process the rides in the XML tree and generate a list of L{Ride} objects and the bounding box for all of the rides. @param xml_tree: root of C{Element} tree that has rides in it @type xml_tree: C{Element} or C{ElementTree} @param correct_ele: make sure that the segment elevations match-up? @type correct_ele: C{boolean} @return: (C{list} of L{Ride}s,C{bounds} of ride) @rtype: (C{list} of L{Ride},L{Box}) """ check_version(xml_tree) xml_rides = xml_tree.findall('ride') xml_parking_places = xml_tree.findall('parking') xml_segs = xml_tree.findall('segment') xml_turns = xml_tree.findall('turn') xml_stops = xml_tree.findall('stop') xml_pois = xml_tree.findall('poi') bounds = Box() ride_list = [] for ride_index, xml_ride in enumerate(xml_rides): new_ride = _process_ride(ride_index, xml_ride, xml_parking_places, xml_segs, xml_turns, xml_stops, xml_pois, correct_ele) bounds.expand_to_box(new_ride.bounds) ride_list.append(new_ride) return ride_list, bounds
def main(): check_version() parser = build_parser() opts = parser.parse_args() check_opts(opts) if not os.path.isdir(opts.in_path): if os.path.exists(opts.out_path) and os.path.isdir(opts.out_path): out_path = \ os.path.join(opts.out_path,os.path.basename(opts.in_path)) else: out_path = opts.out_path ffwd_to_img(opts.in_path, out_path, opts.checkpoint_dir, device=opts.device) else: files = list_files(opts.in_path) full_in = map(lambda x: os.path.join(opts.in_path,x), files) full_out = map(lambda x: os.path.join(opts.out_path,x), files) if opts.allow_different_dimensions: ffwd_different_dimensions(full_in, full_out, opts.checkpoint_dir, device_t=opts.device, batch_size=opts.batch_size) else : ffwd(full_in, full_out, opts.checkpoint_dir, device_t=opts.device, batch_size=opts.batch_size)
def main(): check_version() parser = build_parser() options = parser.parse_args() check_opts(options) style_target = get_img(options.style) if not options.slow: content_targets = _get_files(options.train_path) elif options.test: content_targets = [options.test] kwargs = { "slow":options.slow, "epochs":options.epochs, "print_iterations":options.checkpoint_iterations, "batch_size":options.batch_size, "save_path":os.path.join(options.checkpoint_dir,'fns.ckpt'), "learning_rate":options.learning_rate, "device":options.device, "total_iterations":options.total_iterations, "base_model_path":options.base_model_path, } if options.slow: if options.epochs < 10: kwargs['epochs'] = 1000 if options.learning_rate < 1: kwargs['learning_rate'] = 1e1 args = [ content_targets, style_target, options.content_weight, options.style_weight, options.tv_weight, options.vgg_path ] for preds, losses, i, epoch in optimize(*args, **kwargs): style_loss, content_loss, tv_loss, loss = losses print('Epoch %d, Iteration: %d, Loss: %s' % (epoch, i, loss)) to_print = (style_loss, content_loss, tv_loss) print('style: %s, content:%s, tv: %s' % to_print) sys.stdout.flush() if options.test: assert options.test_dir != False preds_path = '%s/%s_%s.png' % (options.test_dir,epoch,i) if not options.slow: ckpt_dir = os.path.dirname(options.checkpoint_dir) evaluate.ffwd_to_img(options.test,preds_path, options.checkpoint_dir) else: save_img(preds_path, img) ckpt_dir = options.checkpoint_dir cmd_text = 'python evaluate.py --checkpoint-dir %s ...' % ckpt_dir print("Training complete. For evaluation:\n `%s`" % cmd_text)
def fetch_element(element, conf, verbose): url = "%s%s" % (conf['host'], element.url) if bool_conf_value(conf.get('trailing_slash',"")): url = "%s/" % url if verbose: print "-" * 70 print "Connecting to host: %s" % url print "Using key: %s" % conf['key'] print "Using certificate: %s" % conf['cert'] print "-" * 70 server_response = utils.send_document(url, conf['key'], conf['cert']) if server_response is False: sys.stderr.write("Unable to fetch data from \"%s\".\n" % url) sys.stderr.write("See log for more information.\n") else: if verbose: print "%s\nRecieved data:\n%s" % ("-" * 70, "-" * 70) print server_response data = xmlutils.element_from_string(server_response) if data is False: sys.stderr.write(("Got response from server at url \"%s\", " "but unable to parse. \nError message: %s\n") % (url, e)) else: # Check for valid according to DTD: utils.check_version(data.attrib.get("version")) dtd_validation = xmlutils.dtd_validate(data) if len(dtd_validation) == 0: logging.debug(("Data returned from \"%s\" validated to " "DTD.") % url) found_elements = data.findall( element.xml_tag_name ) sub_elements = [] for found_element in found_elements: sub_elements.append(MetaElement.from_xml_element( found_element, element) ) element.update_handler(sub_elements).process() else: logging.error(("XML recieved for \"%s\" did not " "contain valid XML according to DTD.") % element.xml_tag_name) sys.stderr.write(("Received XML document from server " "on url \"%s\", but did not validate " "against DTD.\n") % url) sys.stderr.write("Logging with \"debug\" will show " "validation errors.\n") dtd_errors = "" for error in dtd_validation: dtd_errors = "%s\n%s" % (dtd_errors, error) logging.debug("XML DTD errors: %s" % dtd_errors)
def parse_history(xml_tree): """ Parse the history element in the given C{Element} tree. @param xml_tree: root of C{Element} tree that has history in it @type xml_tree: C{Element} or C{ElementTree} @return: C{List} of L{HistoryUpdate}s @rtype: C{list} of L{HistoryUpdate} """ check_version(xml_tree) return [_parse_update(xml_update) for xml_update in xml_tree.findall('history/update')]
def parse_photos(xml_tree): """ Parse the photos element in the given C{Element} tree. @param xml_tree: root of C{Element} tree that has photos @type xml_tree: C{Element} or C{ElementTree} @return: a C{PhotoSet} object or None @rtype: C{PhotoSet} """ check_version(xml_tree) xml_photos = xml_tree.find('photos') if xml_photos: return PhotoSet(xml_photos.findtext('title'), xml_photos.findtext('src'), _parse_photos_photo(xml_photos)) else: return None
def parse_top_level(xml_tree): """ Parse all of the simple root elements in an SABX file. The simple root elements are: - uuid - version - zip_prefix - description - ride_type - title - description - terrain @param xml_tree: root of C{Element} tree that has SABX data @type xml_tree: C{Element} or C{ElementTree} @return: C{dict} of root elements @rtype: C{dict} """ check_version(xml_tree) sabx = {} sabx['uuid'] = xml_tree.findtext('uuid') sabx['version'] = xml_tree.findtext('version') sabx['zip_prefix'] = xml_tree.findtext('zip_prefix') desc = et.tostring(xml_tree.find('description')).\ replace("<description>", "").\ replace("</description>", "").\ replace("<description />", "") desc = desc.strip() sabx['ride_type'] = xml_tree.findtext('ride_type') sabx['title'] = xml_tree.findtext('title') sabx['description'] = desc sabx['terrain'] = xml_tree.findtext('terrain') return sabx
def main(): check_version() parser = build_parser() options = parser.parse_args() check_opts(options) style_target = get_img(options.style) if not options.slow: content_targets = _get_files(options.train_path) elif options.test: content_targets = [options.test] model_name = os.path.splitext(os.path.basename(options.style))[0] kwargs = { "slow": options.slow, "epochs": options.epochs, "print_iterations": options.checkpoint_iterations, "batch_size": options.batch_size, "save_path": os.path.join(options.checkpoint_dir, '.'.join([model_name, 'ckpt'])), "learning_rate": options.learning_rate, "device": options.device, "total_iterations": options.total_iterations, "base_model_path": options.base_model_path, } if options.slow: if options.epochs < 10: kwargs['epochs'] = 1000 if options.learning_rate < 1: kwargs['learning_rate'] = 1e1 args = [ content_targets, style_target, options.content_weight, options.style_weight, options.tv_weight, options.vgg_path ] for preds, losses, i, epoch in optimize(*args, **kwargs): style_loss, content_loss, tv_loss, loss = losses print('Epoch %d, Iteration: %d, Loss: %s' % (epoch, i, loss)) to_print = (style_loss, content_loss, tv_loss) print('style: %s, content:%s, tv: %s' % to_print) sys.stdout.flush() if options.test: assert options.test_dir != False preds_path = '%s/%s_%s.png' % (options.test_dir, epoch, i) if not options.slow: ckpt_dir = os.path.dirname(options.checkpoint_dir) evaluate.ffwd_to_img(options.test, preds_path, options.checkpoint_dir) else: save_img(preds_path, img) ckpt_dir = options.checkpoint_dir cmd_text = 'python evaluate.py --checkpoint-dir %s ...' % ckpt_dir print("Training complete. For evaluation:\n `%s`" % cmd_text)
def shouldRunOnHost(self, servertypes, servernames, excluded, inputmgr, force, exact_match): """ Determines whether to run, returns True if hasHost is False, else expects task to have host parameter to check on, and swversion """ run_on_server = True if self.hasHost(): if self.task.servertype != constants.LOCAL: # Always run on locals unless specified a task id found_server = False for servertype in servertypes: # Check if server type is correct # Input validation will have prevented user entering # *,TYPE1 - so if * is in list, it will be the only entry # So no special code needed here to cope with it if servertype == constants.ALL or \ self.host.servertype == servertype: found_server = True if not found_server: log.debug( "Skipping task %s on %s as server not type %s" \ % (self.task.name, self.host.hostname, servertypes)) run_on_server = False found_server = False for name in servernames: # Input validation will have prevented user entering # *,name1 - so if * is in list, it will be the only entry # So no special code needed here to cope with it if name == constants.ALL or \ self.host.hostname == name: found_server = True if not found_server: log.debug("Skipping task %s on %s as host not %s" \ % (self.task.name, self.host.hostname, servernames)) run_on_server = False for exclude in excluded: if self.host.hostname == exclude: log.debug( "Skipping task %s on %s as host excluded" % \ (self.task.name, self.host.hostname)) run_on_server = False # Now check for swversion if we need it swMatch = False swversion = None testSwMatch = False if run_on_server and \ self.task.hasVersion() and self.task.swversion != None: # if version starts with $ then we are looking for # a matching param taskversion = utils.extractIniParam( self.task.config.iniparams, self.task.swversion) if taskversion != self.task.swversion: log.debug( "Taken task swversion %s from ini file parameter %s" \ % (taskversion, self.task.swversion)) if taskversion != None: testSwMatch = True swversion = self.getSWVersion() if swversion == None and not force: swversion = inputmgr.getVersion("software", self.host.hostname) if swversion != None: self.setSWVersion(swversion) if utils.check_version(taskversion, swversion, exact_match): swMatch = True # Now check for osversion if we need it osMatch = False osversion = None testOsMatch = False if run_on_server and \ self.task.hasVersion() and self.task.osversion != None: taskversion = utils.extractIniParam( self.task.config.iniparams, self.task.osversion) if taskversion != self.task.osversion: log.debug( "Taken task osversion %s from ini file parameter %s" \ % (taskversion, self.task.osversion)) if taskversion != None: testOsMatch = True osversion = self.getOSVersion() if osversion == None and not force: osversion = inputmgr.getVersion("OS", self.host.hostname) if osversion != None: self.setOSVersion(osversion) if utils.check_version(taskversion, osversion, exact_match): osMatch = True if run_on_server: # Work out results of version check if (testOsMatch and not osMatch) or \ (testSwMatch and not swMatch) or \ (not testOsMatch and not testSwMatch): log.debug("Passed version check so run task") else: # already at correct osversion/swversion log.debug(REACHED_VERSION.format(self.task.name, self.host.hostname, swversion, osversion)) self.status = constants.REACHED_VERSION run_on_server = False if run_on_server: for key, val in self.task.checkparams.iteritems(): if not key in self.host.params: log.debug(NO_PARAM.format(key, self.host.hostname, self.task.name)) self.status = constants.PARAM_NOTMATCH run_on_server = False else: vals = val.split("|") found = False for eachval in vals: if self.host.params[key] == eachval: found = True if not found: log.debug(INV_PARAM.format(key, self.host.params[key], self.host.hostname, self.task.name)) self.status = constants.PARAM_NOTMATCH run_on_server = False return run_on_server
#!/usr/bin/env python3 import utils, open_color, arcade utils.check_version((3, 7)) # Open the window. Set the window title and dimensions (width and height) arcade.open_window(800, 600, "Smiley Face Example") arcade.set_background_color(open_color.white) # Start the render process. This must be done before any drawing commands. arcade.start_render() face_x, face_y = (400, 300) smile_x, smile_y = (face_x + 0, face_y - 25) eye1_x, eye1_y = (face_x - 50, face_y + 25) eye2_x, eye2_y = (face_x + 50, face_y + 25) catch1_x, catch1_y = (face_x - 50, face_y + 35) catch2_x, catch2_y = (face_x + 50, face_y + 35) # Draw the smiley face: # (x,y,radius,color) arcade.draw_circle_filled(face_x, face_y, 100, open_color.yellow_3) # (x,y,radius,color,border_thickness) arcade.draw_circle_outline(face_x, face_y, 100, open_color.black, 4) #(x,y,width,height,color) arcade.draw_ellipse_filled(eye1_x, eye1_y, 15, 25, open_color.black) arcade.draw_ellipse_filled(eye2_x, eye2_y, 15, 25, open_color.black) arcade.draw_circle_filled(catch1_x, catch1_y, 3, open_color.gray_2) arcade.draw_circle_filled(catch2_x, catch2_y, 3, open_color.gray_2)
#!/usr/bin/env python3 import sys, utils, random # import the modules we will need utils.check_version((3,7)) # make sure we are running at least Python 3.7 utils.clear() # clear the screen #The four lines of text above are explained already, except the first one which tells the computer where to find python. print('Greetings!') #This line prints Greetings! colors = ['red','orange','yellow','green','blue','violet','purple'] #Creates an array called colors containing strings. play_again = '' #Assigns an empty string to a variable caleld play_again. best_count = sys.maxsize # the biggest number, assigns the highest number the system can handle, which is based on operating system, to best_count. while (play_again != 'n' and play_again != 'no'): #Creates a while loop where the condition only returns true when play_again is not "n" or "no" exactly. match_color = random.choice(colors) #Assigns a random color from the colors array to match_color. count = 0 #Sets count to 0. color = '' #Sets color to an empty string. while (color != match_color): #Another while loop that has a condition that returns true when the color variable is not the random color. color = input("\nWhat is my favorite color? ") #\n is a special code that adds a new line, asks user for input that is assigned to color, creating a new line before printing it. color = color.lower().strip() #Removes whitespace and lowercases the string. count += 1 #Increments count by one. if (color == match_color): #If statement that has a condition that returns true when color and match color are exact matches. print('Correct!') #Prints Correct! if the colors are the same. else: #The else, which is what would be run if the condition from before returned false. print('Sorry, try again. You have guessed {guesses} times.'.format(guesses=count)) #Prints the number of guesses, which is the count variable. print('\nYou guessed it in {0} tries!'.format(count)) #Prints the text with the number of guesses after the while loop is done. if (count < best_count): #Tests to see if count is less than the previous best lowest count. print('This was your best guess so far!') #Prints the text if the line before returns true. best_count = count #Reassigns the new best count to best_count. play_again = input("\nWould you like to play again? ").lower().strip() #Asks the user for input on whether they want to play more or not. If they put "n" or "no", it terminates. Otherwise the loop starts again.
main_program=main_program) print("train time cost {:.4f}".format(time.time() - start_time)) print("finish training") if args.is_local: print("run local training") train_loop(fluid.default_main_program()) else: print("run distribute training") t = fluid.DistributeTranspiler() t.transpile(args.trainer_id, pservers=args.endpoints, trainers=args.trainers) if args.role == "pserver": print("run psever") pserver_prog, pserver_startup = t.get_pserver_programs( args.current_endpoint) exe = fluid.Executor(fluid.CPUPlace()) exe.run(pserver_startup) exe.run(pserver_prog) elif args.role == "trainer": print("run trainer") train_loop(t.get_trainer_program()) if __name__ == "__main__": utils.check_version() train()
def main(): ''' The main function for this file. It is run if this file is not used as a module. ''' utils.check_version((3,7)) # make sure we are running at least Python 3.7 utils.clear() # clear the screen print("Adding some numbers") print(add(1,2)) print(add(1,-2)) print(add(1.1,5)) print("Subtracting") print(sub(1,2)) print(sub(1,-2)) print(sub(1.1,5)) print("Multiplication") print(mult(4,2)) print(mult(7,-2)) print(mult(9.3,5)) print("Division") print(div(1,2)) print(div(10,-2)) print(div(1.2,5)) print("Integer or floor division") print(floorDiv(1,2)) print(floorDiv(11,-2)) print(floorDiv(16.4,5)) print("Modulo: getting the remainder after division") print(mod(15,2)) print(mod(16,-2)) print(mod(16.2,5)) print("Exponents") print(exp(10,2)) print(exp(6,-2)) print(exp(2.2,5)) print("Changing the order of operations (with parenthesis)") print(orderOperations(1,2,3)) print(orderOperations(1,-2,-6)) print(orderOperations(1.5,5,0.2)) print("Checking data types") print(whichType(1)) print(whichType(1.0)) print(whichType('1')) print(whichType(True)) print(whichType(False)) print(whichType((1,2))) print(whichType([1,2])) print(whichType({1:2})) print("Converting to integers") print(convertInt(5.2)) print(convertInt('1')) print("Converting to floats") print(convertFloat(44)) print(convertFloat('1')) print("Converting to strings") print(convertStr(5.2)) print(convertStr(100)) print("String concatenation") print(concat('This is a ','test')) print(concat('Hello,',' World!')) print("Slicing") print(whichChar('This is a test of the emergency broadcast system.',1)) print(whichChar('This is a test of the emergency broadcast system.',2)) print(whichChar('This is a test of the emergency broadcast system.',10)) print(whichChar('This is a test of the emergency broadcast system.',-1)) print("Slicing substrings") print(substr('This is a test of the emergency broadcast system.',0,100)) print(substr('This is a test of the emergency broadcast system.',2,5)) print(substr('This is a test of the emergency broadcast system.',10,12)) print(substr('This is a test of the emergency broadcast system.',-5,-1)) print("Reversing strings") print(reverseStr('This is a test of the emergency broadcast system.')) print(reverseStr('Hello, World!')) print("Finding list items") print(isIn([1,2,3,4,5,6,7,8],5)) print(isIn(['A','B','C','D'],'C')) print(isIn([1,2,3,4,5,6,7,8],10)) print(isIn(['A','B','C','D'],'E')) print("Returning random list elements") print(randomElement([1,2,3,4,5,6,7,8])) print(randomElement(['A','B','C','D'])) print(randomElement(['G','Hello',1.5,(5,5)])) print("Random numbers") print(randomNumber()) print(randomNumber()) print(randomNumber()) print("Reversing lists") print(reverseList([1,2,3,4,5,6])) print(reverseList(['a','b','c','d','e','f'])) print(reverseList(['G','Hello',1.5,(5,5)])) print("Randomizing lists") print(shuffleList([1,2,3,4,5,6])) print(shuffleList(['a','b','c','d','e','f'])) print(shuffleList(['G','Hello',1.5,(5,5)])) print("Making new lists of sequential numbers") print(listUntil(10)) print(listUntil(50)) print(listUntil(4)) print(listUntil(-5))
#!/usr/bin/python import utils import app if __name__ == "__main__": try: # check if options are given right and return the switches in a dict switches = utils.check_options() # display the version and exit, if switch is given utils.check_version(switches) # display the help and exit, if switch is given utils.check_help(switches) # manipulate the switches app.engine(switches) except KeyboardInterrupt: print "\nbye"
#!/usr/bin/env python3 import utils, open_color, arcade # import utils for python version check # import open_color for color the drawings # import arcade to draw stuff utils.check_version((3, 7)) # python version check SCREEN_WIDTH = 800 # setup the window width SCREEN_HEIGHT = 600 # setup the window height SCREEN_TITLE = "Smiley Face Example" # setup the title of the window class Faces(arcade.Window): # A class of Faces """ Our custom Window Class""" def __init__(self): # constructor of the class """ Initializer """ # Call the parent class initializer super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) # Show the mouse cursor self.set_mouse_visible(True) self.x = SCREEN_WIDTH / 2 # set the starting width position of the mouse cursor self.y = SCREEN_HEIGHT / 2 # set the starting height position of the mouse cursor arcade.set_background_color( open_color.white) # set the background color to white def on_draw(self): # A function to draw """ Draw the face """ arcade.start_render() # start the drawing render
Example of use: 1. Run with default parameters (specified in file) $python LZ_sim_anneal 2. Run with optional parameters: 30 quenches, 20 times steps, action_set, outfile, max number of fidelity evaluations, time_scale, number of restarts, verbose, symmetrize_protocol: $python LZ_sim_anneal.py 30 20 bang-bang8 out.txt 3000 0.05 100 False True 3. Get some help $python LZ_sim_anneal -h ''' import utils as ut import sys,os # for running in batch from terminal ut.check_version() import numpy as np import pickle import Hamiltonian_alex as Hamiltonian from quspin.operators import exp_op import time from analysis.compute_observable import MB_observables np.set_printoptions(precision=4) def main(): ut.check_sys_arg(sys.argv) global action_set,hx_discrete,hx_max#,FIX_NUMBER_FID_EVAL
def OnInit(self): global client_id utils.assert_folders() utils.migrate_from_tmp() try: setup_log() except: wx.MessageBox('Another instance of Assembly is running', 'Unable to start',wx.OK | wx.ICON_ERROR) sys.exit(0) platform = utils.get_platform() auto_upgrade = utils.string2bool(platform['autoupgrade']) if len(sys.argv) > 1: utils.add_user_attribute('show_info_popup','True') utils.delete_folder_async('%s/upgrade' %os.getcwd()) wx.MessageBox('Congratulations! Assembly64 was upgraded from version %s to %s.' %(sys.argv[1], version), 'Assembly64 upgraded!',wx.OK | wx.ICON_INFORMATION) try: utils.update_server_db() newer_available,force,available_version = utils.check_version(version) if newer_available and force: update_dia = UpdateDialog(None,"New version available", "New version available. Upgrade is vital!",auto_upgrade, True) update_dia.ShowModal() if update_dia.is_app_upgrade(): upgrade = UpgradeSplash() upgrade.Show() utils.do_upgrade(upgrade,version,platform) os._exit(1) elif newer_available and not force: update_dia = UpdateDialog(None,"New version available", "New version available, but you can stay with this one.. For now!", auto_upgrade, False) update_dia.ShowModal() if update_dia.is_app_upgrade(): upgrade = UpgradeSplash() upgrade.Show() utils.do_upgrade(upgrade,version,platform) os._exit(1) except FtpOverloadedException: wx.MessageBox('Too many users right now, please try later', 'Assembly Error',wx.OK | wx.ICON_WARNING) sys.exit(0) except ftplib.all_errors as a: wx.MessageBox('Unable to communicate with Assembly64 server.', 'Assembly Error',wx.OK | wx.ICON_WARNING) sys.exit(0) except: wx.MessageBox('Unable to communicate with assembly64 server.', 'Assembly Error',wx.OK | wx.ICON_WARNING) sys.exit(0) if not utils.has_attribute('uid'): client_id = str(uuid.uuid1()) utils.add_user_attribute('uid',client_id) post_ga_event('application','startup_new_user') else: client_id = utils.get_user_attribute('uid') post_ga_event('application','startup_existing_user') if not utils.has_attribute('show_info_popup'): utils.add_user_attribute('show_info_popup','true') if utils.has_attribute(delete_files_after_install) is False: utils.add_user_attribute(delete_files_after_install,'true') thread = Thread(target = update_db,args = (10, )) thread.start() AssemblySplash().Show() return 1
#!/usr/bin/env python3 import utils, open_color, arcade #Import the necessary libraries into the file utils.check_version( (3, 7) ) #Checks to verify that the user has python 3.7 downloaded on their computer SCREEN_WIDTH = 800 # This sets the screen width to be 800 pixels SCREEN_HEIGHT = 600 # This sets the screen height to be 600 pixels SCREEN_TITLE = "Smiley Face Example" # This sets the screen title to say "Smiley Face Example" at the top of the window class Faces( arcade.Window ): #Creates a class in the file, which purpose is to create a window inside of the pop-up arcade box to track where the mouse is. """ Our custom Window Class""" def __init__( self ): # This is an initializer that initializes the class window to be the pop-up game window. This lets python track where the mouse is inside of the window. """ Initializer """ # Call the parent class initializer super().__init__( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE ) #Actually calls the initializer with the variables being the width, height, and name of the window declared above # Show the mouse cursor self.set_mouse_visible( True) #Tells the class that the mouse is visible to the program self.x = SCREEN_WIDTH / 2 #This is the x variable where the mouse location is stored. it is divided by 2 because the face must be centered around the mouse.
#!/usr/bin/env python3 import utils, open_color, arcade # Imported information utils.check_version((3, 7)) # The version of Python SCREEN_WIDTH = 800 # Width of screen SCREEN_HEIGHT = 600 # Height of screen SCREEN_TITLE = "Smiley Face Example" # Text that displays at top of screen class Faces(arcade.Window): """ Our custom Window Class""" def __init__(self): """ Initializer """ # Call the parent class initializer super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) # Show the mouse cursor self.set_mouse_visible(True) self.x = SCREEN_WIDTH / 2 # Parameters of the face self.y = SCREEN_HEIGHT / 2 # Parameters of the face arcade.set_background_color( open_color.white) # Background color is white def on_draw(self): # Place the image on the cursor """ Draw the face """ arcade.start_render() # Start the rendering of the face face_x, face_y = (self.x, self.y
#!/usr/bin/env python3 import utils, open_color, arcade # imports some libraries utils.check_version((3,7)) # checks the python version SCREEN_WIDTH = 800 # assigns SCREEN_WIDTH a value of 800 SCREEN_HEIGHT = 600 # assigns SCREEN_HEIGHT a value of 600 SCREEN_TITLE = "Smiley Face Example" # assigns SCREEN_TITLE a value of "Smiley Face Example" class Faces(arcade.Window): # creates the custom window class """ Our custom Window Class""" def __init__(self): # this is the initializer """ Initializer """ # Call the parent class initializer super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) # calls the class initializer # Show the mouse cursor self.set_mouse_visible(True) # shows the mouse cursor self.x = SCREEN_WIDTH / 2 # assigns self.x the value of 1/2 of the SCREEN_WIDTH variable self.y = SCREEN_HEIGHT / 2 # assigns self.y the value of 1/2 of the SCREEN_HEIGHT variable arcade.set_background_color(open_color.white) # sets the background color of the image to white def on_draw(self): # draws the face """ Draw the face """ arcade.start_render() # starts the arcade renderer face_x,face_y = (self.x,self.y) # assigns face_x and face_y the values of self.x and self.y respectfully smile_x,smile_y = (face_x + 0,face_y - 10) # assigns smile_x and smile_y the values of face_x + 0 and face_y -10 respectfully
if res: xml_data = res.read() if verbose: print "%s\nRecieved data:\n%s" % ("-" * 70, "-" * 70) print xml_data try: return_data = lxml.etree.fromstring(xml_data) except lxml.etree.XMLSyntaxError, e: logging.error(("Error parsing XML document from server: " "%s") % e) sys.stderr.write(("Got response from server at url \"%s\", " "but unable to parse. Error message: %s") % (url, e)) else: # Check for valid according to DTD: utils.check_version(return_data.attrib.get("version")) valid = dtd.validate(return_data) if valid: logging.debug(("Data returned from \"%s\" validated to " "DTD.") % url) found_elements = return_data.findall( element.xml_tag_name ) sub_elements = [] for found_element in found_elements: sub_elements.append(MetaElement.from_xml_element( found_element, element) ) element.update_handler(sub_elements).process() else: logging.error(("XML recieved for \"%s\" did not "
def shouldRunOnHost(self, servertypes, servernames, excluded, inputmgr, force, exact_match): """ Determines whether to run, returns True if hasHost is False, else expects task to have host parameter to check on, and swversion """ run_on_server = True if self.hasHost(): if self.task.servertype != constants.LOCAL: # Always run on locals unless specified a task id found_server = False for servertype in servertypes: # Check if server type is correct # Input validation will have prevented user entering # *,TYPE1 - so if * is in list, it will be the only entry # So no special code needed here to cope with it if servertype == constants.ALL or \ self.host.servertype == servertype: found_server = True if not found_server: log.debug( "Skipping task %s on %s as server not type %s" \ % (self.task.name, self.host.hostname, servertypes)) run_on_server = False found_server = False for name in servernames: # Input validation will have prevented user entering # *,name1 - so if * is in list, it will be the only entry # So no special code needed here to cope with it if name == constants.ALL or \ self.host.hostname == name: found_server = True if not found_server: log.debug("Skipping task %s on %s as host not %s" \ % (self.task.name, self.host.hostname, servernames)) run_on_server = False for exclude in excluded: if self.host.hostname == exclude: log.debug( "Skipping task %s on %s as host excluded" % \ (self.task.name, self.host.hostname)) run_on_server = False # Now check for swversion if we need it swMatch = False swversion = None testSwMatch = False if run_on_server and \ self.task.hasVersion() and self.task.swversion != None: # if version starts with $ then we are looking for # a matching param taskversion = utils.extractIniParam( self.task.config.iniparams, self.task.swversion) if taskversion != self.task.swversion: log.debug( "Taken task swversion %s from ini file parameter %s" \ % (taskversion, self.task.swversion)) if taskversion != None: testSwMatch = True swversion = self.getSWVersion() if swversion == None and not force: swversion = inputmgr.getVersion( "software", self.host.hostname) if swversion != None: self.setSWVersion(swversion) if utils.check_version(taskversion, swversion, exact_match): swMatch = True # Now check for osversion if we need it osMatch = False osversion = None testOsMatch = False if run_on_server and \ self.task.hasVersion() and self.task.osversion != None: taskversion = utils.extractIniParam( self.task.config.iniparams, self.task.osversion) if taskversion != self.task.osversion: log.debug( "Taken task osversion %s from ini file parameter %s" \ % (taskversion, self.task.osversion)) if taskversion != None: testOsMatch = True osversion = self.getOSVersion() if osversion == None and not force: osversion = inputmgr.getVersion( "OS", self.host.hostname) if osversion != None: self.setOSVersion(osversion) if utils.check_version(taskversion, osversion, exact_match): osMatch = True if run_on_server: # Work out results of version check if (testOsMatch and not osMatch) or \ (testSwMatch and not swMatch) or \ (not testOsMatch and not testSwMatch): log.debug("Passed version check so run task") else: # already at correct osversion/swversion log.debug( REACHED_VERSION.format(self.task.name, self.host.hostname, swversion, osversion)) self.status = constants.REACHED_VERSION run_on_server = False if run_on_server: for key, val in self.task.checkparams.iteritems(): if not key in self.host.params: log.debug( NO_PARAM.format(key, self.host.hostname, self.task.name)) self.status = constants.PARAM_NOTMATCH run_on_server = False else: vals = val.split("|") found = False for eachval in vals: if self.host.params[key] == eachval: found = True if not found: log.debug( INV_PARAM.format(key, self.host.params[key], self.host.hostname, self.task.name)) self.status = constants.PARAM_NOTMATCH run_on_server = False return run_on_server
if args.do_train: compiled_prog = fluid.compiler.CompiledProgram(build_res["train_prog"]).with_data_parallel( \ loss_name=build_res["cost"].name, \ build_strategy=build_strategy, \ exec_strategy=exec_strategy) build_res["compiled_prog"] = compiled_prog if args.do_test: test_compiled_prog = fluid.compiler.CompiledProgram( build_res["test_prog"]) build_res["test_compiled_prog"] = test_compiled_prog if args.do_eval: eval_compiled_prog = fluid.compiler.CompiledProgram( build_res["eval_prog"]) build_res["eval_compiled_prog"] = eval_compiled_prog if args.do_train: train(args, exe, build_res, place) if args.do_eval: evaluate(args, exe, build_res, "eval", \ save_result=True, id2intent=id2intent) if args.do_test: evaluate(args, exe, build_res, "test",\ save_result=True, id2intent=id2intent) if __name__ == "__main__": logger.info("the paddle version is %s" % paddle.__version__) check_version('1.6.0') print_arguments(args) main(args)
#!/usr/bin/env python3 import utils, open_color, arcade #gets all outside sources needed utils.check_version((3,7)) #makes sure you are on the right python version SCREEN_WIDTH = 800 #sets the width SCREEN_HEIGHT = 600 #sets the height SCREEN_TITLE = "Smiley Face Example" #names the screen class Faces(arcade.Window): #makes the class """ Our custom Window Class""" #gives class description def __init__(self): #sets up the class """ Initializer """ # Call the parent class initializer super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)#calls for information outside the class # Show the mouse cursor self.set_mouse_visible(True)#lets you see mouse curser self.x = SCREEN_WIDTH / 2 #sets x to half the screen width self.y = SCREEN_HEIGHT / 2 #sets y to half the screen height arcade.set_background_color(open_color.white) #makes background white def on_draw(self): #defines the face """ Draw the face """ #says what it does arcade.start_render() #starts the render face_x,face_y = (self.x,self.y) #centers face smile_x,smile_y = (face_x + 0,face_y - 10) #sets smile