def __init__(self): # Creates the screen pygame.init() size = [config.screen_x, config.screen_y] got_resolution_x = pygame.display.Info().current_w got_resolution_y = pygame.display.Info().current_h log( "Attempting to start screen of size " + str(size) + " on monitor of size [" + str(got_resolution_x) + ", " + str(got_resolution_y) + "]", 2) if size[0] > got_resolution_x or size[1] > got_resolution_y: log( "Screen resolution [" + str(got_resolution_x) + ", " + str(got_resolution_y) + "] too small to fit requested resolution " + str(size) + ", exiting", 0) self.kill_threads() sys.exit() self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN) log("Master screen started", 2) # Creates and starts the update thread self.update_thread = UpdateThread(self) self.update_thread.start() self.last_tick = pygame.time.get_ticks()
def to_xml(self): str_event_id = u'<Event id="{0}"/>'.format(self.eventId) str_provider_id = u'<Provider id="{0}"/>'.format(self.providerId) str_record_format = u'<Param Name="{0}" Value="{1}" T="{2}" />' str_record_no_quote_format = u'<Param Name="{0}" Value={1} T="{2}" />' str_mt_str = u'mt:wstr' str_mt_u_int64 = u'mt:uint64' str_mt_bool = u'mt:bool' str_mt_float = u'mt:float64' str_events_data = u"" for attName in self.__dict__: if attName in ["eventId", "filedCount", "providerId"]: continue att_value = self.__dict__[attName] if type(att_value) is int: str_events_data += str_record_format.format(attName, att_value, str_mt_u_int64) continue if type(att_value) is str: att_value = xml_utils.quoteattr(att_value) str_events_data += str_record_no_quote_format.format(attName, att_value, str_mt_str) continue if str(type(att_value)).count("'unicode'") > 0: att_value = xml_utils.quoteattr(att_value) str_events_data += str_record_no_quote_format.format(attName, att_value, str_mt_str) continue if type(att_value) is bool: str_events_data += str_record_format.format(attName, att_value, str_mt_bool) continue if type(att_value) is float: str_events_data += str_record_format.format(attName, att_value, str_mt_float) continue logger.log( "Warning: property " + attName + ":" + str(type(att_value)) + ":type" + str(type(att_value)) + "Can't convert to events data:" + ":type not supported") return u"<Data>{0}{1}{2}</Data>".format(str_provider_id, str_event_id, str_events_data)
def update(self): super().update() self.collider_box.y = int(self.scroll + self.offset + self.img_height / 2 - self.circle_radius) cursor_x = self.master.cursor.x_pos cursor_y = self.master.cursor.y_pos # If box is selected if self.master.cursor.is_valid \ and self.collider_box.collidepoint(cursor_x, cursor_y): # Increase confidence user is actually "clicking" on the box self.is_selected += 3 if self.is_selected > 255: log("Button pressed to return home", 2) self.is_selected = 0 self.master.close() map.run(self.master.parent.parent) else: # Decrease confidence user is "clicking" on the box if self.is_selected > 0: self.is_selected -= 10 if self.is_selected < 0: self.is_selected = 0
def update(self): # Move box with background so it's "stationary" self.box.x = self.base_x + self.background.off_x self.box.y = self.base_y + self.background.off_y cursor_x = self.background.cursor.x_pos cursor_y = self.background.cursor.y_pos # If box is selected if self.background.cursor.is_valid \ and self.box.collidepoint(cursor_x, cursor_y): # Increase confidence user is actually "clicking" on the box self.is_selected += 3 if self.is_selected > 255: log("Button pressed", 2) self.is_selected = 0 self.parent.close() info.run(self.master_window, self.target) else: # Decrease confidence user is "clicking" on the box if self.is_selected > 0: self.is_selected -= 10 if self.is_selected < 0: self.is_selected = 0
def update(self): super().update() if self.state == States.GOING_TO_TARGET: x_distance = self.target_x - self.x offset_x = x_distance y_distance = self.target_y - self.y offset_y = y_distance magnitude = sqrt(x_distance**2 + y_distance**2) x_distance /= magnitude y_distance /= magnitude x_distance *= self.speed y_distance *= self.speed if abs(offset_x) < abs(x_distance) + 0.1 and abs( offset_y) < abs(y_distance) + 0.1: self.x = self.target_x self.y = self.target_y self.state = States.SHRINKING else: self.x += x_distance self.y += y_distance elif self.state == States.CALIBRATING: if not self.is_calibrating(): self.state = States.GROWING log("Calibrated point", 2) self.color = WHITE elif self.state == States.GETTING_TARGET: if self.calibrations_remaining: self.calibrations_remaining -= 1 self.current_target, self.target_x, self.target_y = self.get_target( ) self.state = States.GOING_TO_TARGET log( "Going to point " + str(self.target_x) + "," + str(self.target_y), 2) else: self.state = States.DONE log("Calibration done", 1) self.get_scoring() self.apply() elif self.state == States.DONE: pass elif self.state == States.GROWING: if self.size < self.grown_size: self.size += self.grow_speed else: self.state = States.GETTING_TARGET elif self.state == States.SHRINKING: if self.size > self.shrunk_size: self.size -= self.shrink_speed else: self.start_calibrating self.state = States.CALIBRATING self.color = RED
def parse(xml_text, configuration, is_deprovision=False): """ Parse xml tree, retrieving user and ssh key information. Return self. """ ofv_env = OvfEnv() logger.log_if_verbose(re.sub("<UserPassword>.*?<", "<UserPassword>*<", xml_text)) dom = xml.dom.minidom.parseString(xml_text) if len(dom.getElementsByTagNameNS(ofv_env.OvfNs, "Environment")) != 1: logger.error("Unable to parse OVF XML.") section = None newer = False for p in dom.getElementsByTagNameNS(ofv_env.WaNs, "ProvisioningSection"): for n in p.childNodes: if n.localName == "Version": verparts = get_node_text_data(n).split('.') major = int(verparts[0]) minor = int(verparts[1]) if major > ofv_env.MajorVersion: newer = True if major != ofv_env.MajorVersion: break if minor > ofv_env.MinorVersion: newer = True section = p if newer: logger.warning( "Newer provisioning configuration detected. Please consider updating waagent.") if section is None: logger.error( "Could not find ProvisioningSection with major version=" + str(ofv_env.MajorVersion)) return None ofv_env.ComputerName = get_node_text_data(section.getElementsByTagNameNS(ofv_env.WaNs, "HostName")[0]) ofv_env.UserName = get_node_text_data(section.getElementsByTagNameNS(ofv_env.WaNs, "UserName")[0]) if is_deprovision: return ofv_env try: ofv_env.UserPassword = get_node_text_data(section.getElementsByTagNameNS(ofv_env.WaNs, "UserPassword")[0]) except (KeyError, ValueError, AttributeError, IndexError): pass try: cd_section = section.getElementsByTagNameNS(ofv_env.WaNs, "CustomData") if len(cd_section) > 0: ofv_env.CustomData = get_node_text_data(cd_section[0]) if len(ofv_env.CustomData) > 0: ext_utils.set_file_contents(constants.LibDir + '/CustomData', bytearray( translate_custom_data(ofv_env.CustomData, configuration))) logger.log('Wrote ' + constants.LibDir + '/CustomData') else: logger.error('<CustomData> contains no data!') except Exception as e: logger.error(str(e) + ' occured creating ' + constants.LibDir + '/CustomData') disable_ssh_passwd = section.getElementsByTagNameNS(ofv_env.WaNs, "DisableSshPasswordAuthentication") if len(disable_ssh_passwd) != 0: ofv_env.DisableSshPasswordAuthentication = (get_node_text_data(disable_ssh_passwd[0]).lower() == "true") for pkey in section.getElementsByTagNameNS(ofv_env.WaNs, "PublicKey"): logger.log_if_verbose(repr(pkey)) fp = None path = None for c in pkey.childNodes: if c.localName == "Fingerprint": fp = get_node_text_data(c).upper() logger.log_if_verbose(fp) if c.localName == "Path": path = get_node_text_data(c) logger.log_if_verbose(path) ofv_env.SshPublicKeys += [[fp, path]] for keyp in section.getElementsByTagNameNS(ofv_env.WaNs, "KeyPair"): fp = None path = None logger.log_if_verbose(repr(keyp)) for c in keyp.childNodes: if c.localName == "Fingerprint": fp = get_node_text_data(c).upper() logger.log_if_verbose(fp) if c.localName == "Path": path = get_node_text_data(c) logger.log_if_verbose(path) ofv_env.SshKeyPairs += [[fp, path]] return ofv_env
def _set_user_account_pub_key(protect_settings, hutil): ovf_xml = None ovf_env = None try: ovf_xml = ext_utils.get_file_contents('/var/lib/waagent/ovf-env.xml') ovf_env = ovf_utils.OvfEnv.parse(ovf_xml, Configuration) except (EnvironmentError, ValueError, KeyError, AttributeError): pass if ovf_xml is None or ovf_env is None: # default ovf_env with empty data ovf_env = ovf_utils.OvfEnv() logger.log("could not load ovf-env.xml") # user name must be provided if set ssh key or password if not protect_settings or 'username' not in protect_settings: return user_name = protect_settings['username'] user_pass = protect_settings.get('password') cert_txt = protect_settings.get('ssh_key') expiration = protect_settings.get('expiration') no_convert = False if not user_pass and not cert_txt and not ovf_env.SshPublicKeys: raise Exception("No password or ssh_key is specified.") if user_pass is not None and len(user_pass) == 0: user_pass = None hutil.log("empty passwords are not allowed, ignoring password reset") # Reset user account and password, password could be empty sudoers = _get_other_sudoers(user_name) error_string = MyDistro.create_account(user_name, user_pass, expiration, None) _save_other_sudoers(sudoers) if error_string is not None: err_msg = "Failed to create the account or set the password" ext_utils.add_extension_event(name=hutil.get_name(), op=constants.WALAEventOperation.Enable, is_success=False, message="(02101)" + err_msg) raise Exception(err_msg + " with " + error_string) hutil.log("Succeeded in creating the account or setting the password.") # Allow password authentication if user_pass is provided if user_pass is not None: ext_utils.add_extension_event(name=hutil.get_name(), op="scenario", is_success=True, message="create-user-with-password") _allow_password_auth() # Reset ssh key with the new public key passed in or reuse old public key. if cert_txt: if cert_txt and cert_txt.strip().lower().startswith("ssh-rsa"): no_convert = True try: pub_path = os.path.join('/home/', user_name, '.ssh', 'authorized_keys') ovf_env.UserName = user_name if no_convert: if cert_txt: pub_path = ovf_env.prepare_dir(pub_path, MyDistro) final_cert_txt = cert_txt if not cert_txt.endswith("\n"): final_cert_txt = final_cert_txt + "\n" ext_utils.append_file_contents(pub_path, final_cert_txt) MyDistro.set_se_linux_context( pub_path, 'unconfined_u:object_r:ssh_home_t:s0') ext_utils.change_owner(pub_path, user_name) ext_utils.add_extension_event(name=hutil.get_name(), op="scenario", is_success=True, message="create-user") hutil.log("Succeeded in resetting ssh_key.") else: err_msg = "Failed to reset ssh key because the cert content is empty." ext_utils.add_extension_event( name=hutil.get_name(), op=constants.WALAEventOperation.Enable, is_success=False, message="(02100)" + err_msg) else: # do the certificate conversion # we support PKCS8 certificates besides ssh-rsa public keys _save_cert_str_as_file(cert_txt, 'temp.crt') pub_path = ovf_env.prepare_dir(pub_path, MyDistro) retcode = ext_utils.run_command_and_write_stdout_to_file([ constants.Openssl, 'x509', '-in', 'temp.crt', '-noout', '-pubkey' ], "temp.pub") if retcode > 0: raise Exception("Failed to generate public key file.") MyDistro.ssh_deploy_public_key('temp.pub', pub_path) os.remove('temp.pub') os.remove('temp.crt') ext_utils.add_extension_event(name=hutil.get_name(), op="scenario", is_success=True, message="create-user") hutil.log("Succeeded in resetting ssh_key.") except Exception as e: hutil.log(str(e)) ext_utils.add_extension_event( name=hutil.get_name(), op=constants.WALAEventOperation.Enable, is_success=False, message="(02100)Failed to reset ssh key.") raise e
def initialize(): global connected_device log("Getting connected eye trackers", 3) device_list = device_enumerate() for device in device_list: if get_status(device) is 1: log("Starting device " + str(device), 2) start(device) log(("Waiting for device " + str(device) + " to start"), 3) while get_status(device) is not 3: pass log(("Device " + str(device) + " started"), 3) if len(device_list) is 0: log("No eye tracker device found, exiting", 0) sys.exit() elif len(device_list) > 1: log("More than 1 device found", 1) connected_device = get_best_camera(device_list) else: connected_device = device_list[0]
def __display_error(code): if code is not 0: log("QL Error: " + error_list[code], 0)
def stop_all(): log("Stopping all devices", 3) func = dll.QLDevice_Stop_All __display_error(func()) log("All devices stopped", 2)
def run(self): global cursor log("Starting update thread", 3) while thread_manager.running: cursor.update() thread_manager.clock.tick(60)
def set_window(self, window): log("Changed active window to " + str(window), 3) self.current_window = window
def close(self): log("Closing window", 3) for child in self.child_list: log("Closing instance " + str(child), 3) child.close()
def unregister(self, child): if child in self.child_list: self.child_list.remove(child) log("Unregistered " + str(child), 3)
def optimize(log_output=False, dest='Mars'): # AU # earth_radius = 0.00004258756 # AU^3/year^2 # earth_attractor = 0.0001184 phi = [np.random.uniform(0, 2 * np.pi) for i in range(2) ] + [0] + [np.random.uniform(0, 2 * np.pi) for i in range(5)] Earth = Planet(1, 1, phi[2], "Earth") Mercury = Planet(0.374496, 0.241, phi[0], "Mercury") Mars = Planet(1.5458, 1.8821, phi[3], "Mars") Venus = Planet(0.726088, 0.6156, phi[1], "Venus") Jupiter = Planet(5.328, 11.87, phi[4], "Jupiter") Saturn = Planet(9.5497, 29.446986, phi[5], "Saturn") Uranus = Planet(19.2099281, 84.01538, phi[6], "Uranus") Neptune = Planet(30.0658708, 164.78845, phi[7], "Neptune") num_gens = 1 num_evolutions = 75 pop_size = 200 cometX = Comet() if dest == "Comet": planets = [ Earth, Earth, Mercury, Mars, Venus, Jupiter, Saturn, Neptune, Uranus, cometX ] else: choices = [ Earth, Earth, Mercury, Mars, Venus, Jupiter, Saturn, Neptune, Uranus ] destination = [x for x in choices if x.get_name() == dest] choices.remove(destination[0]) planets = choices + [destination[0]] if dest == "Venus" or dest == "Mercury": max_enctrs = 1 else: max_enctrs = len(planets) - 2 times = [0] + [0.1] * (max_enctrs + 1) max_times = [5] * (max_enctrs + 2) # optimize t0 = time.time() udp = gprob(planets, times, max_times, max_enctr=max_enctrs) uda = pg.algorithm(pg.sade(gen=num_gens, memory=True)) if (not log_output ): # this avoids the persistent looping to get the fitness data archi = pg.archipelago(algo=uda, prob=udp, n=8, pop_size=pop_size) archi.evolve(num_evolutions) archi.wait() else: # this is where we loop and evolve and get the fitness data for each island archi = pg.archipelago(algo=uda, prob=udp, n=8, pop_size=pop_size) islands = [] for i in range(num_evolutions): archi.evolve() archi.wait() avgFit = [ -1.0 * np.average(island.get_population().get_f()) for island in archi ] islands.append(np.array(avgFit)) # islands.append(np.array(archi.get_champions_f())) # get the best scores from each island after each stage showlog(np.array(islands), 8, num_evolutions) t1 = time.time() sols = archi.get_champions_f() idx = sols.index(min(sols)) # print("index: {}, Scores: ".format(idx) + str(sols) + "\n\n") mission = udp.pretty(archi.get_champions_x()[idx]) # [print(str(l) + "\n") for l in mission] convert(mission[0], mission[1], mission[2]) logger.log(mission[1][0], mission[1][-1], phi) print("\n\nTime for soln: {} sec\n\n".format(t1 - t0))
def create_account(self, user, password, expiration, thumbprint): """ Create a user account, with 'user', 'password', 'expiration', ssh keys and sudo permissions. Returns None if successful, error string on failure. """ userentry = None try: userentry = pwd.getpwnam(user) except (EnvironmentError, KeyError): pass uidmin = None try: if os.path.isfile("/etc/login.defs"): uidmin = int(ext_utils.get_line_starting_with("UID_MIN", "/etc/login.defs").split()[1]) except (ValueError, KeyError, AttributeError, EnvironmentError): pass pass if uidmin is None: uidmin = 100 if userentry is not None and userentry[2] < uidmin: logger.error( "CreateAccount: " + user + " is a system user. Will not set password.") return "Failed to set password for system user: "******" (0x06)." if userentry is None: command = ['pw', 'useradd', user, '-m'] if expiration is not None: command += ['-e', expiration.split('.')[0]] if ext_utils.run(command): logger.error("Failed to create user account: " + user) return "Failed to create user account: " + user + " (0x07)." else: logger.log( "CreateAccount: " + user + " already exists. Will update password.") if password is not None: self.change_password(user, password) try: # for older distros create sudoers.d if not os.path.isdir(self.sudoers_dir_base + '/sudoers.d/'): # create the /etc/sudoers.d/ directory os.mkdir(self.sudoers_dir_base + '/sudoers.d') # add the include of sudoers.d to the /etc/sudoers ext_utils.set_file_contents( self.sudoers_dir_base + '/sudoers', ext_utils.get_file_contents( self.sudoers_dir_base + '/sudoers') + '\n#includedir ' + self.sudoers_dir_base + '/sudoers.d\n') if password is None: ext_utils.set_file_contents( self.sudoers_dir_base + "/sudoers.d/waagent", user + " ALL = (ALL) NOPASSWD: ALL\n") else: ext_utils.set_file_contents(self.sudoers_dir_base + "/sudoers.d/waagent", user + " ALL = (ALL) ALL\n") os.chmod(self.sudoers_dir_base + "/sudoers.d/waagent", 0o440) except (ValueError, KeyError, AttributeError, EnvironmentError): logger.error("CreateAccount: Failed to configure sudo access for user.") return "Failed to configure sudo privileges (0x08)." home = self.get_home() if thumbprint is not None: ssh_dir = home + "/" + user + "/.ssh" ext_utils.create_dir(ssh_dir, user, 0o700) pub = ssh_dir + "/id_rsa.pub" prv = ssh_dir + "/id_rsa" ext_utils.run_command_and_write_stdout_to_file(['sh-keygen', '-y', '-f', thumbprint + '.prv'], pub) ext_utils.set_file_contents( prv, ext_utils.get_file_contents(thumbprint + ".prv")) for f in [pub, prv]: os.chmod(f, 0o600) ext_utils.change_owner(f, user) ext_utils.set_file_contents( ssh_dir + "/authorized_keys", ext_utils.get_file_contents(pub)) ext_utils.change_owner(ssh_dir + "/authorized_keys", user) logger.log("Created user account: " + user) return None
def state_machine(self, tag_type, tag, attrs): # Tag of the form </$tag> if tag_type is END: if tag == self.state: # if it's ending the state the parser is currently in if self.state is NO_STATE: self.state = OUTSIDE elif self.state is BODY or self.state is HEAD: self.state = NO_STATE elif self.state is TITLE: self.state = HEAD else: self.state = BODY return # Parser is outside of any tags (not yet reached <aml>) if self.state is OUTSIDE: if tag_type is START: if tag == NO_STATE: self.state = NO_STATE return # Inside of <aml> but not in any specific tag if self.state is NO_STATE: if tag_type is START: if tag == BODY: # Start of main body self.state = BODY return if tag == HEAD: # Controls the text displayed on the title self.state = HEAD return # Currently just used to wrap the title if self.state is HEAD: if tag_type is START: if tag == TITLE: self.state = TITLE return # Inside the main body of the page if self.state is BODY: if tag_type is START: if tag == HEADING1: self.state = HEADING1 return if tag == PARAGRAPH: self.create_paragraph() self.state = PARAGRAPH return # Actual content being passed if tag_type is DATA: if self.state is HEADING1: self.feed_heading1(tag) return if self.state is TITLE: self.create_title(tag) return if self.state is PARAGRAPH: self.feed_text(tag) return # Images can only be created inside of paragraphs if self.state is PARAGRAPH: if tag_type is START: if tag == IMAGE: self.feed_image(attrs) return # In case something wasn't handled by parser, usually indicates malformed AML log('Unhandled ' + tag_type + ' "' + tag + '" in state ' + self.state, 1)
def initialize(): if config.use_tracker: quick_link.initialize() update_thread.start() log("Update thread started", 2)
def apply(self): quick_link.calibration_finalize(self.calibration) quick_link.apply_calibration(self.calibration) log("Calibration complete", 2) self.parent.close() map.run(self.parent.parent)