Instruction:
Can you tell what is the following Python 3 function doing
def get_rendered_page_source(self, dom_idle_requirement_secs=3, max_wait_timeout=30):
		'''
		Get the HTML markup for the current page.

		This is done by looking up the root DOM node, and then requesting the outer HTML
		for that node ID.

		This calls return will reflect any modifications made by javascript to the
		page. For unmodified content, use `blocking_navigate_and_get_source()`

		dom_idle_requirement_secs specifies the period of time for which there must have been no
		DOM modifications before treating the rendered output as "final". This call will therefore block for
		at least dom_idle_requirement_secs seconds.
		'''

		# There are a bunch of events which generally indicate a page is still doing *things*.
		# I have some concern about how this will handle things like advertisements, which
		# basically load crap forever. That's why we have the max_wait_timeout.
		target_events = [
			"Page.frameResized",
			"Page.frameStartedLoading",
			"Page.frameNavigated",
			"Page.frameAttached",
			"Page.frameStoppedLoading",
			"Page.frameScheduledNavigation",
			"Page.domContentEventFired",
			"Page.frameClearedScheduledNavigation",
			"Page.loadEventFired",
			"DOM.documentUpdated",
			"DOM.childNodeInserted",
			"DOM.childNodeRemoved",
			"DOM.childNodeCountUpdated",
		]

		start_time = time.time()
		try:
			while 1:
				if time.time() - start_time > max_wait_timeout:
					self.log.debug("Page was not idle after waiting %s seconds. Giving up and extracting content now.", max_wait_timeout)
				self.transport.recv_filtered(filter_funcs.wait_for_methods(target_events),
					tab_key=self.tab_id, timeout=dom_idle_requirement_secs)

		except ChromeResponseNotReceived:
			# We timed out, the DOM is probably idle.
			pass

		# We have to find the DOM root node ID
		dom_attr = self.DOM_getDocument(depth=-1, pierce=False)
		assert 'result' in dom_attr
		assert 'root' in dom_attr['result']
		assert 'nodeId' in dom_attr['result']['root']

		# Now, we have the root node ID.
		root_node_id = dom_attr['result']['root']['nodeId']

		# Use that to get the HTML for the specified node
		response = self.DOM_getOuterHTML(nodeId=root_node_id)

		assert 'result' in response
		assert 'outerHTML' in response['result']
		return response['result']['outerHTML']

Response: Get the rendered HTML markup for the current page.


Instruction:
Given the following Python 3 function, write the documentation
def take_screeshot(self):
		'''
		Take a screenshot of the virtual viewport content.

		Return value is a png image as a bytestring.
		'''
		resp = self.Page_captureScreenshot()
		assert 'result' in resp
		assert 'data' in resp['result']
		imgdat = base64.b64decode(resp['result']['data'])
		return imgdat

Response: Take a screenshot of the virtual viewport content.


Instruction:
Here you have a function in Python 3, explain what it does
def blocking_navigate(self, url, timeout=DEFAULT_TIMEOUT_SECS):
		'''
		Do a blocking navigate to url `url`.

		This function triggers a navigation, and then waits for the browser
		to claim the page has finished loading.

		Roughly, this corresponds to the javascript `DOMContentLoaded` event,
		meaning the dom for the page is ready.

		Internals:

		A navigation command results in a sequence of events:

		 - Page.frameStartedLoading" (with frameid)
		 - Page.frameStoppedLoading" (with frameid)
		 - Page.loadEventFired" (not attached to an ID)

		Therefore, this call triggers a navigation option,
		and then waits for the expected set of response event messages.

		'''

		self.transport.flush(tab_key=self.tab_id)

		ret = self.Page_navigate(url = url)

		assert("result"   in ret),           "Missing return content"
		assert("frameId"  in ret['result']), "Missing 'frameId' in return content"
		assert("loaderId" in ret['result']), "Missing 'loaderId' in return content"

		expected_id = ret['result']['frameId']
		loader_id   = ret['result']['loaderId']

		try:
			self.log.debug("Waiting for frame navigated command response.")
			self.transport.recv_filtered(filter_funcs.check_frame_navigated_command(expected_id), tab_key=self.tab_id, timeout=timeout)
			self.log.debug("Waiting for frameStartedLoading response.")
			self.transport.recv_filtered(filter_funcs.check_frame_load_command("Page.frameStartedLoading"), tab_key=self.tab_id, timeout=timeout)
			self.log.debug("Waiting for frameStoppedLoading response.")
			self.transport.recv_filtered(filter_funcs.check_frame_load_command("Page.frameStoppedLoading"), tab_key=self.tab_id, timeout=timeout)
			# self.transport.recv_filtered(check_load_event_fired, tab_key=self.tab_id, timeout=timeout)

			self.log.debug("Waiting for responseReceived response.")
			resp = self.transport.recv_filtered(filter_funcs.network_response_recieved_for_url(url=None, expected_id=expected_id), tab_key=self.tab_id, timeout=timeout)

			if resp is None:
				raise ChromeNavigateTimedOut("Blocking navigate timed out!")

			return resp['params']
		# The `Page.frameNavigated ` event does not get fired for non-markup responses.
		# Therefore, if we timeout on waiting for that, check to see if we received a binary response.
		except ChromeResponseNotReceived:
			# So this is basically broken, fix is https://bugs.chromium.org/p/chromium/issues/detail?id=831887
			# but that bug report isn't fixed yet.
			# Siiiigh.
			self.log.warning("Failed to receive expected response to navigate command. Checking if response is a binary object.")
			resp = self.transport.recv_filtered(
				keycheck = filter_funcs.check_frame_loader_command(
						method_name = "Network.responseReceived",
						loader_id   = loader_id
					),
				tab_key  = self.tab_id,
				timeout  = timeout)

			return resp['params']

Response: This method is used to send a blocking navigate command to url.


Instruction:
Here you have a function in Python 3, explain what it does
def tab(self, netloc=None, url=None, extra_id=None, use_tid=False):
		'''
		Get a chromium tab from the pool, optionally one that has an association with a specific netloc/URL.

		If no url or netloc is specified, the per-thread identifier will be used.
		If `extra_id` is specified, it's stringified value will be mixed into the pool key
		If `use_tid` is true, the per-thread identifier will be mixed into the pool key.

		In all cases, the tab pool is a least-recently-used cache, so the tab that has been accessed the
		least recently will be automatically closed if a new tab is requested, and there are already
		`tab_pool_max_size` tabs created.

		'''
		assert self.alive, "Chrome has been shut down! Cannot continue!"
		if not netloc and url:
			netloc = urllib.parse.urlparse(url).netloc
			self.log.debug("Getting tab for netloc: %s (url: %s)", netloc, url)
		# Coerce to string type so even if it's none, it doesn't hurt anything.
		key = str(netloc)
		if extra_id:
			key += " " + str(extra_id)
		if use_tid or not key:
			key += " " + str(threading.get_ident())

		if self.__started_pid != os.getpid():
			self.log.error("TabPooledChromium instances are not safe to share across multiple processes.")
			self.log.error("Please create a new in each separate multiprocesssing process.")
			raise RuntimeError("TabPooledChromium instances are not safe to share across multiple processes.")

		with self.__counter_lock:
			self.__active_tabs.setdefault(key, 0)
			self.__active_tabs[key] += 1
			if self.__active_tabs[key] > 1:
				self.log.warning("Tab with key %s checked out more then once simultaneously")

		try:
			lock, tab = self.__tab_cache[key]
			with lock:
				yield tab
		finally:

			with self.__counter_lock:
				self.__active_tabs[key] -= 1
				if self.__active_tabs[key] == 0:
					self.__active_tabs.pop(key)

Response: Get a chromium tab from the pool optionally one that has an association with a specific netloc and URL.


Instruction:
How would you code a function in Python 3 to
return a function to be run when the parent process dies

Response:
def on_parent_exit(signame):
    """
    Return a function to be run in a child process which will trigger SIGNAME
    to be sent when the parent process dies
    """
    signum = getattr(signal, signame)
    def set_parent_exit_signal():
        # http://linux.die.net/man/2/prctl
        result = cdll['libc.so.6'].prctl(PR_SET_PDEATHSIG, signum)
        if result != 0:
            raise PrCtlError('prctl failed with error code %s' % result)
    return set_parent_exit_signal


Instruction:
How would you explain what the following Python 3 function does
def ChromeContext(*args, **kwargs):
	'''
	Context manager for conveniently handling the lifetime of the underlying chromium instance.

	In general, this should be the preferred way to use an instance of `ChromeRemoteDebugInterface`.

	All parameters are forwarded through to the underlying ChromeRemoteDebugInterface() constructor.
	'''
	log = logging.getLogger("Main.ChromeController.ChromeContext")
	chrome_created = False
	try:
		chrome_instance = ChromeRemoteDebugInterface(*args, **kwargs)
		chrome_created = True
		log.info("Entering chrome context")
		yield chrome_instance
	except Exception as e:

		log.error("Exception in chrome context!")
		for line in traceback.format_exc().split("\n"):
			log.error(line)
		raise e

	finally:
		log.info("Exiting chrome context")
		if chrome_created:
			chrome_instance.close()

Response: A context manager for conveniently handling the lifetime of a chrome instance.


Instruction:
Write a Python 3 function for
forwarding a command to the remote chrome instance via the transport connection, and check the return for an error. If the command resulted in an error, a `ChromeController.ChromeError` is raised, with the error string containing the response from the remote chrome instance describing the problem and it's cause. Otherwise, the decoded json data-structure returned from the remote instance is returned.

Response:
def synchronous_command(self, *args, **kwargs):
		'''
		Forward a command to the remote chrome instance via the transport
		connection, and check the return for an error.

		If the command resulted in an error, a `ChromeController.ChromeError` is raised,
		with the error string containing the response from the remote
		chrome instance describing the problem and it's cause.

		Otherwise, the decoded json data-structure returned from the remote instance is
		returned.

		'''

		self.transport.check_process_ded()
		ret = self.transport.synchronous_command(tab_key=self.tab_id, *args, **kwargs)
		self.transport.check_process_ded()
		self.__check_ret(ret)
		self.transport.check_process_ded()
		return ret


Instruction:
Here you have a function in Python 3, explain what it does
def drain_transport(self):
		'''
		"Drain" the transport connection.

		This command simply returns all waiting messages sent from the remote chrome
		instance. This can be useful when waiting for a specific asynchronous message
		from chrome, but higher level calls are better suited for managing wait-for-message
		type needs.

		'''
		self.transport.check_process_ded()
		ret = self.transport.drain(tab_key=self.tab_id)
		self.transport.check_process_ded()
		return ret

Response: Drain the transport connection.


Instruction:
How would you explain what the following Python 3 function does
def resetLoggingLocks():
	'''
	This function is a HACK!

	Basically, if we fork() while a logging lock is held, the lock
	is /copied/ while in the acquired state. However, since we've
	forked, the thread that acquired the lock no longer exists,
	so it can never unlock the lock, and we end up blocking
	forever.

	Therefore, we manually enter the logging module, and forcefully
	release all the locks it holds.

	THIS IS NOT SAFE (or thread-safe).
	Basically, it MUST be called right after a process
	starts, and no where else.
	'''
	try:
		logging._releaseLock()
	except RuntimeError:
		pass  # The lock is already released

	# Iterate over the root logger hierarchy, and
	# force-free all locks.
	# if logging.Logger.root
	for handler in logging.Logger.manager.loggerDict.values():
		if hasattr(handler, "lock") and handler.lock:
			try:
				handler.lock.release()
			except RuntimeError:
				pass

Response: This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK! This function is a HACK!


Instruction:
Can you write a function in Python 3 where it
emits a record to the output stream.

Response:
def stream_emit(self, record, source_name):
		"""
		Emit a record.

		If a formatter is specified, it is used to format the record.
		The record is then written to the stream with a trailing newline.  If
		exception information is present, it is formatted using
		traceback.print_exception and appended to the stream.  If the stream
		has an 'encoding' attribute, it is used to determine how to do the
		output to the stream.
		"""

		if not source_name in self.output_streams:
			out_path = os.path.abspath("./logs")
			logpath = ansi_escape.sub('', source_name.replace("/", ";").replace(":", ";").replace("?", "-"))
			filename = "log {path}.txt".format(path=logpath)
			print("Opening output log file for path: %s" % filename)
			self.output_streams[source_name] = open(os.path.join(out_path, filename), self.mode, encoding=self.encoding)

		stream = self.output_streams[source_name]
		try:
			msg = self.format(record)
			stream.write(msg)
			stream.write(self.terminator)
			stream.flush()
			self.flush()
		except Exception:
			self.handleError(record)


Instruction:
Create a Python 3 function to
emit a record. If the stream was not opened because 'delay' was specified in the constructor, open it before calling the superclass's emit.

Response:
def emit(self, record):
		"""
		Emit a record.

		If the stream was not opened because 'delay' was specified in the
		constructor, open it before calling the superclass's emit.
		"""
		failures = 0
		while failures < 3:
			try:
				self.stream_emit(record, record.name)
				break
			except:
				failures += 1
		else:
			traceback.print_stack()
			print("Error writing to file?")

		self.close()


Instruction:
Explain what the following Python 3 code does
def run_suite(self, suite, **kwargs):
        return self.test_runner(
            verbosity=self.verbosity,
            failfast=self.failfast,
            no_colour=self.no_colour,
        ).run(suite)

Response: This is the version from Django 1. 7.


Instruction:
How would you implement a function in Python 3 that
generates a private key of key_length bits and attaches it to the object as the private_key variable.

Response:
def generate_private_key(self):
        """
        Generates a private key of key_length bits and attaches it to the object as the __private_key variable.

        :return: void
        :rtype: void
        """
        key_length = self.key_length // 8 + 8
        key = 0

        try:
            key = int.from_bytes(rng(key_length), byteorder='big')
        except:
            key = int(hex(rng(key_length)), base=16)

        self.__private_key = key


Instruction:
Can you implement a function in Python 3 that
generates public key. :return: void :rtype: void

Response:
def generate_public_key(self):
        """
        Generates public key.

        :return: void
        :rtype: void
        """
        self.public_key = pow(self.generator,
                              self.__private_key,
                              self.prime)


Instruction:
Write a Python 3 script to
generate a shared secret from the other party s public key.

Response:
def generate_shared_secret(self, other_public_key, echo_return_key=False):
        """
        Generates shared secret from the other party's public key.

        :param other_public_key: Other party's public key
        :type other_public_key: int
        :param echo_return_key: Echo return shared key
        :type bool
        :return: void
        :rtype: void
        """
        if self.verify_public_key(other_public_key) is False:
            raise MalformedPublicKey

        self.shared_secret = pow(other_public_key,
                                 self.__private_key,
                                 self.prime)

        shared_secret_as_bytes = self.shared_secret.to_bytes(self.shared_secret.bit_length() // 8 + 1, byteorder='big')

        _h = sha256()
        _h.update(bytes(shared_secret_as_bytes))

        self.shared_key = _h.hexdigest()

        if echo_return_key is True:
            return self.shared_key


Instruction:
Make a summary of the following Python 3 code
def requires_public_key(func):

    def func_wrapper(self, *args, **kwargs):
        if hasattr(self, "public_key"):
            func(self, *args, **kwargs)
        else:
            self.generate_public_key()
            func(self, *args, **kwargs)

    return func_wrapper

Response: Decorator for functions that require a public key to be defined.


Instruction:
How would you code a function in Python 3 to
print the debug flag if set to True in the config. yaml file.

Response:
def print_debug(*args, **kwargs):
    """
    Print if and only if the debug flag is set true in the config.yaml file.

    Args:
        args : var args of print arguments.

    """
    if WTF_CONFIG_READER.get("debug", False) == True:
        print(*args, **kwargs)


Instruction:
Implement a Python 3 function for
printing the current elapsed time.

Response:
def print_time(self, message="Time is now: ", print_frame_info=True):
        """
        Print the current elapsed time.

        Kwargs:
            message (str) : Message to prefix the time stamp.
            print_frame_info (bool) : Add frame info to the print message.

        """
        if print_frame_info:
            frame_info = inspect.getouterframes(inspect.currentframe())[1]
            print(message, (datetime.now() - self.start_time), frame_info)
        else:
            print(message, (datetime.now() - self.start_time))


Instruction:
Can you create a Python 3 function that
checks if resource at URL is fetchable.

Response:
def check_url(url):
        '''
        Check if resource at URL is fetchable. (by trying to fetch it and checking for 200 status.

        Args:
            url (str): Url to check.

        Returns:
            Returns a tuple of {True/False, response code}

        '''
        request = urllib2.Request(url)
        try:
            response = urlopen(request)
            return True, response.code
        except urllib2.HTTPError as e:
            return False, e.code


Instruction:
Here you have a function in Python 3, explain what it does
def get_base_url(webdriver):
        current_url = webdriver.current_url
        try:
            return re.findall("^[^/]+//[^/$]+", current_url)[0]
        except:
            raise RuntimeError(
                u("Unable to process base url: {0}").format(current_url))

Response: Get the current base URL.


Instruction:
Here you have a function in Python 3, explain what it does
def get_browser_datetime(webdriver):
        js_stmt = """
            var wtf_get_date = new Date();
            return {'month':wtf_get_date.getMonth(),
                    'day':wtf_get_date.getDate(),
                    'year':wtf_get_date.getFullYear(),
                    'hours':wtf_get_date.getHours(),
                    'minutes':wtf_get_date.getMinutes(),
                    'seconds':wtf_get_date.getSeconds(),
                    'milliseconds':wtf_get_date.getMilliseconds()};
        """
        browser_date = webdriver.execute_script(js_stmt)
        return datetime(int(browser_date['year']),
                        int(browser_date['month']) + 1,  # javascript months start at 0
                        int(browser_date['day']),
                        int(browser_date['hours']),
                        int(browser_date['minutes']),
                        int(browser_date['seconds']),
                        int(browser_date['milliseconds']))

Response: Get the current date and time on the web browser as a Python datetime object.


Instruction:
Implement a function in Python 3 to
check if a web driver is mobile

Response:
def is_webdriver_mobile(webdriver):
        """
        Check if a web driver if mobile.

        Args:
            webdriver (WebDriver): Selenium webdriver.

        """
        browser = webdriver.capabilities['browserName']

        if (browser == u('iPhone') or
            browser == u('android')):
            return True
        else:
            return False


Instruction:
Here you have a function in Python 3, explain what it does
def is_webdriver_ios(webdriver):
        browser = webdriver.capabilities['browserName']

        if (browser == u('iPhone') or
            browser == u('iPad')):
            return True
        else:
            return False

Response: Check if a web driver is iOS


Instruction:
Can you write a function in Python 3 where it
converts a row into a dictionary of key - value pairs.

Response:
def row_to_dictionary(header_row_web_element, row_webelement):
        """
        Converts a row into a dictionary of key/values.
        (Note: assumes all rows/columns have uniform cells.  Does not
        account for any row or column spans)

        Args:
            header_row_web_element (WebElement): WebElement reference to the column headers.
            row_webelement (WebElement): WebElement reference to row.

        Returns:
            Returns a dictionary object containing keys consistenting of the column headers
            and values consisting of the row contents.

        Usage::

            self.webdriver.get("http://the-internet.herokuapp.com/tables")

            header = self.webdriver.find_element_by_css_selector("#table1 thead tr")
            target_row = self.webdriver.find_element_by_css_selector("#table1 tbody tr")

            row_values = WebUtils.row_to_dictionary(header, target_row)
            row_values ==    {'Last Name': 'Smith',
                              'Due': '$50.00',
                              'First Name': 'John',
                              'Web Site': 'http://www.jsmith.com',
                              'Action': 'edit delete',
                              'Email': 'jsmith@gmail.com'}

        """
        headers = header_row_web_element.find_elements_by_tag_name("th")
        data_cells = row_webelement.find_elements_by_tag_name("td")

        value_dictionary = {}
        for i in range(len(data_cells)):
            value_dictionary[ headers[i].text ] = data_cells[i].text

        return value_dictionary


Instruction:
Write a Python 3 script for
creating an instance of BrowserStandBy and immediately return a running instance.

Response:
def start_standby(cls, webdriver=None, max_time=WTF_TIMEOUT_MANAGER.EPIC, sleep=5):
        """
        Create an instance of BrowserStandBy() and immediately return a running instance.

        This is best used in a 'with' block.

        Example::

            with BrowserStandBy.start_standby():
                # Now browser is in standby, you can do a bunch of stuff with in this block.
                # ...

            # We are now outside the block, and the browser standby has ended.

        """
        return cls(webdriver=webdriver, max_time=max_time, sleep=sleep, _autostart=True)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def start(self):
        self._end_time = datetime.now() + timedelta(seconds=self._max_time)
        self._thread = Thread(target=lambda: self.__stand_by_loop())
        self._keep_running = True
        self._thread.start()
        return self

Response:
Start standing by.  A periodic command like 'current_url' will be sent to the
        webdriver instance to prevent it from timing out.


Instruction:
Write a Python 3 script to
get a temp path.

Response:
def temp_path(file_name=None):
    """
    Gets a temp path.

    Kwargs:
        file_name (str) : if file name is specified, it gets appended to the temp dir.

    Usage::

        temp_file_path = temp_path("myfile")
        copyfile("myfile", temp_file_path) # copies 'myfile' to '/tmp/myfile'

    """

    if file_name is None:
        file_name = generate_timestamped_string("wtf_temp_file")

    return os.path.join(tempfile.gettempdir(), file_name)


Instruction:
Can you create a Python 3 function that
creates a temporary file with the given name.

Response:
def create_temp_file(file_name=None, string_or_another_file=""):
    """
    Creates a temp file using a given name.  Temp files are placed in the Project/temp/
    directory.  Any temp files being created with an existing temp file, will be
    overridden.  This is useful for testing uploads, where you would want to create a
    temporary file with a desired name, upload it, then delete the file when you're
    done.

    Kwargs:
        file_name (str): Name of file
        string_or_another_file: Contents to set this file to. If this is set to a file,
                                it will copy that file.  If this is set to a string, then
                                it will write this string to the temp file.

    Return:
        str - Returns the file path to the generated temp file.

    Usage::

        temp_file_path = create_temp_file("mytestfile", "The nimble fox jumps over the lazy dog.")
        file_obj = open(temp_file_path)
        os.remove(temp_file_path)

    """
    temp_file_path = temp_path(file_name)
    if isinstance(string_or_another_file, file):
        # attempt to read it as a file.
        temp_file = open(temp_file_path, "wb")
        temp_file.write(string_or_another_file.read())
    else:
        # handle as a string type if we can't handle as a file.
        temp_file = codecs.open(temp_file_path, "w+", "utf-8")
        temp_file.write(string_or_another_file)

    temp_file.close()
    return temp_file_path


Instruction:
Implement a Python 3 function for
downloading a URL contents to a tempfile.

Response:
def download_to_tempfile(url, file_name=None, extension=None):
    """
    Downloads a URL contents to a tempfile.  This is useful for testing downloads.
    It will download the contents of a URL to a tempfile, which you then can
    open and use to validate the downloaded contents.

    Args:
        url (str) : URL of the contents to download.

    Kwargs:
        file_name (str): Name of file.
        extension (str): Extension to use.

    Return:
        str - Returns path to the temp file.

    """

    if not file_name:
        file_name = generate_timestamped_string("wtf_temp_file")

    if extension:
        file_path = temp_path(file_name + extension)
    else:
        ext = ""
        try:
            ext = re.search(u"\\.\\w+$", file_name).group(0)
        except:
            pass
        file_path = temp_path(file_name + ext)

    webFile = urllib.urlopen(url)
    localFile = open(file_path, 'w')
    localFile.write(webFile.read())
    webFile.close()
    localFile.close()

    return file_path


Instruction:
Here you have a function in Python 3, explain what it does
def create_page(cls, webdriver=None, **kwargs):
        if not webdriver:
            webdriver = WTF_WEBDRIVER_MANAGER.get_driver()
        return PageFactory.create_page(cls, webdriver=webdriver, **kwargs)

Response: Class method short cut to call PageFactory. create_page on itself using a webdriver.


Instruction:
How would you explain what the following Python 3 function does
def create_page(page_object_class_or_interface,
                    webdriver=None, **kwargs):
        """
        Instantiate a page object from a given Interface or Abstract class.

        Args:
            page_object_class_or_interface (Class): PageObject class, AbstractBaseClass, or
            Interface to attempt to consturct.

        Kwargs:
            webdriver (WebDriver): Selenium Webdriver to use to instantiate the page. If none
                                   is provided, then it was use the default from
                                   WTF_WEBDRIVER_MANAGER

        Returns:
            PageObject

        Raises:
            NoMatchingPageError

        Instantiating a Page from PageObject from class usage::

            my_page_instance = PageFactory.create_page(MyPageClass)

        Instantiating a Page from an Interface or base class::

            import pages.mysite.*  # Make sure you import classes first, or else PageFactory will not know about it.
            my_page_instance = PageFactory.create_page(MyPageInterfaceClass)

        Instantiating a Page from a list of classes.::

            my_page_instance = PageFactory.create_page([PossiblePage1, PossiblePage2])

        Note: It'll only be able to detect pages that are imported.  To it's best to
        do an import of all pages implementing a base class or the interface inside the
        __init__.py of the package directory.

        """
        if not webdriver:
            webdriver = WTF_WEBDRIVER_MANAGER.get_driver()

        # will be used later when tracking best matched page.
        current_matched_page = None

        # used to track if there is a valid page object within the set of PageObjects searched.
        was_validate_called = False

        # Walk through all classes if a list was passed.
        if type(page_object_class_or_interface) == list:
            subclasses = []
            for page_class in page_object_class_or_interface:
                # attempt to instantiate class.
                page = PageFactory.__instantiate_page_object(page_class,
                                                             webdriver,
                                                             **kwargs)

                if isinstance(page, PageObject):
                    was_validate_called = True
                    if (current_matched_page == None or page > current_matched_page):
                        current_matched_page = page

                elif page is True:
                    was_validate_called = True

                # check for subclasses
                subclasses += PageFactory.__itersubclasses(page_class)
        else:
            # A single class was passed in, try to instantiate the class.
            page_class = page_object_class_or_interface
            page = PageFactory.__instantiate_page_object(page_class,
                                                         webdriver,
                                                         **kwargs)
            # Check if we got a valid PageObject back.
            if isinstance(page, PageObject):
                was_validate_called = True
                current_matched_page = page
            elif page is True:
                was_validate_called = True

            # check for subclasses
            subclasses = PageFactory.__itersubclasses(
                page_object_class_or_interface)

        # Iterate over subclasses of the passed in classes to see if we have a
        # better match.
        for pageClass in subclasses:
            try:
                page = PageFactory.__instantiate_page_object(pageClass,
                                                      webdriver,
                                                      **kwargs)
                # If we get a valid PageObject match, check to see if the ranking is higher
                # than our current PageObject.
                if isinstance(page, PageObject):
                    was_validate_called = True
                    if current_matched_page == None or page > current_matched_page:
                        current_matched_page = page
                elif page is True:
                    was_validate_called = True

            except InvalidPageError as e:
                _wtflog.debug("InvalidPageError: %s", e)
                pass  # This happens when the page fails check.
            except TypeError as e:
                _wtflog.debug("TypeError: %s", e)
                # this happens when it tries to instantiate the original
                # abstract class.
                pass
            except Exception as e:
                _wtflog.debug("Exception during page instantiation: %s", e)
                # Unexpected exception.
                raise e

        # If no matching classes.
        if not isinstance(current_matched_page, PageObject):
            # Check that there is at least 1 valid page object that was passed in.
            if was_validate_called is False:
                raise TypeError("Neither the PageObjects nor it's subclasses have implemented " +
                                "'PageObject._validate(self, webdriver)'.")

            try:
                current_url = webdriver.current_url
                raise NoMatchingPageError(u("There's, no matching classes to this page. URL:{0}")
                                          .format(current_url))
            except:
                raise NoMatchingPageError(u("There's, no matching classes to this page. "))
        else:
            return current_matched_page

Response: Instantiate a Page object from a given class or interface.


Instruction:
Implement a Python 3 function for
attempting to instantiate a page object.

Response:
def __instantiate_page_object(page_obj_class, webdriver, **kwargs):
        """
        Attempts to instantiate a page object.

        Args:
            page_obj_class (PageObject) - PageObject to instantiate.
            webdriver (WebDriver) - Selenium webdriver to associate with the PageObject

        Returns:
            PageObject - If page object instantiation succeeded.
            True - If page object instantiation failed, but validation was called.
            None - If validation did not occur.

        """
        try:
            page = page_obj_class(webdriver, **kwargs)
            return page
        except InvalidPageError:
            # This happens when the page fails check.
            # Means validate was implemented, but the check didn't pass.
            return True
        except TypeError:
            # this happens when it tries to instantiate the original abstract
            # class, or a PageObject where _validate() was not implemented.
            return False
        except Exception as e:
            # Unexpected exception.
            raise e


Instruction:
Write a Python 3 function that can
iterate over all subclasses of a given class.

Response:
def __itersubclasses(cls, _seen=None):
        """

        Credit goes to: http://code.activestate.com/recipes/576949-find-all-subclasses-of-a-given-class/

        itersubclasses(cls)

        Generator over all subclasses of a given class, in depth first order.

        >>> list(itersubclasses(int)) == [bool]
        True
        >>> class A(object): pass
        >>> class B(A): pass
        >>> class C(A): pass
        >>> class D(B,C): pass
        >>> class E(D): pass
        >>>
        >>> for cls in itersubclasses(A):
        ...     print(cls.__name__)
        B
        D
        E
        C
        >>> # get ALL (new-style) classes currently defined
        >>> [cls.__name__ for cls in itersubclasses(object)] #doctest: +ELLIPSIS
        ['type', ...'tuple', ...]
        """
        if not isinstance(cls, type):
            raise TypeError(u('Argument ({0}) passed to PageFactory does not appear to be a valid Class.').format(cls),
                            "Check to make sure the first parameter is an PageObject class, interface, or mixin.")
        if _seen is None:
            _seen = set()
        try:
            subs = cls.__subclasses__()
        except TypeError:  # fails only when cls is type
            subs = cls.__subclasses__(cls)
        for sub in subs:
            if sub not in _seen:
                _seen.add(sub)
                yield sub
                for sub in PageFactory.__itersubclasses(sub, _seen):
                    yield sub


Instruction:
Implement a Python 3 function for
checking if all CSS selectors passed in are found.

Response:
def check_css_selectors(webdriver, *selectors):
        """Returns true if all CSS selectors passed in is found.  This can be used
        to quickly validate a page.

        Args:
            webdriver (Webdriver) : Selenium Webdriver instance
            selectors (str) : N number of CSS selectors strings to match against the page.

        Returns:
            True, False - if the page matches all selectors.

        Usage Example::

            # Checks for a Form with id='loginForm' and a button with class 'login'
            if not PageObjectUtils.check_css_selectors("form#loginForm", "button.login"):
                raise InvalidPageError("This is not the login page.")

        You can use this within a PageObject's `_validate_page(webdriver)` method for
        validating pages.
        """
        for selector in selectors:
            try:
                webdriver.find_element_by_css_selector(selector)
            except:
                return False  # A selector failed.

        return True


Instruction:
Explain what the following Python 3 code does
def wait_until_page_loaded(page_obj_class,
                               webdriver=None,
                               timeout=WTF_TIMEOUT_MANAGER.NORMAL,
                               sleep=0.5,
                               bad_page_classes=[],
                               message=None,
                               **kwargs):
        """
        Waits until the page is loaded.

        Args:
            page_obj_class (Class) : PageObject class

        Kwargs:
            webdriver (Webdriver) : Selenium Webdriver.  Default uses WTF_WEBDRIVER_MANAGER's instance.
            timeout (number) : Number of seconds to wait to allow the page to load.
            sleep (number) : Number of seconds to wait between polling.
            bad_page_classes (list) : List of PageObject classes to fail if matched.  For example, ServerError page.
            message (string) : Use your own message with PageLoadTimeoutError raised.

        Returns:
            PageObject

        Raises:
            PageUtilOperationTimeoutError : Timeout occurred before the desired PageObject was matched.
            BadPageEncounteredError : One or more of the PageObject in the specified 'bad_page_classes' list
            was matched.

        Usage Example::
            webdriver.get("http://www.mysite.com/login")
            # Wait up to 60 seconds for the page to load.
            login_page = wait_until_page_loaded(LoginPage, timeout=60, [ServerErrorPage])

        This will wait for the login_page to load, then return a LoginPage() PageObject.

        """
        if not webdriver:
            webdriver = WTF_WEBDRIVER_MANAGER.get_driver()

        # convert this param to list if not already.
        if type(bad_page_classes) != list:
            bad_page_classes = [bad_page_classes]

        end_time = datetime.now() + timedelta(seconds=timeout)
        last_exception = None
        while datetime.now() < end_time:
            # Check to see if we're at our target page.
            try:
                page = PageFactory.create_page(
                    page_obj_class, webdriver=webdriver, **kwargs)
                return page
            except Exception as e:
                _wtflog.debug("Encountered exception: %s ", e)
                last_exception = e

            # Check to see if we're at one of those labled 'Bad' pages.
            for bad_page_class in bad_page_classes:
                try:
                    PageFactory.create_page(
                        bad_page_class, webdriver=webdriver, **kwargs)
                    # if the if/else statement succeeds, than we have an error.
                    raise BadPageEncounteredError(
                        u("Encountered a bad page. ") + bad_page_class.__name__)
                except BadPageEncounteredError as e:
                    raise e
                except:
                    pass  # We didn't hit a bad page class yet.
            # sleep till the next iteration.
            time.sleep(sleep)

        print "Unable to construct page, last exception", last_exception

        # Attempt to get current URL to assist in debugging
        try:
            current_url = webdriver.current_url
        except:
            # unable to get current URL, could be a webdriver for a non-webpage like mobile app.
            current_url = None

        if message:
            err_msg = u(message) + u("{page}:{url}")\
                .format(page=PageUtils.__get_name_for_class__(page_obj_class),
                        url=current_url)
        else:
            err_msg = u("Timed out while waiting for {page} to load. Url:{url}")\
                .format(page=PageUtils.__get_name_for_class__(page_obj_class),
                        url=current_url)
        raise PageLoadTimeoutError(err_msg)

Response: Waits until a page is loaded.


Instruction:
Implement a Python 3 function for
waiting until the page is ready.

Response:
def wait_until_page_ready(page_object, timeout=WTF_TIMEOUT_MANAGER.NORMAL):
        """Waits until document.readyState == Complete (e.g. ready to execute javascript commands)

        Args:
            page_object (PageObject) : PageObject class

        Kwargs:
            timeout (number) : timeout period
        """
        try:
            do_until(lambda: page_object.webdriver.execute_script("return document.readyState").lower()
                     == 'complete', timeout)
        except wait_utils.OperationTimeoutError:
            raise PageUtilOperationTimeoutError(
                "Timeout occurred while waiting for page to be ready.")


Instruction:
Can you tell what is the following Python 3 function doing
def get_asset_path(self, filename):
        if os.path.exists(os.path.join(self._asset_path, filename)):
            return os.path.join(self._asset_path, filename)
        else:
            raise AssetNotFoundError(
                u("Cannot find asset: {0}").format(filename))

Response: Get the full system path of a given asset.


Instruction:
Write a Python 3 script to
create a Selenium WebDriver instance based on config settings.

Response:
def create_webdriver(self, testname=None):
        '''
            Creates an instance of Selenium webdriver based on config settings.
            This should only be called by a shutdown hook.  Do not call directly within
            a test.

            Kwargs:
                testname: Optional test name to pass, this gets appended to the test name
                          sent to selenium grid.

            Returns:
                WebDriver - Selenium Webdriver instance.

        '''
        try:
            driver_type = self._config_reader.get(
                self.DRIVER_TYPE_CONFIG)
        except:
            driver_type = self.DRIVER_TYPE_LOCAL
            _wtflog.warn("%s setting is missing from config. Using default setting, %s",
                         self.DRIVER_TYPE_CONFIG, driver_type)

        if driver_type == self.DRIVER_TYPE_REMOTE:
            # Create desired capabilities.
            self.webdriver = self.__create_remote_webdriver_from_config(
                testname=testname)
        else:
            # handle as local webdriver
            self.webdriver = self.__create_driver_from_browser_config()
        try:
            self.webdriver.maximize_window()
        except:
            # wait a short period and try again.
            time.sleep(self._timeout_mgr.BRIEF)
            try:
                self.webdriver.maximize_window()
            except Exception as e:
                if (isinstance(e, WebDriverException) and
                    "implemented" in e.msg.lower()):
                    pass  # Maximizing window not supported by this webdriver.
                else:
                    _wtflog.warn("Unable to maxmize browser window. " +
                                 "It may be possible the browser did not instantiate correctly. % s",
                                 e)

        return self.webdriver


Instruction:
Can you generate a brief explanation for the following Python 3 code
def __create_driver_from_browser_config(self):
        '''
        Reads the config value for browser type.
        '''
        try:
            browser_type = self._config_reader.get(
                WebDriverFactory.BROWSER_TYPE_CONFIG)
        except KeyError:
            _wtflog("%s missing is missing from config file. Using defaults",
                    WebDriverFactory.BROWSER_TYPE_CONFIG)
            browser_type = WebDriverFactory.FIREFOX

        # Special Chrome Sauce
        options = webdriver.ChromeOptions()
        options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"])
        options.add_argument("always-authorize-plugins")

        browser_type_dict = {
            self.CHROME: lambda: webdriver.Chrome(
                self._config_reader.get(WebDriverFactory.CHROME_DRIVER_PATH),
                chrome_options=options),
            self.FIREFOX: lambda: webdriver.Firefox(),
            self.INTERNETEXPLORER: lambda: webdriver.Ie(),
            self.OPERA: lambda: webdriver.Opera(),
            self.PHANTOMJS: lambda: self.__create_phantom_js_driver(),
            self.SAFARI: lambda: self.__create_safari_driver()
        }

        try:
            return browser_type_dict[browser_type]()
        except KeyError:
            raise TypeError(
                u("Unsupported Browser Type {0}").format(browser_type))

Response: Reads the config value for browser type.


Instruction:
How would you explain what the following Python 3 function does
def __create_safari_driver(self):
        '''
        Creates an instance of Safari webdriver.
        '''
        # Check for selenium jar env file needed for safari driver.
        if not os.getenv(self.__SELENIUM_SERVER_JAR_ENV):
            # If not set, check if we have a config setting for it.
            try:
                selenium_server_path = self._config_reader.get(
                    self.SELENIUM_SERVER_LOCATION)
                self._env_vars[
                    self.__SELENIUM_SERVER_JAR_ENV] = selenium_server_path
            except KeyError:
                raise RuntimeError(u("Missing selenium server path config {0}.").format(
                    self.SELENIUM_SERVER_LOCATION))

        return webdriver.Safari()

Response: Creates an instance of Safari webdriver.


Instruction:
How would you code a function in Python 3 to
create an instance of PhantomJS driver.

Response:
def __create_phantom_js_driver(self):
        '''
        Creates an instance of PhantomJS driver.
        '''
        try:
            return webdriver.PhantomJS(executable_path=self._config_reader.get(self.PHANTOMEJS_EXEC_PATH),
                                       service_args=['--ignore-ssl-errors=true'])
        except KeyError:
            return webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])


Instruction:
Implement a Python 3 function for
creating a remote webdriver instance from the config file.

Response:
def __create_remote_webdriver_from_config(self, testname=None):
        '''
        Reads the config value for browser type.
        '''
        desired_capabilities = self._generate_desired_capabilities(testname)

        remote_url = self._config_reader.get(
            WebDriverFactory.REMOTE_URL_CONFIG)

        # Instantiate remote webdriver.
        driver = webdriver.Remote(
            desired_capabilities=desired_capabilities,
            command_executor=remote_url
        )

        # Log IP Address of node if configured, so it can be used to
        # troubleshoot issues if they occur.
        log_driver_props = \
            self._config_reader.get(
                WebDriverFactory.LOG_REMOTEDRIVER_PROPS, default_value=False
            ) in [True, "true", "TRUE", "True"]
        if "wd/hub" in remote_url and log_driver_props:
            try:
                grid_addr = remote_url[:remote_url.index("wd/hub")]
                info_request_response = urllib2.urlopen(
                    grid_addr + "grid/api/testsession?session=" + driver.session_id, "", 5000)
                node_info = info_request_response.read()
                _wtflog.info(
                    u("RemoteWebdriver using node: ") + u(node_info).strip())
            except:
                # Unable to get IP Address of remote webdriver.
                # This happens with many 3rd party grid providers as they don't want you accessing info on nodes on
                # their internal network.
                pass

        return driver


Instruction:
Can you write a function in Python 3 where it
cleans up webdrivers created during execution.

Response:
def clean_up_webdrivers(self):
        '''
        Clean up webdrivers created during execution.
        '''
        # Quit webdrivers.
        _wtflog.info("WebdriverManager: Cleaning up webdrivers")
        try:
            if self.__use_shutdown_hook:
                for key in self.__registered_drivers.keys():
                    for driver in self.__registered_drivers[key]:
                        try:
                            _wtflog.debug(
                                "Shutdown hook closing Webdriver for thread: %s", key)
                            driver.quit()
                        except:
                            pass
        except:
            pass


Instruction:
Create a Python 3 function to
close current running instance of Webdriver.

Response:
def close_driver(self):
        """
        Close current running instance of Webdriver.

        Usage::

            driver = WTF_WEBDRIVER_MANAGER.new_driver()
            driver.get("http://the-internet.herokuapp.com")
            WTF_WEBDRIVER_MANAGER.close_driver()
        """
        channel = self.__get_channel()
        driver = self.__get_driver_for_channel(channel)
        if self.__config.get(self.REUSE_BROWSER, True):
            # If reuse browser is set, we'll avoid closing it and just clear out the cookies,
            # and reset the location.
            try:
                driver.delete_all_cookies()
                # check to see if webdriver is still responding
                driver.get("about:blank")
            except:
                pass

        if driver is not None:
            try:
                driver.quit()
            except:
                pass

            self.__unregister_driver(channel)
            if driver in self.__registered_drivers[channel]:
                self.__registered_drivers[channel].remove(driver)

            self.webdriver = None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_driver(self):
        '''
        Get an already running instance of Webdriver. If there is none, it will create one.

        Returns:
            Webdriver - Selenium Webdriver instance.

        Usage::

            driver = WTF_WEBDRIVER_MANAGER.new_driver()
            driver.get("http://the-internet.herokuapp.com")
            same_driver = WTF_WEBDRIVER_MANAGER.get_driver()
            print(driver is same_driver) # True
        '''
        driver = self.__get_driver_for_channel(self.__get_channel())
        if driver is None:
            driver = self.new_driver()

        return driver

Response: Get an already running instance of Webdriver.


Instruction:
Given the following Python 3 function, write the documentation
def new_driver(self, testname=None):
        '''
        Used at a start of a test to get a new instance of WebDriver.  If the
        'resuebrowser' setting is true, it will use a recycled WebDriver instance
        with delete_all_cookies() called.

        Kwargs:
            testname (str) - Optional test name to pass to Selenium Grid.  Helpful for
                             labeling tests on 3rd party WebDriver cloud providers.

        Returns:
            Webdriver - Selenium Webdriver instance.

        Usage::

            driver = WTF_WEBDRIVER_MANAGER.new_driver()
            driver.get("http://the-internet.herokuapp.com")
        '''
        channel = self.__get_channel()

        # Get reference for the current driver.
        driver = self.__get_driver_for_channel(channel)

        if self.__config.get(WebDriverManager.REUSE_BROWSER, True):

            if driver is None:
                driver = self._webdriver_factory.create_webdriver(
                    testname=testname)

                # Register webdriver so it can be retrieved by the manager and
                # cleaned up after exit.
                self.__register_driver(channel, driver)
            else:
                try:
                    # Attempt to get the browser to a pristine state as possible when we are
                    # reusing this for another test.
                    driver.delete_all_cookies()
                    # check to see if webdriver is still responding
                    driver.get("about:blank")
                except:
                    # In the case the browser is unhealthy, we should kill it
                    # and serve a new one.
                    try:
                        if driver.is_online():
                            driver.quit()
                    except:
                        pass

                    driver = self._webdriver_factory.create_webdriver(
                        testname=testname)
                    self.__register_driver(channel, driver)

        else:
            # Attempt to tear down any existing webdriver.
            if driver is not None:
                try:
                    driver.quit()
                except:
                    pass
            self.__unregister_driver(channel)
            driver = self._webdriver_factory.create_webdriver(
                testname=testname)
            self.__register_driver(channel, driver)

        return driver

Response: Create a new instance of Selenium Webdriver.


Instruction:
Write a Python 3 script to
register webdriver to a channel.

Response:
def __register_driver(self, channel, webdriver):
        "Register webdriver to a channel."

        # Add to list of webdrivers to cleanup.
        if not self.__registered_drivers.has_key(channel):
            self.__registered_drivers[channel] = []  # set to new empty array

        self.__registered_drivers[channel].append(webdriver)

        # Set singleton instance for the channel
        self.__webdriver[channel] = webdriver


Instruction:
Here you have a function in Python 3, explain what it does
def __get_channel(self):
        "Get the channel to register webdriver to."
        if self.__config.get(WebDriverManager.ENABLE_THREADING_SUPPORT, False):
            channel = current_thread().ident
        else:
            channel = 0

        return channel

Response: Get the channel to register webdriver to.


Instruction:
Make a summary of the following Python 3 code
def take_screenshot(webdriver, file_name):
        folder_location = os.path.join(ProjectUtils.get_project_root(),
                                       WebScreenShotUtil.SCREEN_SHOT_LOCATION)

        WebScreenShotUtil.__capture_screenshot(
            webdriver, folder_location, file_name + ".png")

Response:
Captures a screenshot.

        Args:
            webdriver (WebDriver) - Selenium webdriver.
            file_name (str) - File name to save screenshot as.


Instruction:
Make a summary of the following Python 3 code
def take_reference_screenshot(webdriver, file_name):
        folder_location = os.path.join(ProjectUtils.get_project_root(),
                                       WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION)

        WebScreenShotUtil.__capture_screenshot(
            webdriver, folder_location, file_name + ".png")

Response: Takes a screenshot as a reference screenshot.


Instruction:
How would you explain what the following Python 3 function does
def get_project_root(cls):
        '''
        Return path of the project directory.  Use this method for getting paths relative to the project.
        However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended
        to use WTF_ASSET_MANAGER, which are already singleton instances that manger the /data, and /assets
        folder for you.

        Returns:
            str - path of project root directory.
        '''
        if(cls.__root_folder__ != None):
            return cls.__root_folder__

        # Check for enviornment variable override.
        try:
            cls.__root_folder__ = os.environ[cls.WTF_HOME_CONFIG_ENV_VAR]
        except KeyError:
            # Means WTF_HOME override isn't specified.
            pass

        # Search starting from the current working directory and traverse up parent directories for the
        # hidden file denoting the project root folder.
        path = os.getcwd()
        seperator_matches = re.finditer("/|\\\\", path)

        paths_to_search = [path]
        for match in seperator_matches:
            p = path[:match.start()]
            paths_to_search.insert(0, p)

        for path in paths_to_search:
            target_path = os.path.join(path, cls.__WTF_ROOT_FOLDER_FILE)
            if os.path.isfile(target_path):
                cls.__root_folder__ = path
                return cls.__root_folder__

        raise RuntimeError(u("Missing root project folder locator file '.wtf_root_folder'.")
                           + u("Check to make sure this file is located in your project directory."))

Response: Get the project root directory.


Instruction:
Explain what the following Python 3 code does
def do_until(lambda_expr, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, message=None):
    '''
    A retry wrapper that'll keep performing the action until it succeeds.
    (main differnce between do_until and wait_until is do_until will keep trying
    until a value is returned, while wait until will wait until the function
    evaluates True.)

    Args:
        lambda_expr (lambda) : Expression to evaluate.

    Kwargs:
        timeout (number): Timeout period in seconds.
        sleep (number) : Sleep time to wait between iterations
        message (str) : Provide a message for TimeoutError raised.

    Returns:
        The value of the evaluated lambda expression.

    Usage::

        do_until(lambda: driver.find_element_by_id("save").click(),
                 timeout=30,
                 sleep=0.5)

    Is equivalent to:

        end_time = datetime.now() + timedelta(seconds=30)
        while datetime.now() < end_time:
            try:
                return driver.find_element_by_id("save").click()
            except:
                pass
            time.sleep(0.5)
        raise OperationTimeoutError()
    '''
    __check_condition_parameter_is_function(lambda_expr)

    end_time = datetime.now() + timedelta(seconds=timeout)
    last_exception = None
    while datetime.now() < end_time:
        try:
            return lambda_expr()
        except Exception as e:
            last_exception = e
            time.sleep(sleep)

    if message:
        raise OperationTimeoutError(message, last_exception)
    else:
        raise OperationTimeoutError("Operation timed out.", last_exception)

Response: A retry wrapper that will keep performing the action until the function evaluates True.


Instruction:
Can you write a function in Python 3 where it
waits until condition is met and returns the result.

Response:
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5):
    '''
    Waits wrapper that'll wait for the condition to become true, but will
    not error if the condition isn't met.

    Args:
        condition (lambda) - Lambda expression to wait for to evaluate to True.

    Kwargs:
        timeout (number) : Maximum number of seconds to wait.
        sleep (number) : Sleep time to wait between iterations.

    Example::

        wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(),
                       timeout=30,
                       sleep=0.5)

    is equivalent to::

        end_time = datetime.now() + timedelta(seconds=30)
        while datetime.now() < end_time:
            try:
                if driver.find_element_by_id("success").is_displayed():
                    break;
            except:
                pass
            time.sleep(0.5)
    '''
    try:
        return wait_until(condition, timeout, sleep)
    except:
        pass


Instruction:
How would you implement a function in Python 3 that
waits until a condition is true.

Response:
def wait_until(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, pass_exceptions=False, message=None):
    '''
    Waits wrapper that'll wait for the condition to become true.
    (main differnce between do_until and wait_until is do_until will keep trying
    until a value is returned, while wait until will wait until the function
    evaluates True.)

    Args:
        condition (lambda) - Lambda expression to wait for to evaluate to True.

    Kwargs:
        timeout (number) : Maximum number of seconds to wait.
        sleep (number) : Sleep time to wait between iterations.
        pass_exceptions (bool) : If set true, any exceptions raised will be re-raised up the chain.
                                Normally exceptions are ignored.
        message (str) : Optional message to pass into OperationTimeoutError if the wait times out.

    Example::

        wait_until(lambda: driver.find_element_by_id("success").is_displayed(),
                   timeout=30,
                   sleep=0.5)

    is equivalent to::

        end_time = datetime.now() + timedelta(seconds=30)
        did_succeed = False
        while datetime.now() < end_time:
            try:
                if driver.find_element_by_id("success").is_displayed():
                    did_succeed = True
                    break;
            except:
                pass
            time.sleep(0.5)
        if not did_succeed:
            raise OperationTimeoutError()
    '''
    __check_condition_parameter_is_function(condition)

    last_exception = None
    end_time = datetime.now() + timedelta(seconds=timeout)
    while datetime.now() < end_time:
        try:
            if condition():
                return
        except Exception as e:
            if pass_exceptions:
                raise e
            else:
                last_exception = e
        time.sleep(sleep)

    if message:
        if last_exception:
            raise OperationTimeoutError(message, e)
        else:
            raise OperationTimeoutError(message)
    else:
        if last_exception:
            raise OperationTimeoutError("Operation timed out.", e)
        else:
            raise OperationTimeoutError("Operation timed out.")


Instruction:
How would you code a function in Python 3 to
search for an email by Subject. Returns True or False.

Response:
def check_email_exists_by_subject(self, subject, match_recipient=None):
        """
        Searches for Email by Subject.  Returns True or False.

        Args:
            subject (str): Subject to search for.

        Kwargs:
            match_recipient (str) : Recipient to match exactly. (don't care if not specified)

        Returns:
            True - email found, False - email not found

        """
        # Select inbox to fetch the latest mail on server.
        self._mail.select("inbox")

        try:
            matches = self.__search_email_by_subject(subject, match_recipient)
            if len(matches) <= 0:
                return False
            else:
                return True
        except Exception as e:
            raise e


Instruction:
Write a Python 3 function that can
search for Email by Subject. Returns a list of Integers representing the email s UIDs if matching subjects is found.

Response:
def find_emails_by_subject(self, subject, limit=50, match_recipient=None):
        """
        Searches for Email by Subject.  Returns email's imap message IDs
        as a list if matching subjects is found.

        Args:
            subject (str) - Subject to search for.

        Kwargs:
            limit (int) - Limit search to X number of matches, default 50
            match_recipient (str) - Recipient to exactly (don't care if not specified)

        Returns:
            list - List of Integers representing imap message UIDs.

        """
        # Select inbox to fetch the latest mail on server.
        self._mail.select("inbox")

        matching_uids = self.__search_email_by_subject(
            subject, match_recipient)

        return matching_uids


Instruction:
How would you implement a function in Python 3 that
fetches contents of an email.

Response:
def get_email_message(self, message_uid, message_type="text/plain"):
        """
        Fetch contents of email.

        Args:
            message_uid (int): IMAP Message UID number.

        Kwargs:
            message_type: Can be 'text' or 'html'

        """
        self._mail.select("inbox")
        result = self._mail.uid('fetch', message_uid, "(RFC822)")
        msg = email.message_from_string(result[1][0][1])

        try:
            # Try to handle as multipart message first.
            for part in msg.walk():
                if part.get_content_type() == message_type:
                    return part.get_payload(decode=True)
        except:
            # handle as plain text email
            return msg.get_payload(decode=True)


Instruction:
Write a Python 3 function for
finding the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search through. date (datetime) - If specified, it will filter avoid checking messages older than this date.

Response:
def raw_search(self, *args, **kwargs):
        """
        Find the a set of emails matching each regular expression passed in against the (RFC822) content.

        Args:
            *args: list of regular expressions.

        Kwargs:
            limit (int) - Limit to how many of the most resent emails to search through.
            date (datetime) - If specified, it will filter avoid checking messages older
                              than this date.

        """
        limit = 50
        try:
            limit = kwargs['limit']
        except KeyError:
            pass

        # Get first X messages.
        self._mail.select("inbox")

        # apply date filter.
        try:
            date = kwargs['date']
            date_str = date.strftime("%d-%b-%Y")
            _, email_ids = self._mail.search(None, '(SINCE "%s")' % date_str)
        except KeyError:
            _, email_ids = self._mail.search(None, 'ALL')

        # Above call returns email IDs as an array containing 1 str
        email_ids = email_ids[0].split()

        matching_uids = []
        for _ in range(1, min(limit, len(email_ids))):
            email_id = email_ids.pop()
            rfc_body = self._mail.fetch(email_id, "(RFC822)")[1][0][1]

            match = True
            for expr in args:
                if re.search(expr, rfc_body) is None:
                    match = False
                    break

            if match:
                uid = re.search(
                    "UID\\D*(\\d+)\\D*", self._mail.fetch(email_id, 'UID')[1][0]).group(1)
                matching_uids.append(uid)

        return matching_uids


Instruction:
Implement a Python 3 function for
getting a list of message numbers

Response:
def __search_email_by_subject(self, subject, match_recipient):
        "Get a list of message numbers"
        if match_recipient is None:
            _, data = self._mail.uid('search',
                                     None,
                                     '(HEADER SUBJECT "{subject}")'
                                     .format(subject=subject))

            uid_list = data[0].split()
            return uid_list
        else:
            _, data = self._mail.uid('search',
                                     None,
                                     '(HEADER SUBJECT "{subject}" TO "{recipient}")'
                                     .format(subject=subject, recipient=match_recipient))

            filtered_list = []
            uid_list = data[0].split()
            for uid in uid_list:
                # Those hard coded indexes [1][0][1] is a hard reference to the message email message headers
                # that's burried in all those wrapper objects that's associated
                # with fetching a message.
                to_addr = re.search(
                    "[^-]To: (.*)", self._mail.uid('fetch', uid, "(RFC822)")[1][0][1]).group(1).strip()

                if (to_addr == match_recipient or to_addr == "<{0}>".format(match_recipient)):
                    # Add matching entry to the list.
                    filtered_list.append(uid)

            return filtered_list


Instruction:
Implement a Python 3 function for
getting the value from the yaml config file based on the key.

Response:
def get(self, key, default_value=__NoDefaultSpecified__):
        '''
        Gets the value from the yaml config based on the key.

        No type casting is performed, any type casting should be
        performed by the caller.

        Args:
            key (str) - Config setting key.

        Kwargs:
            default_value - Default value to return if config is not specified.

        Returns:
            Returns value stored in config file.

        '''
        # First attempt to get the var from OS enviornment.
        os_env_string = ConfigReader.ENV_PREFIX + key
        os_env_string = os_env_string.replace(".", "_")
        if type(os.getenv(os_env_string)) != NoneType:
            return os.getenv(os_env_string)

        # Otherwise search through config files.
        for data_map in self._dataMaps:
            try:
                if "." in key:
                    # this is a multi levl string
                    namespaces = key.split(".")
                    temp_var = data_map
                    for name in namespaces:
                        temp_var = temp_var[name]
                    return temp_var
                else:
                    value = data_map[key]
                    return value
            except (AttributeError, TypeError, KeyError):
                pass

        if default_value == self.__NoDefaultSpecified__:
            raise KeyError(u("Key '{0}' does not exist").format(key))
        else:
            return default_value


Instruction:
How would you explain what the following Python 3 function does
def generate_page_object(page_name, url):
    "Generate page object from URL"

    # Attempt to extract partial URL for verification.
    url_with_path = u('^.*//[^/]+([^?]+)?|$')
    try:
        match = re.match(url_with_path, url)
        partial_url = match.group(1)
        print("Using partial URL for location verification. ", partial_url)
    except:
        # use full url since we couldn't extract a partial.
        partial_url = url
        print("Could not find usable partial url, using full url.", url)

    # Attempt to map input objects.
    print("Processing page source...")
    response = urllib2.urlopen(url)
    html = response.read()
    input_tags_expr = u('<\s*input[^>]*>')
    input_tag_iter = re.finditer(input_tags_expr, html, re.IGNORECASE)

    objectmap = ""
    print("Creating object map for <input> tags...")
    for input_tag_match in input_tag_iter:
        if not "hidden" in input_tag_match.group(0):
            try:
                print("processing", input_tag_match.group(0))
                obj_map_entry = _process_input_tag(input_tag_match.group(0))
                objectmap += u("    ") + obj_map_entry + "\n"
            except Exception as e:
                print(e)
                # we failed to process it, nothing more we can do.
                pass

    return _page_object_template_.contents.format(date=datetime.now(),
                                                  url=url,
                                                  pagename=page_name,
                                                  partialurl=partial_url,
                                                  objectmap=objectmap)

Response: Generate page object from URL


Instruction:
Can you write a function in Python 3 where it
gets data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAGER.get_data_path('testdata.csv') Note: WTF_DATA_MANAGER is a provided global instance of DataManager

Response:
def get_data_path(self, filename, env_prefix=None):
        """
        Get data path.

        Args:
            filename (string) : Name of file inside of /data folder to retrieve.

        Kwargs:
            env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa

        Returns:
            String - path to file.

        Usage::

            open(WTF_DATA_MANAGER.get_data_path('testdata.csv')

        Note: WTF_DATA_MANAGER is a provided global instance of DataManager

        """
        if env_prefix == None:
            target_file = filename
        else:
            target_file = os.path.join(env_prefix, filename)

        if os.path.exists(os.path.join(self._data_path, target_file)):
            return os.path.join(self._data_path, target_file)
        else:
            raise DataNotFoundError(
                u("Cannot find data file: {0}").format(target_file))


Instruction:
Here you have a function in Python 3, explain what it does
def next(self):
        try:
            entry = {}
            row = self._csv_reader.next()
            for i in range(0, len(row)):
                entry[self._headers[i]] = row[i]

            return entry
        except Exception as e:
            # close our file when we're done reading.
            self._file.close()
            raise e

Response: Gets next entry as a dictionary.


Instruction:
Explain what the following Python 3 code does
def find_element_by_selectors(webdriver, *selectors):
        # perform initial check to verify selectors are valid by statements.
        for selector in selectors:
            (by_method, value) = selector
            if not WebElementSelector.__is_valid_by_type(by_method):
                raise BadSelectorError(
                    u("Selectors should be of type selenium.webdriver.common.by.By"))
            if type(value) != str:
                raise BadSelectorError(
                    u("Selectors should be of type selenium.webdriver.common.by.By"))

        selectors_used = []
        for selector in selectors:
            (by_method, value) = selector
            selectors_used.append(
                u("{by}:{value}").format(by=by_method, value=value))
            try:
                return webdriver.find_element(by=by_method, value=value)
            except:
                pass

        raise ElementNotSelectableException(
            u("Unable to find elements using:") + u(",").join(selectors_used))

Response: Utility method makes it easier to find an element using multiple selectors. This method will return a new element if the element is found.


Instruction:
Here you have a function in Python 3, explain what it does
def wait_until_element_not_visible(webdriver, locator_lambda_expression,
                                       timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5):
        """
        Wait for a WebElement to disappear.

        Args:
            webdriver (Webdriver) - Selenium Webdriver
            locator (lambda) - Locator lambda expression.

        Kwargs:
            timeout (number) - timeout period
            sleep (number) - sleep period between intervals.

        """
        # Wait for loading progress indicator to go away.
        try:
            stoptime = datetime.now() + timedelta(seconds=timeout)
            while datetime.now() < stoptime:
                element = WebDriverWait(webdriver, WTF_TIMEOUT_MANAGER.BRIEF).until(
                    locator_lambda_expression)
                if element.is_displayed():
                    time.sleep(sleep)
                else:
                    break
        except TimeoutException:
            pass

Response: Wait until an element is not visible.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def is_image_loaded(webdriver, webelement):
        '''
        Check if an image (in an image tag) is loaded.
        Note: This call will not work against background images.  Only Images in <img> tags.

        Args:
            webelement (WebElement) - WebDriver web element to validate.

        '''
        script = (u("return arguments[0].complete && type of arguments[0].naturalWidth != \"undefined\" ") +
                 u("&& arguments[0].naturalWidth > 0"))
        try:
            return webdriver.execute_script(script, webelement)
        except:
            return False

Response: Check if an image is loaded.


Instruction:
Implement a Python 3 function for
generating a time - stamped string.

Response:
def generate_timestamped_string(subject="test", number_of_random_chars=4):
    """
    Generate time-stamped string. Format as follows...

    `2013-01-31_14:12:23_SubjectString_a3Zg`

    Kwargs:
        subject (str): String to use as subject.
        number_of_random_chars (int) : Number of random characters to append.

    This method is helpful for creating unique names with timestamps in them so
    when you have to troubleshoot an issue, the name is easier to find.::

        self.project_name = generate_timestamped_string("project")
        new_project_page.create_project(project_name)

    """
    random_str = generate_random_string(number_of_random_chars)
    timestamp = generate_timestamp()
    return u"{timestamp}_{subject}_{random_str}".format(timestamp=timestamp,
                                                        subject=subject,
                                                        random_str=random_str)


Instruction:
Explain what the following Python 3 code does
def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters):
    return u('').join(random.choice(character_set)
                      for _ in range(number_of_random_chars))

Response: Generates a series of random characters.


Instruction:
Write a Python 3 function for
converting the date format pattern used by Weka to the date format pattern used by Python s datetime. strftime.

Response:
def convert_weka_to_py_date_pattern(p):
    """
    Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime().
    """
    # https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
    # https://www.cs.waikato.ac.nz/ml/weka/arff.html
    p = p.replace('yyyy', r'%Y')
    p = p.replace('MM', r'%m')
    p = p.replace('dd', r'%d')
    p = p.replace('HH', r'%H')
    p = p.replace('mm', r'%M')
    p = p.replace('ss', r'%S')
    return p


Instruction:
How would you explain what the following Python 3 function does
def get_attribute_value(self, name, index):
        if index == MISSING:
            return
        elif self.attribute_types[name] in NUMERIC_TYPES:
            at = self.attribute_types[name]
            if at == TYPE_INTEGER:
                return int(index)
            return Decimal(str(index))
        else:
            assert self.attribute_types[name] == TYPE_NOMINAL
            cls_index, cls_value = index.split(':')
            #return self.attribute_data[name][index-1]
            if cls_value != MISSING:
                assert cls_value in self.attribute_data[name], \
                    'Predicted value "%s" but only values %s are allowed.' \
                        % (cls_value, ', '.join(self.attribute_data[name]))
            return cls_value

Response: Returns the value associated with the given value index.


Instruction:
Implement a Python 3 function for
loading an ARFF File from a file.

Response:
def load(cls, filename, schema_only=False):
        """
        Load an ARFF File from a file.
        """
        o = open(filename)
        s = o.read()
        a = cls.parse(s, schema_only=schema_only)
        if not schema_only:
            a._filename = filename
        o.close()
        return a


Instruction:
Can you write a function in Python 3 where it
parses an ARFF File already loaded into a string.

Response:
def parse(cls, s, schema_only=False):
        """
        Parse an ARFF File already loaded into a string.
        """
        a = cls()
        a.state = 'comment'
        a.lineno = 1
        for l in s.splitlines():
            a.parseline(l)
            a.lineno += 1
            if schema_only and a.state == 'data':
                # Don't parse data if we're only loading the schema.
                break
        return a


Instruction:
Write a Python 3 function that can
create a deep copy of the instance.

Response:
def copy(self, schema_only=False):
        """
        Creates a deepcopy of the instance.
        If schema_only is True, the data will be excluded from the copy.
        """
        o = type(self)()
        o.relation = self.relation
        o.attributes = list(self.attributes)
        o.attribute_types = self.attribute_types.copy()
        o.attribute_data = self.attribute_data.copy()
        if not schema_only:
            o.comment = list(self.comment)
            o.data = copy.deepcopy(self.data)
        return o


Instruction:
How would you code a function in Python 3 to
open the arff structure to a file.

Response:
def open_stream(self, class_attr_name=None, fn=None):
        """
        Save an arff structure to a file, leaving the file object
        open for writing of new data samples.
        This prevents you from directly accessing the data via Python,
        but when generating a huge file, this prevents all your data
        from being stored in memory.
        """
        if fn:
            self.fout_fn = fn
        else:
            fd, self.fout_fn = tempfile.mkstemp()
            os.close(fd)
        self.fout = open(self.fout_fn, 'w')
        if class_attr_name:
            self.class_attr_name = class_attr_name
        self.write(fout=self.fout, schema_only=True)
        self.write(fout=self.fout, data_only=True)
        self.fout.flush()


Instruction:
Can you create a Python 3 function that
terminates an open stream and returns the filename of the file containing the streamed data.

Response:
def close_stream(self):
        """
        Terminates an open stream and returns the filename
        of the file containing the streamed data.
        """
        if self.fout:
            fout = self.fout
            fout_fn = self.fout_fn
            self.fout.flush()
            self.fout.close()
            self.fout = None
            self.fout_fn = None
            return fout_fn


Instruction:
Create a Python 3 function for
saving an arff structure to a file.

Response:
def save(self, filename=None):
        """
        Save an arff structure to a file.
        """
        filename = filename or self._filename
        o = open(filename, 'w')
        o.write(self.write())
        o.close()


Instruction:
Write a Python 3 script for
converting a single data line into a string.

Response:
def write_line(self, d, fmt=SPARSE):
        """
        Converts a single data line to a string.
        """

        def smart_quote(s):
            if isinstance(s, basestring) and ' ' in s and s[0] != '"':
                s = '"%s"' % s
            return s

        if fmt == DENSE:
            #TODO:fix
            assert not isinstance(d, dict), NotImplemented
            line = []
            for e, a in zip(d, self.attributes):
                at = self.attribute_types[a]
                if at in NUMERIC_TYPES:
                    line.append(str(e))
                elif at == TYPE_STRING:
                    line.append(self.esc(e))
                elif at == TYPE_NOMINAL:
                    line.append(e)
                else:
                    raise Exception("Type " + at + " not supported for writing!")
            s = ','.join(map(str, line))
            return s
        elif fmt == SPARSE:
            line = []

            # Convert flat row into dictionary.
            if isinstance(d, (list, tuple)):
                d = dict(zip(self.attributes, d))
                for k in d:
                    at = self.attribute_types.get(k)
                    if isinstance(d[k], Value):
                        continue
                    elif d[k] == MISSING:
                        d[k] = Str(d[k])
                    elif at in (TYPE_NUMERIC, TYPE_REAL):
                        d[k] = Num(d[k])
                    elif at == TYPE_STRING:
                        d[k] = Str(d[k])
                    elif at == TYPE_INTEGER:
                        d[k] = Int(d[k])
                    elif at == TYPE_NOMINAL:
                        d[k] = Nom(d[k])
                    elif at == TYPE_DATE:
                        d[k] = Date(d[k])
                    else:
                        raise Exception('Unknown type: %s' % at)

            for i, name in enumerate(self.attributes):
                v = d.get(name)
                if v is None:
#                    print 'Skipping attribute with None value:', name
                    continue
                elif v == MISSING or (isinstance(v, Value) and v.value == MISSING):
                    v = MISSING
                elif isinstance(v, String):
                    v = '"%s"' % v.value
                elif isinstance(v, Date):
                    date_format = self.attribute_data.get(name, DEFAULT_DATE_FORMAT)
                    date_format = convert_weka_to_py_date_pattern(date_format)
                    if isinstance(v.value, basestring):
                        _value = dateutil.parser.parse(v.value)
                    else:
                        assert isinstance(v.value, (date, datetime))
                        _value = v.value
                    v.value = v = _value.strftime(date_format)
                elif isinstance(v, Value):
                    v = v.value

                if v != MISSING and self.attribute_types[name] == TYPE_NOMINAL and str(v) not in map(str, self.attribute_data[name]):
                    pass
                else:
                    line.append('%i %s' % (i, smart_quote(v)))

            if len(line) == 1 and MISSING in line[-1]:
                # Skip lines with nothing other than a missing class.
                return
            elif not line:
                # Don't write blank lines.
                return
            return '{' + (', '.join(line)) + '}'
        else:
            raise Exception('Uknown format: %s' % (fmt,))


Instruction:
Make a summary of the following Python 3 code
def write(self,
        fout=None,
        fmt=SPARSE,
        schema_only=False,
        data_only=False):
        """
        Write an arff structure to a string.
        """
        assert not (schema_only and data_only), 'Make up your mind.'
        assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s' % (fmt, ', '.join(FORMATS))
        close = False
        if fout is None:
            close = True
            fout = StringIO()
        if not data_only:
            print('% ' + re.sub("\n", "\n% ", '\n'.join(self.comment)), file=fout)
            print("@relation " + self.relation, file=fout)
            self.write_attributes(fout=fout)
        if not schema_only:
            print("@data", file=fout)
            for d in self.data:
                line_str = self.write_line(d, fmt=fmt)
                if line_str:
                    print(line_str, file=fout)
        if isinstance(fout, StringIO) and close:
            return fout.getvalue()

Response: Write an arff structure to a string.


Instruction:
Create a Python 3 function to
define a new attribute. atype has to be one of integer real numeric string date nominal or date. data can be a dictionary of data type and value.

Response:
def define_attribute(self, name, atype, data=None):
        """
        Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'.
        For nominal attributes, pass the possible values as data.
        For date attributes, pass the format as data.
        """
        self.attributes.append(name)
        assert atype in TYPES, "Unknown type '%s'. Must be one of: %s" % (atype, ', '.join(TYPES),)
        self.attribute_types[name] = atype
        self.attribute_data[name] = data


Instruction:
How would you code a function in Python 3 to
print an overview of the ARFF file.

Response:
def dump(self):
        """Print an overview of the ARFF file."""
        print("Relation " + self.relation)
        print("  With attributes")
        for n in self.attributes:
            if self.attribute_types[n] != TYPE_NOMINAL:
                print("    %s of type %s" % (n, self.attribute_types[n]))
            else:
                print("    " + n + " of type nominal with values " + ', '.join(self.attribute_data[n]))
        for d in self.data:
            print(d)


Instruction:
Can you create a Python 3 function that
sorts the attributes names alphabetically except for the class attribute which is kept last.

Response:
def alphabetize_attributes(self):
        """
        Orders attributes names alphabetically, except for the class attribute, which is kept last.
        """
        self.attributes.sort(key=lambda name: (name == self.class_attr_name, name))


Instruction:
How would you explain what the following Python 3 function does
def rgb_to_hsl(r, g=None, b=None):
  if type(r) in [list,tuple]:
    r, g, b = r

  minVal = min(r, g, b)       # min RGB value
  maxVal = max(r, g, b)       # max RGB value

  l = (maxVal + minVal) / 2.0
  if minVal==maxVal:
    return (0.0, 0.0, l)    # achromatic (gray)

  d = maxVal - minVal         # delta RGB value

  if l < 0.5: s = d / (maxVal + minVal)
  else: s = d / (2.0 - maxVal - minVal)

  dr, dg, db = [(maxVal-val) / d for val in (r, g, b)]

  if r==maxVal:
    h = db - dg
  elif g==maxVal:
    h = 2.0 + dr - db
  else:
    h = 4.0 + dg - dr

  h = (h*60.0) % 360.0
  return (h, s, l)

Response: Convert the color from RGB coordinates to HSL.


Instruction:
Can you tell what is the following Python 3 function doing
def hsl_to_rgb(h, s=None, l=None):
  if type(h) in [list,tuple]:
    h, s, l = h

  if s==0: return (l, l, l)   # achromatic (gray)

  if l<0.5: n2 = l * (1.0 + s)
  else: n2 = l+s - (l*s)

  n1 = (2.0 * l) - n2

  h /= 60.0
  hueToRgb = _hue_to_rgb
  r = hueToRgb(n1, n2, h + 2)
  g = hueToRgb(n1, n2, h)
  b = hueToRgb(n1, n2, h - 2)

  return (r, g, b)

Response: Convert the color from HSL coordinates to RGB.


Instruction:
Can you tell what is the following Python 3 function doing
def rgb_to_hsv(r, g=None, b=None):
  if type(r) in [list,tuple]:
    r, g, b = r

  v = float(max(r, g, b))
  d = v - min(r, g, b)
  if d==0: return (0.0, 0.0, v)
  s = d / v

  dr, dg, db = [(v - val) / d for val in (r, g, b)]

  if r==v:
    h = db - dg             # between yellow & magenta
  elif g==v:
    h = 2.0 + dr - db       # between cyan & yellow
  else: # b==v
    h = 4.0 + dg - dr       # between magenta & cyan

  h = (h*60.0) % 360.0
  return (h, s, v)

Response: Convert the color from RGB coordinates to HSV.


Instruction:
How would you explain what the following Python 3 function does
def hsv_to_rgb(h, s=None, v=None):
  if type(h) in [list,tuple]:
    h, s, v = h

  if s==0: return (v, v, v)   # achromatic (gray)

  h /= 60.0
  h = h % 6.0

  i = int(h)
  f = h - i
  if not(i&1): f = 1-f     # if i is even

  m = v * (1.0 - s)
  n = v * (1.0 - (s * f))

  if i==0: return (v, n, m)
  if i==1: return (n, v, m)
  if i==2: return (m, v, n)
  if i==3: return (m, n, v)
  if i==4: return (n, m, v)
  return (v, m, n)

Response: Convert the color from RGB coordinates to HSV.


Instruction:
How would you explain what the following Python 3 function does
def rgb_to_yiq(r, g=None, b=None):
  if type(r) in [list,tuple]:
    r, g, b = r

  y = (r * 0.29895808) + (g * 0.58660979) + (b *0.11443213)
  i = (r * 0.59590296) - (g * 0.27405705) - (b *0.32184591)
  q = (r * 0.21133576) - (g * 0.52263517) + (b *0.31129940)
  return (y, i, q)

Response: Convert the color from RGB to YIQ.


Instruction:
Can you create a Python 3 function that
converts the color from YIQ coordinates to RGB.

Response:
def yiq_to_rgb(y, i=None, q=None):
  """Convert the color from YIQ coordinates to RGB.

  Parameters:
    :y:
      Tte Y component value [0...1]
    :i:
      The I component value [0...1]
    :q:
      The Q component value [0...1]

  Returns:
    The color as an (r, g, b) tuple in the range:
    r[0...1],
    g[0...1],
    b[0...1]

  >>> '({}, {}, {})'.format(*[round(v, 6) for v in yiq_to_rgb(0.592263, 0.458874, -0.0499818)])
  '(1.0, 0.5, 1e-06)'

  """
  if type(y) in [list,tuple]:
    y, i, q = y
  r = y + (i * 0.9562) + (q * 0.6210)
  g = y - (i * 0.2717) - (q * 0.6485)
  b = y - (i * 1.1053) + (q * 1.7020)
  return (r, g, b)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def rgb_to_yuv(r, g=None, b=None):
  if type(r) in [list,tuple]:
    r, g, b = r

  y =  (r * 0.29900) + (g * 0.58700) + (b * 0.11400)
  u = -(r * 0.14713) - (g * 0.28886) + (b * 0.43600)
  v =  (r * 0.61500) - (g * 0.51499) - (b * 0.10001)
  return (y, u, v)

Response: Convert the color from RGB coordinates to YUV.


Instruction:
Write a Python 3 script to
convert the color from YUV coordinates to RGB.

Response:
def yuv_to_rgb(y, u=None, v=None):
  """Convert the color from YUV coordinates to RGB.

  Parameters:
    :y:
      The Y component value [0...1]
    :u:
      The U component value [-0.436...0.436]
    :v:
      The V component value [-0.615...0.615]

  Returns:
    The color as an (r, g, b) tuple in the range:
    r[0...1],
    g[0...1],
    b[0...1]

  >>> '(%g, %g, %g)' % yuv_to_rgb(0.5925, -0.2916, 0.3575)
  '(0.999989, 0.500015, -6.3276e-05)'

  """
  if type(y) in [list,tuple]:
    y, u, v = y
  r = y + (v * 1.13983)
  g = y - (u * 0.39465) - (v * 0.58060)
  b = y + (u * 2.03211)
  return (r, g, b)


Instruction:
Explain what the following Python 3 code does
def rgb_to_xyz(r, g=None, b=None):
  if type(r) in [list,tuple]:
    r, g, b = r

  r, g, b = [((v <= 0.03928) and [v / 12.92] or [((v+0.055) / 1.055) **2.4])[0] for v in (r, g, b)]

  x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805)
  y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722)
  z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505)
  return (x, y, z)

Response: Convert the color from sRGB to XYZ.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def xyz_to_rgb(x, y=None, z=None):
  if type(x) in [list,tuple]:
    x, y, z = x
  r =  (x * 3.2406255) - (y * 1.5372080) - (z * 0.4986286)
  g = -(x * 0.9689307) + (y * 1.8757561) + (z * 0.0415175)
  b =  (x * 0.0557101) - (y * 0.2040211) + (z * 1.0569959)
  return tuple((((v <= _srgbGammaCorrInv) and [v * 12.92] or [(1.055 * (v ** (1/2.4))) - 0.055])[0] for v in (r, g, b)))

Response: Converts the color from CIE XYZ coordinates to sRGB.


Instruction:
How would you implement a function in Python 3 that
converts the color from CIE XYZ to lab.

Response:
def xyz_to_lab(x, y=None, z=None, wref=_DEFAULT_WREF):
  """Convert the color from CIE XYZ to CIE L*a*b*.

  Parameters:
    :x:
      The X component value [0...1]
    :y:
      The Y component value [0...1]
    :z:
      The Z component value [0...1]
    :wref:
      The whitepoint reference, default is 2° D65.

  Returns:
    The color as an (L, a, b) tuple in the range:
    L[0...100],
    a[-1...1],
    b[-1...1]

  >>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137)
  '(66.9518, 0.430841, 0.739692)'

  >>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137, WHITE_REFERENCE['std_D50'])
  '(66.9518, 0.41166, 0.67282)'

  """
  if type(x) in [list,tuple]:
    x, y, z = x
  # White point correction
  x /= wref[0]
  y /= wref[1]
  z /= wref[2]

  # Nonlinear distortion and linear transformation
  x, y, z = [((v > 0.008856) and [v**_oneThird] or [(7.787 * v) + _sixteenHundredsixteenth])[0] for v in (x, y, z)]

  # Vector scaling
  l = (116 * y) - 16
  a = 5.0 * (x - y)
  b = 2.0 * (y - z)

  return (l, a, b)


Instruction:
Here you have a function in Python 3, explain what it does
def lab_to_xyz(l, a=None, b=None, wref=_DEFAULT_WREF):
  if type(l) in [list,tuple]:
    l, a, b = l
  y = (l + 16) / 116
  x = (a / 5.0) + y
  z = y - (b / 2.0)
  return tuple((((v > 0.206893) and [v**3] or [(v - _sixteenHundredsixteenth) / 7.787])[0] * w for v, w in zip((x, y, z), wref)))

Response: Convert the color from CIE L a * b * to CIE 1931 XYZ.


Instruction:
Make a summary of the following Python 3 code
def cmyk_to_cmy(c, m=None, y=None, k=None):
  if type(c) in [list,tuple]:
    c, m, y, k = c
  mk = 1-k
  return ((c*mk + k), (m*mk + k), (y*mk + k))

Response: Convert the color from CMYK coordinates to CMY.


Instruction:
Can you create a Python 3 function that
converts the color from CMY coordinates to CMYK.

Response:
def cmy_to_cmyk(c, m=None, y=None):
  """Convert the color from CMY coordinates to CMYK.

  Parameters:
    :c:
      The Cyan component value [0...1]
    :m:
      The Magenta component value [0...1]
    :y:
      The Yellow component value [0...1]

  Returns:
    The color as an (c, m, y, k) tuple in the range:
    c[0...1],
    m[0...1],
    y[0...1],
    k[0...1]

  >>> '(%g, %g, %g, %g)' % cmy_to_cmyk(1, 0.66, 0.5)
  '(1, 0.32, 0, 0.5)'

  """
  if type(c) in [list,tuple]:
    c, m, y = c
  k = min(c, m, y)
  if k==1.0: return (0.0, 0.0, 0.0, 1.0)
  mk = 1.0-k
  return ((c-k) / mk, (m-k) / mk, (y-k) / mk, k)


Instruction:
Implement a function in Python 3 to
convert the color from RGB coordinates to CMY.

Response:
def rgb_to_cmy(r, g=None, b=None):
  """Convert the color from RGB coordinates to CMY.

  Parameters:
    :r:
      The Red component value [0...1]
    :g:
      The Green component value [0...1]
    :b:
      The Blue component value [0...1]

  Returns:
    The color as an (c, m, y) tuple in the range:
    c[0...1],
    m[0...1],
    y[0...1]

  >>> rgb_to_cmy(1, 0.5, 0)
  (0, 0.5, 1)

  """
  if type(r) in [list,tuple]:
    r, g, b = r
  return (1-r, 1-g, 1-b)


Instruction:
Make a summary of the following Python 3 code
def cmy_to_rgb(c, m=None, y=None):
  if type(c) in [list,tuple]:
    c, m, y = c
  return (1-c, 1-m, 1-y)

Response: Convert the color from CMY coordinates to RGB.


Instruction:
Make a summary of the following Python 3 code
def rgb_to_ints(r, g=None, b=None):
  if type(r) in [list,tuple]:
    r, g, b = r
  return tuple(int(round(v*255)) for v in (r, g, b))

Response: Convert the color in the standard [ 0... 255 ] range to ints in the [ 0... 255 ] range.