Best Python code snippet using Airtest
installer.py
Source:installer.py
...35 print(BOLD + HEADER + "--- " + title + " ---" + ENDC)36 def _display_warning(self, content):37 """ Displays a warning in the console """38 print(WARNING + "(WARN) " + content + ENDC)39 def _display_info(self, content):40 """ Displays an info message in the console """41 print(INFO + "(INFO) " + content + ENDC)42 def _display_question(self, content):43 """ Displays a preamble to a question """44 print(DOC + content + ENDC)45 def _display_error(self, content):46 """ Displays an error """47 print(WHITE + BACKGROUND_RED + "(ERROR) " + content + ENDC)48 def _display_big_warning(self, content):49 """ Displays a BIG warning """50 print("")51 print(BOLD + WARNING + "--- WARNING ---" + ENDC)52 print(WARNING + content + ENDC)53 print("")54 def _ask_with_default(self, question, default):55 default = str(default)56 answer = input(DOC + UNDERLINE + question + " [" + default + "]:" + ENDC + " ")57 if answer == "":58 answer = default59 return answer60 def _ask_boolean(self, question, default):61 while True:62 val = self._ask_with_default(question, ("yes" if default else "no")).lower()63 if val in ["yes", "y", "1", "true", "t"]:64 return True65 elif val in ["no", "n", "0", "false", "f"]:66 return False67 self._display_question("Please answer 'yes' or 'no'.")68 #######################################69 # Main function #70 #######################################71 def run(self):72 """ Run the installator """73 self._display_header("BACKEND CONFIGURATION")74 options = {}75 while True:76 options = {}77 backend = self.ask_backend()78 if backend == "local":79 self._display_info("Backend chosen: local. Testing the configuration.")80 options = self._ask_local_config()81 if not self.test_local_docker_conf():82 self._display_error(83 "An error occurred while testing the configuration. Please make sure you are able do run `docker info` in "84 "your command line, and environment parameters like DOCKER_HOST are correctly set.")85 if self._ask_boolean("Would you like to continue anyway?", False):86 break87 else:88 break89 else:90 self._display_warning(91 "Backend chosen: manual. As it is a really advanced feature, you will have to configure it yourself in "92 "the configuration file, at the end of the setup process.")93 options = {"backend": backend}94 break95 self._display_header("MONGODB CONFIGURATION")96 mongo_opt = self.configure_mongodb()97 options.update(mongo_opt)98 self._display_header("TASK DIRECTORY")99 task_directory_opt = self.configure_task_directory()100 options.update(task_directory_opt)101 self._display_header("CONTAINERS")102 self.configure_containers(options)103 self._display_header("MISC")104 misc_opt = self.configure_misc()105 options.update(misc_opt)106 database = self.try_mongodb_opts(options["mongo_opt"]["host"], options["mongo_opt"]["database"])107 self._display_header("BACKUP DIRECTORY")108 backup_directory_opt = self.configure_backup_directory()109 options.update(backup_directory_opt)110 self._display_header("AUTHENTIFICATION")111 auth_opts = self.configure_authentication(database)112 options.update(auth_opts)113 self._display_info("You may want to add additional plugins to the configuration file.")114 self._display_header("REMOTE DEBUGGING - IN BROWSER")115 self._display_info(116 "If you want to activate the remote debugging of task in the users' browser, you have to install separately "117 "INGInious-xterm, which is available on Github, according to the parameters you have given for the hostname and the "118 "port range given in the configuration of the remote debugging.")119 self._display_info(120 "You can leave the following question empty to disable this feature; remote debugging will still be available, "121 "but not in the browser.")122 webterm = self._ask_with_default(123 "Please indicate the link to your installation of INGInious-xterm (for example: "124 "https://your-hostname.com:8080).", "")125 if webterm != "":126 options["webterm"] = webterm127 self._display_header("END")128 file_dir = self._config_path or os.path.join(os.getcwd(), self.configuration_filename())129 try:130 yaml.dump(options, open(file_dir, "w"))131 self._display_info("Successfully written the configuration file")132 except:133 self._display_error("Cannot write the configuration file on disk. Here is the content of the file")134 print(yaml.dump(options))135 #######################################136 # Docker configuration #137 #######################################138 def _ask_local_config(self):139 """ Ask some parameters about the local configuration """140 options = {"backend": "local", "local-config": {}}141 # Concurrency142 while True:143 concurrency = self._ask_with_default(144 "Maximum concurrency (number of tasks running simultaneously). Leave it empty to use the number of "145 "CPU of your host.", "")146 if concurrency == "":147 break148 try:149 concurrency = int(concurrency)150 except:151 self._display_error("Invalid number")152 continue153 if concurrency <= 0:154 self._display_error("Invalid number")155 continue156 options["local-config"]["concurrency"] = concurrency157 break158 # Debug hostname159 hostname = self._ask_with_default(160 "What is the external hostname/address of your machine? You can leave this empty and let INGInious "161 "autodetect it.", "")162 if hostname != "":163 options["local-config"]["debug_host"] = hostname164 self._display_info(165 "You can now enter the port range for the remote debugging feature of INGInious. Please verify that these "166 "ports are open in your firewall. You can leave this parameters empty, the default is 64100-64200")167 # Debug port range168 port_range = None169 while True:170 start_port = self._ask_with_default("Beginning of the range", "")171 if start_port != "":172 try:173 start_port = int(start_port)174 except:175 self._display_error("Invalid number")176 continue177 end_port = self._ask_with_default("End of the range", str(start_port + 100))178 try:179 end_port = int(end_port)180 except:181 self._display_error("Invalid number")182 continue183 if start_port > end_port:184 self._display_error("Invalid range")185 continue186 port_range = str(start_port) + "-" + str(end_port)187 else:188 break189 if port_range != None:190 options["local-config"]["debug_ports"] = port_range191 return options192 def test_local_docker_conf(self):193 """ Test to connect to a local Docker daemon """194 try:195 docker_connection = docker.from_env()196 except Exception as e:197 self._display_error("- Unable to connect to Docker. Error was %s" % str(e))198 return False199 try:200 self._display_info("- Asking Docker some info")201 if docker.utils.compare_version('1.24', docker_connection.version()['ApiVersion']) < 0:202 self._display_error("- Docker version >= 1.12.0 is required.")203 return False204 except Exception as e:205 self._display_error("- Unable to contact Docker. Error was %s" % str(e))206 return False207 self._display_info("- Successfully got info from Docker. Docker connection works.")208 return True209 def ask_backend(self):210 """ Ask the user to choose the backend """211 response = self._ask_boolean(212 "Do you have a local docker daemon (on Linux), do you use docker-machine via a local machine, or do you use "213 "Docker for macOS?", True)214 if (response):215 self._display_info("If you use docker-machine on macOS, please see "216 "http://inginious.readthedocs.io/en/latest/install_doc/troubleshooting.html")217 return "local"218 else:219 self._display_info(220 "You will have to run inginious-backend and inginious-agent yourself. Please run the commands without argument "221 "and/or read the documentation for more info")222 return self._display_question("Please enter the address of your backend")223 #######################################224 # MONGODB CONFIGURATION #225 #######################################226 def try_mongodb_opts(self, host="localhost", database_name='INGInious'):227 """ Try MongoDB configuration """228 try:229 mongo_client = MongoClient(host=host)230 except Exception as e:231 self._display_warning("Cannot connect to MongoDB on host %s: %s" % (host, str(e)))232 return None233 try:234 database = mongo_client[database_name]235 except Exception as e:236 self._display_warning("Cannot access database %s: %s" % (database_name, str(e)))237 return None238 try:239 GridFS(database)240 except Exception as e:241 self._display_warning("Cannot access gridfs %s: %s" % (database_name, str(e)))242 return None243 return database244 def configure_mongodb(self):245 """ Configure MongoDB """246 self._display_info("Trying default configuration")247 host = "localhost"248 database_name = "INGInious"249 should_ask = True250 if self.try_mongodb_opts(host, database_name):251 should_ask = self._ask_boolean(252 "Successfully connected to MongoDB. Do you want to edit the configuration anyway?", False)253 else:254 self._display_info("Cannot guess configuration for MongoDB.")255 while should_ask:256 self._display_question(257 "Please enter the MongoDB host. If you need to enter a password, here is the syntax:")258 self._display_question("mongodb://USERNAME:PASSWORD@HOST:PORT/AUTHENTIFICATION_DATABASE")259 host = self._ask_with_default("MongoDB host", host)260 database_name = self._ask_with_default("Database name", database_name)261 if not self.try_mongodb_opts(host, database_name):262 if self._ask_boolean("Cannot connect to MongoDB. Would you like to continue anyway?", False):263 break264 else:265 self._display_info("Successfully connected to MongoDB")266 break267 return {"mongo_opt": {"host": host, "database": database_name}}268 #######################################269 # TASK DIRECTORY #270 #######################################271 def configure_task_directory(self):272 """ Configure task directory """273 self._display_question(274 "Please choose a directory in which to store the course/task files. By default, the tool will put them in the current "275 "directory")276 task_directory = None277 while task_directory is None:278 task_directory = self._ask_with_default("Task directory", ".")279 if not os.path.exists(task_directory):280 self._display_error("Path does not exists")281 if self._ask_boolean("Would you like to retry?", True):282 task_directory = None283 if os.path.exists(task_directory):284 self._display_question("Demonstration tasks can be downloaded to let you discover INGInious.")285 if self._ask_boolean("Would you like to download them ?", True):286 try:287 filename, _ = urllib.request.urlretrieve(288 "https://api.github.com/repos/UCL-INGI/INGInious-demo-tasks/tarball")289 with tarfile.open(filename, mode="r:gz") as thetarfile:290 members = thetarfile.getmembers()291 commonpath = os.path.commonpath([tarinfo.name for tarinfo in members])292 for member in members:293 member.name = member.name[len(commonpath) + 1:]294 if member.name:295 thetarfile.extract(member, task_directory)296 self._display_info("Successfully downloaded and copied demonstration tasks.")297 except Exception as e:298 self._display_error("An error occurred while copying the directory: %s" % str(e))299 else:300 self._display_warning("Skipping copying the 'test' course because the task dir does not exists")301 return {"tasks_directory": task_directory}302 #######################################303 # CONTAINERS #304 #######################################305 def download_containers(self, to_download, current_options):306 """ Download the chosen containers on all the agents """307 if current_options["backend"] == "local":308 self._display_info("Connecting to the local Docker daemon...")309 try:310 docker_connection = docker.from_env()311 except:312 self._display_error("Cannot connect to local Docker daemon. Skipping download.")313 return314 for image in to_download:315 try:316 self._display_info("Downloading image %s. This can take some time." % image)317 docker_connection.images.pull(image + ":latest")318 except Exception as e:319 self._display_error("An error occurred while pulling the image: %s." % str(e))320 else:321 self._display_warning(322 "This installation tool does not support the backend configuration directly, if it's not local. You will have to "323 "pull the images by yourself. Here is the list: %s" % str(to_download))324 def configure_containers(self, current_options):325 """ Configures the container dict """326 containers = [327 ("default", "Default container. For Bash and Python 2 tasks"),328 ("cpp", "Contains gcc and g++ for compiling C++"),329 ("java7", "Contains Java 7"),330 ("java8scala", "Contains Java 8 and Scala"),331 ("mono", "Contains Mono, which allows to run C#, F# and many other languages"),332 ("oz", "Contains Mozart 2, an implementation of the Oz multi-paradigm language, made for education"),333 ("php", "Contains PHP 5"),334 ("pythia0compat", "Compatibility container for Pythia 0"),335 ("pythia1compat", "Compatibility container for Pythia 1"),336 ("r", "Can run R scripts"),337 ("sekexe", "Can run an user-mode-linux for advanced tasks")338 ]339 default_download = ["default"]340 self._display_question(341 "The tool will now propose to download some base container image for multiple languages.")342 self._display_question(343 "Please note that the download of these images can take a lot of time, so choose only the images you need")344 to_download = []345 for container_name, description in containers:346 if self._ask_boolean("Download %s (%s) ?" % (container_name, description),347 container_name in default_download):348 to_download.append("ingi/inginious-c-%s" % container_name)349 self.download_containers(to_download, current_options)350 wants = self._ask_boolean("Do you want to manually add some images?", False)351 while wants:352 image = self._ask_with_default("Container image name (leave this field empty to skip)", "")353 if image == "":354 break355 self._display_info("Configuration of the containers done.")356 #######################################357 # MISC #358 #######################################359 def configure_misc(self):360 """ Configure various things """361 options = {}362 options["use_minified_js"] = self._ask_boolean(363 "Use minified javascript? (Useful in production, but should be disabled in dev environment)",364 True)365 return options366 def configure_backup_directory(self):367 """ Configure backup directory """368 self._display_question("Please choose a directory in which to store the backup files. By default, the tool will them in the current "369 "directory")370 backup_directory = None371 while backup_directory is None:372 backup_directory = self._ask_with_default("Backup directory", ".")373 if not os.path.exists(backup_directory):374 self._display_error("Path does not exists")375 if self._ask_boolean("Would you like to retry?", True):376 backup_directory = None377 return {"backup_directory": backup_directory}378 def ldap_plugin(self):379 """ Configures the LDAP plugin """380 name = self._ask_with_default("Authentication method name (will be displayed on the login page)", "LDAP")381 prefix = self._ask_with_default("Prefix to append to the username before db storage. Usefull when you have more than one auth method with "382 "common usernames.", "")383 ldap_host = self._ask_with_default("LDAP Host", "ldap.your.domain.com")384 encryption = 'none'385 while True:386 encryption = self._ask_with_default("Encryption (either 'ssl', 'tls', or 'none')", 'none')387 if encryption not in ['none', 'ssl', 'tls']:388 self._display_error("Invalid value")389 else:390 break391 base_dn = self._ask_with_default("Base DN", "ou=people,c=com")392 request = self._ask_with_default("Request to find a user. '{}' will be replaced by the username", "uid={}")393 require_cert = self._ask_boolean("Require certificate validation?", encryption is not None)394 return {395 "plugin_module": "inginious.frontend.plugins.auth.ldap_auth",396 "host": ldap_host,397 "encryption": encryption,398 "base_dn": base_dn,399 "request": request,400 "prefix": prefix,401 "name": name,402 "require_cert": require_cert403 }404 def configure_authentication(self, database):405 """ Configure the authentication """406 options = {"plugins": [], "superadmins": []}407 self._display_info("We will now create the first user.")408 username = self._ask_with_default("Enter the login of the superadmin", "superadmin")409 realname = self._ask_with_default("Enter the name of the superadmin", "INGInious SuperAdmin")410 email = self._ask_with_default("Enter the email address of the superadmin", "superadmin@inginious.org")411 password = self._ask_with_default("Enter the password of the superadmin", "superadmin")412 database.users.insert({"username": username,413 "realname": realname,414 "email": email,415 "password": hashlib.sha512(password.encode("utf-8")).hexdigest(),416 "bindings": {},417 "language": "en"})418 options["superadmins"].append(username)419 while True:420 if not self._ask_boolean("Would you like to add another auth method?", False):421 break422 self._display_info("You can choose an authentication plugin between:")423 self._display_info("- 1. LDAP auth plugin. This plugin allows to connect to a distant LDAP host.")424 plugin = self._ask_with_default("Enter the corresponding number to your choice", '1')425 if plugin not in ['1']:426 continue427 elif plugin == '1':428 options["plugins"].append(self.ldap_plugin())429 return options430 def configuration_filename(self):431 """ Returns the name of the configuration file """432 return "configuration.yaml"433 def support_remote_debugging(self):434 """ Returns True if the frontend supports remote debugging, False else"""...
converter_gui.py
Source:converter_gui.py
...19 self.converter = None20 self.stack_steps.setCurrentIndex(0)21 self.first_page_msg = ('<b>This is a tool to convert Opus project XML files from version 4.x to 4.3</b><br/>'22 'Please select the project file that you wish to upgrade.')23 self._display_info(self.first_page_msg, icon = 'info')24 self.resize(self.width(), 0) # compress the dialogs height25 self._enable_save()26 self.le_filename.setFocus()27 self.raise_()28 def _get_filename(self):29 if self.stack_steps.currentIndex() == 0:30 filename = QFileDialog.getOpenFileName()31 widget = self.le_filename32 else:33 filename = QFileDialog.getSaveFileName()34 widget = self.le_filename_out35 if not filename:36 return37 widget.setText(filename)38 widget.setToolTip(filename)39 widget.setCursorPosition(len(filename))40 def _enable_save(self, state = True):41 self.pb_save.setEnabled(state)42 self.pb_save.setText('Save' if state else 'Saved')43 self.le_filename_out.setEnabled(state)44 self.pb_get_filename_out.setEnabled(state)45 def _display_info(self, first_msg, secondary_msg = None, icon = 'info', show_message_button = False):46 # show information in the information box for the current stack index47 # icon can be 'info' (default), 'warning' or 'ok'48 # if show_message_button is True, the show message button is shown (only on page 1)49 icon_widgets = (self.p0_info_icon, self.p0_warning_icon, self.p1_info_icon,50 self.p1_ok_icon, self.p1_warning_icon)51 for widget in icon_widgets:52 widget.setVisible(False)53 # select widgets based on current page54 if self.stack_steps.currentIndex() == 0:55 icon_widgets = {'info': self.p0_info_icon,56 'warning': self.p0_warning_icon,57 'ok': self.p0_info_icon}58 text_widget = self.p0_text59 else:60 icon_widgets = {'info': self.p1_info_icon,61 'warning': self.p1_warning_icon,62 'ok': self.p1_ok_icon}63 text_widget = self.p1_text64 self.pb_show_warnings.setVisible(show_message_button)65 icon_widgets[icon].setVisible(True)66 if secondary_msg:67 msg = '<qt>%s<br/>%s</qt>' %(first_msg, secondary_msg)68 else:69 msg = '<qt>%s</qt>' %first_msg70 text_widget.setText(msg)71 def on_pb_log_released(self):72 self.frame_log.setVisible(self.pb_log.isChecked())73 self.frame_page2.setVisible(not self.pb_log.isChecked())74 def on_pb_next_released(self):75 # Try to convert the given file. If it was (partly or completely) successful, proceed to the76 # next page. Otherwise stay on the first page to let the user investigate the error.77 self.setCursor(Qt.WaitCursor)78 try:79 self.converter = Converter()80 self.converter.quiet = True81 filename = str(self.le_filename.text())82 self.converter.complete_check(filename)83 self.converter.execute()84 self.txt_log.document().setPlainText('\n'.join(self.converter.successfuls))85 self.pb_save.setEnabled(True)86 self._enable_save()87 self.stack_steps.setCurrentIndex(1)88 # put together an appropriate information message89 total_changes = len(self.converter.successfuls) + len(self.converter.warnings)90 num_warnings = len(self.converter.warnings)91 if self.converter.warnings:92 info = ('<b>Found a total of %d changes, but %d was not completed because of errors.'93 % (total_changes, num_warnings))94 sec_info = ('You can still save the changes that was successful by selecting a '95 'filename and clicking %s' % self.pb_save.text())96 self._display_info(info, sec_info, icon = 'warning', show_message_button = True)97 self.pb_show_warnings.setFocus()98 else:99 info = '<b>Found a total of %d changes, all completed OK.</b>' % total_changes100 sec_info = ('To save the changes, select a filename and click <i>%s</i>.'101 % self.pb_save.text())102 self._display_info(info)103 self.pb_save.setFocus()104 # suggest a converted filename105 path, name_of_file = os.path.split(filename)106 base_name, ext = os.path.splitext(name_of_file)107 suggested_savename = os.path.join(path, base_name + '_opus_43' + ext)108 suggested_savename = os.path.normpath(suggested_savename)109 self.le_filename_out.setText(suggested_savename)110 except SyntaxError, ex:111 self.le_filename.setFocus()112 self.le_filename.selectAll()113 self._display_info('<b>This XML file seems to have an invalid syntax.</b>', ex,114 icon = 'warning')115 except IOError, ex:116 self.le_filename.setFocus()117 self.le_filename.selectAll()118 self._display_info('<b>An read error occurred while trying to load the file.</b>',119 ex, icon = 'warning')120 except Exception, ex:121 self.le_filename.setFocus()122 self.le_filename.selectAll()123 print repr(ex)124 self._display_info('<b>An error occurred while parsing the file.</b>', ex,125 icon = 'warning')126 finally:127 self.setCursor(Qt.ArrowCursor)128 def on_pb_back_released(self):129 # re-select a filename130 self._display_info(self.first_page_msg)131 self.stack_steps.setCurrentIndex(0)132 def on_pb_show_warnings_released(self):133 # show a dialog box with only the warnings from the conversion134 win = QDialog(self)135 win.resize(self.size() * 0.85)136 layout = QVBoxLayout()137 txt = QTextEdit(win)138 txt.setLineWrapMode(txt.NoWrap)139 txt.document().setPlainText('\n'.join(self.converter.warnings))140 pb = QPushButton('Close')141 self.connect(pb, SIGNAL('released()'), win.accept)142 layout.addWidget(txt)143 layout.addWidget(pb)144 win.setLayout(layout)145 win.exec_()146 def on_pb_save_released(self):147 try:148 filename = str(self.le_filename_out.text())149 dummy, just_filename = os.path.split(filename)150 f = open(filename, 'w')151 f.write(etree.tostring(self.converter.root))152 info = ('<b>Successfully wrote converted XML to file %s</b>' % just_filename)153 sec_info = 'If you you have more files to convert, you can go back and select another file'154 self._display_info(info, sec_info, icon = 'ok')155 self._enable_save(False)156 except IOError, ex:157 self._display_info('<b>A file error occurred while trying to save the converted XML.</b>', ex)158 except Exception, ex:159 self._display_info('<b>An error occurred while trying to save the converted XML.</b>', ex)160 finally:161 f.close()162if __name__ == '__main__':163 app = QApplication([], True)164 d = ConverterGui()165 app.connect(app, SIGNAL("lastWindowClosed()"), app, SLOT("quit()"))166 d.show()167 d.raise_()168 d.activateWindow()...
display.py
Source:display.py
1from pepper.framework import AbstractComponent2from pepper.framework.component import FaceRecognitionComponent, ObjectDetectionComponent3from .server import DisplayServer4from threading import Thread, Lock5from PIL import Image6from io import BytesIO7import base648import json9class DisplayComponent(AbstractComponent):10 def __init__(self, backend):11 super(DisplayComponent, self).__init__(backend)12 server = DisplayServer()13 server_thread = Thread(target=server.start)14 server_thread.daemon = True15 server_thread.start()16 lock = Lock()17 self._display_info = {}18 def encode_image(image):19 """20 Parameters21 ----------22 image: Image.Image23 Returns24 -------25 base64: str26 Base64 encoded PNG string27 """28 with BytesIO() as png:29 image.save(png, 'png')30 png.seek(0)31 return base64.b64encode(png.read())32 def on_image(image, orientation):33 with lock:34 if self._display_info:35 server.update(json.dumps(self._display_info))36 self._display_info = {37 "hash": hash(str(image)),38 "img": encode_image(Image.fromarray(image)),39 "items": []40 }41 def add_items(items):42 if self._display_info:43 with lock:44 self._display_info["items"] += [45 {"name": item.name,46 "confidence": item.confidence,47 "bounds": item.bounds.to_list()48 } for item in items]49 face_recognition = self.require(DisplayComponent, FaceRecognitionComponent) # type: FaceRecognitionComponent50 object_recognition = self.require(DisplayComponent, ObjectDetectionComponent) # type: ObjectDetectionComponent51 self.backend.camera.callbacks += [on_image]52 face_recognition.on_face_known_callbacks += [lambda faces: add_items(faces)]...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!