INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Greedy method to group ExperimentSettings in a given TomographyExperiment | def group_experiments_greedy(tomo_expt: TomographyExperiment):
"""
Greedy method to group ExperimentSettings in a given TomographyExperiment
:param tomo_expt: TomographyExperiment to group ExperimentSettings within
:return: TomographyExperiment, with grouped ExperimentSettings according to whether
... |
Group experiments that are diagonal in a shared tensor product basis ( TPB ) to minimize number of QPU runs. | def group_experiments(experiments: TomographyExperiment,
method: str = 'greedy') -> TomographyExperiment:
"""
Group experiments that are diagonal in a shared tensor product basis (TPB) to minimize number
of QPU runs.
Background
----------
Given some PauliTerm operator, th... |
Measure all the observables in a TomographyExperiment. | def measure_observables(qc: QuantumComputer, tomo_experiment: TomographyExperiment,
n_shots: int = 10000, progress_callback=None, active_reset=False,
symmetrize_readout: str = 'exhaustive',
calibrate_readout: str = 'plus-eig'):
"""
Measure ... |
: param ops_bool: tuple of booleans specifying the operation to be carried out on qubits: param qubits: list specifying the qubits to be carried operations on: return: Program with the operations specified in ops_bool on the qubits specified in qubits | def _ops_bool_to_prog(ops_bool: Tuple[bool], qubits: List[int]) -> Program:
"""
:param ops_bool: tuple of booleans specifying the operation to be carried out on `qubits`
:param qubits: list specifying the qubits to be carried operations on
:return: Program with the operations specified in `ops_bool` on ... |
: param bs_results: results from running qc. run: param qubit_index_map: dict mapping qubit to classical register index: param setting: ExperimentSetting: param n_shots: number of shots in the measurement process: param coeff: coefficient of the operator being estimated: return: tuple specifying ( mean variance ) | def _stats_from_measurements(bs_results: np.ndarray, qubit_index_map: Dict,
setting: ExperimentSetting, n_shots: int,
coeff: float = 1.0) -> Tuple[float]:
"""
:param bs_results: results from running `qc.run`
:param qubit_index_map: dict mapping qubit... |
r Given random variables A and B compute the variance on the ratio Y = A/ B. Denote the mean of the random variables as a = E [ A ] and b = E [ B ] while the variances are var_a = Var [ A ] and var_b = Var [ B ] and the covariance as Cov [ A B ]. The following expression approximates the variance of Y | def ratio_variance(a: Union[float, np.ndarray],
var_a: Union[float, np.ndarray],
b: Union[float, np.ndarray],
var_b: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
r"""
Given random variables 'A' and 'B', compute the variance on the ratio Y = A/B.... |
Perform exhaustive symmetrization | def _exhaustive_symmetrization(qc: QuantumComputer, qubits: List[int],
shots: int, prog: Program) -> (np.ndarray, Dict):
"""
Perform exhaustive symmetrization
:param qc: A QuantumComputer which can run quantum programs
:param qubits: qubits on which the symmetrization pro... |
Program required for calibration in a tomography - like experiment. | def _calibration_program(qc: QuantumComputer, tomo_experiment: TomographyExperiment,
setting: ExperimentSetting) -> Program:
"""
Program required for calibration in a tomography-like experiment.
:param tomo_experiment: A suite of tomographic observables
:param ExperimentSetting... |
Get the value of the environment variable or config file value. The environment variable takes precedence. | def _env_or_config_or_default(self, env=None, file=None, section=None, name=None, default=None):
"""
Get the value of the environment variable or config file value.
The environment variable takes precedence.
:param env: The environment variable name.
:param name: The config file... |
Cache threadpool since context is recreated for each request | def instance(cls, size):
"""
Cache threadpool since context is
recreated for each request
"""
if not getattr(cls, "_instance", None):
cls._instance = {}
if size not in cls._instance:
cls._instance[size] = ThreadPool(size)
return cls._instan... |
Runs thumbor server with the specified arguments. | def main(arguments=None):
'''Runs thumbor server with the specified arguments.'''
if arguments is None:
arguments = sys.argv[1:]
server_parameters = get_server_parameters(arguments)
config = get_config(server_parameters.config_path, server_parameters.use_environment)
configure_log(config, s... |
Retrieves mime metadata if available: return: | def mime(self):
'''
Retrieves mime metadata if available
:return:
'''
return self.metadata['ContentType'] if 'ContentType' in self.metadata else BaseEngine.get_mimetype(self.buffer) |
Cache statsd client so it doesn t do a DNS lookup over and over | def client(cls, config):
"""
Cache statsd client so it doesn't do a DNS lookup
over and over
"""
if not hasattr(cls, "_client"):
cls._client = statsd.StatsClient(config.STATSD_HOST, config.STATSD_PORT, config.STATSD_PREFIX)
return cls._client |
Pads the image with transparent pixels if necessary. | def handle_padding(self, padding):
'''Pads the image with transparent pixels if necessary.'''
left = padding[0]
top = padding[1]
right = padding[2]
bottom = padding[3]
offset_x = 0
offset_y = 0
new_width = self.engine.size[0]
new_height = self.eng... |
Returns the target dimensions and calculates them if necessary. The target dimensions are display independent.: return: Target dimensions as a tuple ( width height ): rtype: ( int int ) | def get_target_dimensions(self):
"""
Returns the target dimensions and calculates them if necessary.
The target dimensions are display independent.
:return: Target dimensions as a tuple (width, height)
:rtype: (int, int)
"""
if self.target_height is None:
... |
If ENGINE_THREADPOOL_SIZE > 0 this will schedule the image operations into a threadpool. If not it just executes them synchronously and calls self. done_callback when it s finished. | def do_image_operations(self):
"""
If ENGINE_THREADPOOL_SIZE > 0, this will schedule the image operations
into a threadpool. If not, it just executes them synchronously, and
calls self.done_callback when it's finished.
The actual work happens in self.img_operation_worker
... |
Returns the image orientation of the buffer image or None if it is undefined. Gets the original value from the Exif tag. If the buffer has been rotated then the value is adjusted to 1.: return: Orientation value ( 1 - 8 ): rtype: int or None | def get_orientation(self):
"""
Returns the image orientation of the buffer image or None
if it is undefined. Gets the original value from the Exif tag.
If the buffer has been rotated, then the value is adjusted to 1.
:return: Orientation value (1 - 8)
:rtype: int or None
... |
Rotates the image in the buffer so that it is oriented correctly. If override_exif is True ( default ) then the metadata orientation is adjusted as well.: param override_exif: If the metadata should be adjusted as well.: type override_exif: Boolean | def reorientate(self, override_exif=True):
"""
Rotates the image in the buffer so that it is oriented correctly.
If override_exif is True (default) then the metadata
orientation is adjusted as well.
:param override_exif: If the metadata should be adjusted as well.
:type o... |
This function is called after the PRE_LOAD filters have been applied. It applies the AFTER_LOAD filters on the result then crops the image. | def get_image(self):
"""
This function is called after the PRE_LOAD filters have been applied.
It applies the AFTER_LOAD filters on the result, then crops the image.
"""
try:
result = yield self._fetch(
self.context.request.image_url
)
... |
Converts a given url with the specified arguments. | def main(arguments=None):
'''Converts a given url with the specified arguments.'''
parsed_options, arguments = get_options(arguments)
image_url = arguments[0]
image_url = quote(image_url)
try:
config = Config.load(None)
except Exception:
config = None
if not parsed_option... |
checkImages ( images ) Check numpy images and correct intensity range etc. The same for all movie formats. | def checkImages(images):
""" checkImages(images)
Check numpy images and correct intensity range etc.
The same for all movie formats.
"""
# Init results
images2 = []
for im in images:
if PIL and isinstance(im, PIL.Image.Image):
# We assume PIL images are allright
... |
Integer to two bytes | def intToBin(i):
""" Integer to two bytes """
# devide in two parts (bytes)
i1 = i % 256
i2 = int(i / 256)
# make string (little endian)
return chr(i1) + chr(i2) |
writeGif ( filename images duration = 0. 1 repeat = True dither = False nq = 0 subRectangles = True dispose = None ) | def writeGif(
filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None):
""" writeGif(filename, images, duration=0.1, repeat=True, dither=False,
nq=0, subRectangles=True, dispose=None)
Write an animated gif from the specified images.
... |
readGif ( filename asNumpy = True ) | def readGif(filename, asNumpy=True):
""" readGif(filename, asNumpy=True)
Read images from an animated GIF file. Returns a list of numpy
arrays, or, if asNumpy is false, a list if PIL images.
"""
# Check PIL
if PIL is None:
raise RuntimeError("Need PIL to read animated gif files.")
... |
getheaderAnim ( im ) | def getheaderAnim(self, im):
""" getheaderAnim(im)
Get animation header. To replace PILs getheader()[0]
"""
bb = "GIF89a"
bb += intToBin(im.size[0])
bb += intToBin(im.size[1])
bb += "\x87\x00\x00"
return bb |
getImageDescriptor ( im xy = None ) | def getImageDescriptor(self, im, xy=None):
""" getImageDescriptor(im, xy=None)
Used for the local color table properties per image.
Otherwise global color table applies to all frames irrespective of
whether additional colors comes in play that require a redefined
palette. Still ... |
getAppExt ( loops = float ( inf )) | def getAppExt(self, loops=float('inf')):
""" getAppExt(loops=float('inf'))
Application extention. This part specifies the amount of loops.
If loops is 0 or inf, it goes on infinitely.
"""
if loops == 0 or loops == float('inf'):
loops = 2 ** 16 - 1
# bb ... |
getGraphicsControlExt ( duration = 0. 1 dispose = 2 ) | def getGraphicsControlExt(self, duration=0.1, dispose=2):
""" getGraphicsControlExt(duration=0.1, dispose=2)
Graphics Control Extension. A sort of header at the start of
each image. Specifies duration and transparancy.
Dispose
-------
* 0 - No disposal specified.
... |
handleSubRectangles ( images ) | def handleSubRectangles(self, images, subRectangles):
""" handleSubRectangles(images)
Handle the sub-rectangle stuff. If the rectangles are given by the
user, the values are checked. Otherwise the subrectangles are
calculated automatically.
"""
if isinstance(subRectang... |
getSubRectangles ( ims ) | def getSubRectangles(self, ims):
""" getSubRectangles(ims)
Calculate the minimal rectangles that need updating each frame.
Returns a two-element tuple containing the cropped images and a
list of x-y positions.
Calculating the subrectangles takes extra time, obviously. However,
... |
convertImagesToPIL ( images nq = 0 ) | def convertImagesToPIL(self, images, dither, nq=0):
""" convertImagesToPIL(images, nq=0)
Convert images to Paletted PIL images, which can then be
written to a single animaged GIF.
"""
# Convert to PIL images
images2 = []
for im in images:
if isinsta... |
writeGifToFile ( fp images durations loops xys disposes ) | def writeGifToFile(self, fp, images, durations, loops, xys, disposes):
""" writeGifToFile(fp, images, durations, loops, xys, disposes)
Given a set of images writes the bytes to the specified stream.
"""
# Obtain palette for all images and count each occurance
palettes, occur = ... |
Generate an application string based on some of the given information that can be pulled from the test object: app_env start_time. | def generate_application_string(cls, test):
""" Generate an application string based on some of the given information
that can be pulled from the test object: app_env, start_time. """
app_env = 'test'
if hasattr(test, 'env'):
app_env = test.env
elif hasattr(test,... |
This method removes the outer parentheses for xpath grouping. The xpath converter will break otherwise. Example: (// button [ | def _filter_xpath_grouping(xpath):
"""
This method removes the outer parentheses for xpath grouping.
The xpath converter will break otherwise.
Example:
"(//button[@type='submit'])[1]" becomes "//button[@type='submit'][1]"
"""
# First remove the first open parentheses
xpath = xpath[1:]
... |
Implementation of https:// stackoverflow. com/ a/ 35293284 for https:// stackoverflow. com/ questions/ 12848327/ ( Run Selenium on a proxy server that requires authentication. ) Solution involves creating & adding a Chrome extension on the fly. * CHROME - ONLY for now! * | def create_proxy_zip(proxy_string, proxy_user, proxy_pass):
""" Implementation of https://stackoverflow.com/a/35293284 for
https://stackoverflow.com/questions/12848327/
(Run Selenium on a proxy server that requires authentication.)
Solution involves creating & adding a Chrome extension on th... |
Remove Chrome extension zip file used for proxy server authentication. Used in the implementation of https:// stackoverflow. com/ a/ 35293284 for https:// stackoverflow. com/ questions/ 12848327/ | def remove_proxy_zip_if_present():
""" Remove Chrome extension zip file used for proxy server authentication.
Used in the implementation of https://stackoverflow.com/a/35293284
for https://stackoverflow.com/questions/12848327/
"""
try:
if os.path.exists(PROXY_ZIP_PATH):
o... |
This method clicks on a list of elements in succession. spacing is the amount of time to wait between clicks. ( sec ) | def click_chain(self, selectors_list, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT, spacing=0):
""" This method clicks on a list of elements in succession.
'spacing' is the amount of time to wait between clicks. (sec) """
if self.timeout_multiplier and timeout == se... |
Returns True if the link text appears in the HTML of the page. The element doesn t need to be visible such as elements hidden inside a dropdown selection. | def is_link_text_present(self, link_text):
""" Returns True if the link text appears in the HTML of the page.
The element doesn't need to be visible,
such as elements hidden inside a dropdown selection. """
soup = self.get_beautiful_soup()
html_links = soup.find_all('a')
... |
Finds a link by link text and then returns the attribute s value. If the link text or attribute cannot be found an exception will get raised if hard_fail is True ( otherwise None is returned ). | def get_link_attribute(self, link_text, attribute, hard_fail=True):
""" Finds a link by link text and then returns the attribute's value.
If the link text or attribute cannot be found, an exception will
get raised if hard_fail is True (otherwise None is returned). """
soup = self... |
This method clicks link text on a page | def click_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT):
""" This method clicks link text on a page """
# If using phantomjs, might need to extract and open the link directly
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeo... |
Same as self. click_link_text () | def click_link(self, link_text, timeout=settings.SMALL_TIMEOUT):
""" Same as self.click_link_text() """
self.click_link_text(link_text, timeout=timeout) |
This method clicks the partial link text on a page. | def click_partial_link_text(self, partial_link_text,
timeout=settings.SMALL_TIMEOUT):
""" This method clicks the partial link text on a page. """
# If using phantomjs, might need to extract and open the link directly
if self.timeout_multiplier and timeout == setti... |
This method uses JavaScript to get the value of an attribute. | def get_attribute(self, selector, attribute, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" This method uses JavaScript to get the value of an attribute. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(tim... |
This method uses JavaScript to set/ update an attribute. | def set_attribute(self, selector, attribute, value, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" This method uses JavaScript to set/update an attribute. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(ti... |
Returns the property value of a page element s computed style. Example: opacity = self. get_property_value ( html body a opacity ) self. assertTrue ( float ( opacity ) > 0 Element not visible! ) | def get_property_value(self, selector, property, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Returns the property value of a page element's computed style.
Example:
opacity = self.get_property_value("html body a", "opacity")
sel... |
Extracts the URL from an image element on the page. | def get_image_url(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Extracts the URL from an image element on the page. """
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
return ... |
The more - reliable version of driver. send_keys () Similar to update_text () but won t clear the text field first. | def add_text(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" The more-reliable version of driver.send_keys()
Similar to update_text(), but won't clear the text field first. """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEO... |
Same as add_text () - > more reliable but less name confusion. | def send_keys(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" Same as add_text() -> more reliable, but less name confusion. """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
... |
The shorter version of update_text_value () which clears existing text and adds new text into the text field. We want to keep the old version for backward compatibility. | def update_text(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT, retry=False):
""" The shorter version of update_text_value(), which
clears existing text and adds new text into the text field.
We want to keep the old version for backward ... |
Returns a list of matching WebElements. If limit is set and > 0 will only return that many elements. | def find_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
""" Returns a list of matching WebElements.
If "limit" is set and > 0, will only return that many elements. """
self.wait_for_ready_state_complete()
if page_utils.is_xpath_selector(selector):
by = By.XPATH
... |
Returns a list of matching WebElements that are visible. If limit is set and > 0 will only return that many elements. | def find_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
""" Returns a list of matching WebElements that are visible.
If "limit" is set and > 0, will only return that many elements. """
self.wait_for_ready_state_complete()
if page_utils.is_xpath_selector(selector):
... |
Finds all matching page elements and clicks visible ones in order. If a click reloads or opens a new page the clicking will stop. Works best for actions such as clicking all checkboxes on a page. Example: self. click_visible_elements ( input [ type = checkbox ] ) If limit is set and > 0 will only click that many elemen... | def click_visible_elements(self, selector, by=By.CSS_SELECTOR, limit=0):
""" Finds all matching page elements and clicks visible ones in order.
If a click reloads or opens a new page, the clicking will stop.
Works best for actions such as clicking all checkboxes on a page.
Ex... |
Returns True if the selector s element is located in an iframe. Otherwise returns False. | def is_element_in_an_iframe(self, selector, by=By.CSS_SELECTOR):
""" Returns True if the selector's element is located in an iframe.
Otherwise returns False. """
selector, by = self.__recalculate_selector(selector, by)
if self.is_element_present(selector, by=by):
return F... |
Creates a tour for a website. By default the Shepherd JavaScript Library is used with the Shepherd Light/ Arrows theme. | def create_tour(self, name=None, theme=None):
""" Creates a tour for a website. By default, the Shepherd JavaScript
Library is used with the Shepherd "Light" / "Arrows" theme.
@Params
name - If creating multiple tours at the same time,
use this to select th... |
Creates a Shepherd JS website tour. | def create_shepherd_tour(self, name=None, theme=None):
""" Creates a Shepherd JS website tour.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
theme - Sets the default theme for the tour.
... |
Creates a Bootstrap tour for a website. | def create_bootstrap_tour(self, name=None):
""" Creates a Bootstrap tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
... |
Creates an Hopscotch tour for a website. | def create_hopscotch_tour(self, name=None):
""" Creates an Hopscotch tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
... |
Creates an IntroJS tour for a website. | def create_introjs_tour(self, name=None):
""" Creates an IntroJS tour for a website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
"""
if not name:
name = "default"
... |
Allows the user to add tour steps for a website. | def add_tour_step(self, message, selector=None, name=None,
title=None, theme=None, alignment=None, duration=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element t... |
Allows the user to add tour steps for a website. | def __add_shepherd_tour_step(self, message, selector=None, name=None,
title=None, theme=None, alignment=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the El... |
Allows the user to add tour steps for a website. | def __add_bootstrap_tour_step(self, message, selector=None, name=None,
title=None, alignment=None, duration=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of t... |
Allows the user to add tour steps for a website. | def __add_hopscotch_tour_step(self, message, selector=None, name=None,
title=None, alignment=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to a... |
Allows the user to add tour steps for a website. | def __add_introjs_tour_step(self, message, selector=None, name=None,
title=None, alignment=None):
""" Allows the user to add tour steps for a website.
@Params
message - The message to display.
selector - The CSS Selector of the Element to attac... |
Plays a tour on the current website. | def play_tour(self, name=None, interval=0):
""" Plays a tour on the current website.
@Params
name - If creating multiple tours at the same time,
use this to select the tour you wish to add steps to.
interval - The delay time between autoplaying tour steps.
... |
Exports a tour as a JS file. You can call self. export_tour () anywhere where you would normally use self. play_tour () to play a tour. It will include necessary resources as well such as jQuery. You ll be able to copy the tour directly into the Console of any web browser to play the tour outside of SeleniumBase runs. | def export_tour(self, name=None, filename="my_tour.js", url=None):
""" Exports a tour as a JS file.
You can call self.export_tour() anywhere where you would
normally use self.play_tour() to play a tour.
It will include necessary resources as well, such as jQuery.
... |
Sets a theme for posting messages. Themes: [ flat future block air ice ] Locations: [ top_left top_center top_right bottom_left bottom_center bottom_right ] max_messages is the limit of concurrent messages to display. | def set_messenger_theme(self, theme="default", location="default",
max_messages="default"):
""" Sets a theme for posting messages.
Themes: ["flat", "future", "block", "air", "ice"]
Locations: ["top_left", "top_center", "top_right",
"bot... |
Post a message on the screen with Messenger. Arguments: message: The message to display. duration: The time until the message vanishes. ( Default: 2. 55s ) pause: If True the program waits until the message completes. style: info success or error. | def post_message(self, message, duration=None, pause=True, style="info"):
""" Post a message on the screen with Messenger.
Arguments:
message: The message to display.
duration: The time until the message vanishes. (Default: 2.55s)
pause: If True, the p... |
Updates the Z - index of a page element to bring it into view. Useful when getting a WebDriverException such as the one below: { Element is not clickable at point ( # # ). Other element would receive the click:... } | def bring_to_front(self, selector, by=By.CSS_SELECTOR):
""" Updates the Z-index of a page element to bring it into view.
Useful when getting a WebDriverException, such as the one below:
{ Element is not clickable at point (#, #).
Other element would receive the clic... |
This method uses fancy JavaScript to highlight an element. Used during demo_mode. | def highlight(self, selector, by=By.CSS_SELECTOR,
loops=settings.HIGHLIGHTS, scroll=True):
""" This method uses fancy JavaScript to highlight an element.
Used during demo_mode.
@Params
selector - the selector of the element to find
by - the type ... |
Fast scroll to destination | def scroll_to(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
''' Fast scroll to destination '''
if self.demo_mode:
self.slow_scroll_to(selector, by=by, timeout=timeout)
return
if self.timeout_multiplier and timeout == settings.SMALL... |
Slow motion scroll to destination | def slow_scroll_to(self, selector, by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
''' Slow motion scroll to destination '''
if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
element = self.wait_for... |
Clicks an element using pure JS. Does not use jQuery. | def js_click(self, selector, by=By.CSS_SELECTOR):
""" Clicks an element using pure JS. Does not use jQuery. """
selector, by = self.__recalculate_selector(selector, by)
if by == By.LINK_TEXT:
message = (
"Pure JavaScript doesn't support clicking by Link Text. "
... |
Clicks an element using jQuery. Different from using pure JS. | def jquery_click(self, selector, by=By.CSS_SELECTOR):
""" Clicks an element using jQuery. Different from using pure JS. """
selector, by = self.__recalculate_selector(selector, by)
self.wait_for_element_present(
selector, by=by, timeout=settings.SMALL_TIMEOUT)
if self.is_elem... |
Alternative to self. driver. find_element_by_ * ( SELECTOR ). submit () | def submit(self, selector, by=By.CSS_SELECTOR):
""" Alternative to self.driver.find_element_by_*(SELECTOR).submit() """
if page_utils.is_xpath_selector(selector):
by = By.XPATH
element = self.wait_for_element_visible(
selector, by=by, timeout=settings.SMALL_TIMEOUT)
... |
Hide the first element on the page that matches the selector. | def hide_element(self, selector, by=By.CSS_SELECTOR):
""" Hide the first element on the page that matches the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_onl... |
Hide all elements on the page that match the selector. | def hide_elements(self, selector, by=By.CSS_SELECTOR):
""" Hide all elements on the page that match the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
hide_script = """jQuery('%s').hide()""" % selector
... |
Show the first element on the page that matches the selector. | def show_element(self, selector, by=By.CSS_SELECTOR):
""" Show the first element on the page that matches the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element_onl... |
Show all elements on the page that match the selector. | def show_elements(self, selector, by=By.CSS_SELECTOR):
""" Show all elements on the page that match the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
show_script = """jQuery('%s').show(0)""" % selector
... |
Remove the first element on the page that matches the selector. | def remove_element(self, selector, by=By.CSS_SELECTOR):
""" Remove the first element on the page that matches the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
selector = self.__make_css_match_first_element... |
Remove all elements on the page that match the selector. | def remove_elements(self, selector, by=By.CSS_SELECTOR):
""" Remove all elements on the page that match the selector. """
selector, by = self.__recalculate_selector(selector, by)
selector = self.convert_to_css_selector(selector, by=by)
remove_script = """jQuery('%s').remove()""" % select... |
BeautifulSoup is a toolkit for dissecting an HTML document and extracting what you need. It s great for screen - scraping! | def get_beautiful_soup(self, source=None):
""" BeautifulSoup is a toolkit for dissecting an HTML document
and extracting what you need. It's great for screen-scraping! """
from bs4 import BeautifulSoup
if not source:
self.wait_for_ready_state_complete()
source... |
Get all unique links in the html of the page source. Page links include those obtained from: a - > href img - > src link - > href and script - > src. | def get_unique_links(self):
""" Get all unique links in the html of the page source.
Page links include those obtained from:
"a"->"href", "img"->"src", "link"->"href", and "script"->"src". """
page_url = self.get_current_url()
soup = self.get_beautiful_soup(self.get_page_... |
Get the status code of a link. If the timeout is exceeded will return a 404. For a list of available status codes see: https:// en. wikipedia. org/ wiki/ List_of_HTTP_status_codes | def get_link_status_code(self, link, allow_redirects=False, timeout=5):
""" Get the status code of a link.
If the timeout is exceeded, will return a 404.
For a list of available status codes, see:
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes """
status_code... |
Assert no 404 errors from page links obtained from: a - > href img - > src link - > href and script - > src. | def assert_no_404_errors(self, multithreaded=True):
""" Assert no 404 errors from page links obtained from:
"a"->"href", "img"->"src", "link"->"href", and "script"->"src". """
links = self.get_unique_links()
if multithreaded:
from multiprocessing.dummy import Pool as Thre... |
Finds all unique links in the html of the page source and then prints out those links with their status codes. Format: [ link - > status_code ] ( per line ) Page links include those obtained from: a - > href img - > src link - > href and script - > src. | def print_unique_links_with_status_codes(self):
""" Finds all unique links in the html of the page source
and then prints out those links with their status codes.
Format: ["link" -> "status_code"] (per line)
Page links include those obtained from:
"a"->"href",... |
When executing a script that contains a jQuery command it s important that the jQuery library has been loaded first. This method will load jQuery if it wasn t already loaded. | def safe_execute_script(self, script):
""" When executing a script that contains a jQuery command,
it's important that the jQuery library has been loaded first.
This method will load jQuery if it wasn't already loaded. """
try:
self.execute_script(script)
exce... |
Creates a folder of the given name if it doesn t already exist. | def create_folder(self, folder):
""" Creates a folder of the given name if it doesn't already exist. """
if folder.endswith("/"):
folder = folder[:-1]
if len(folder) < 1:
raise Exception("Minimum folder name length = 1.")
if not os.path.exists(folder):
... |
Take a screenshot of an element and save it as an image file. If no folder is specified will save it to the current folder. | def save_element_as_image_file(self, selector, file_name, folder=None):
""" Take a screenshot of an element and save it as an image file.
If no folder is specified, will save it to the current folder. """
element = self.find_element(selector)
element_png = element.screenshot_as_png
... |
Downloads the file from the url to the destination folder. If no destination folder is specified the default one is used. ( The default downloads folder =./ downloaded_files ) | def download_file(self, file_url, destination_folder=None):
""" Downloads the file from the url to the destination folder.
If no destination folder is specified, the default one is used.
(The default downloads folder = "./downloaded_files") """
if not destination_folder:
... |
Similar to self. download_file () except that you get to rename the file being downloaded to whatever you want. | def save_file_as(self, file_url, new_file_name, destination_folder=None):
""" Similar to self.download_file(), except that you get to rename the
file being downloaded to whatever you want. """
if not destination_folder:
destination_folder = constants.Files.DOWNLOADS_FOLDER
... |
Saves the data specified to a file of the name specified. If no destination folder is specified the default one is used. ( The default downloads folder =./ downloaded_files ) | def save_data_as(self, data, file_name, destination_folder=None):
""" Saves the data specified to a file of the name specified.
If no destination folder is specified, the default one is used.
(The default downloads folder = "./downloaded_files") """
if not destination_folder:
... |
Asserts that there are no JavaScript SEVERE - level page errors. Works ONLY for Chrome ( non - headless ) and Chrome - based browsers. Does NOT work on Firefox Edge IE and some other browsers: * See https:// github. com/ SeleniumHQ/ selenium/ issues/ 1161 Based on the following Stack Overflow solution: * https:// stack... | def assert_no_js_errors(self):
""" Asserts that there are no JavaScript "SEVERE"-level page errors.
Works ONLY for Chrome (non-headless) and Chrome-based browsers.
Does NOT work on Firefox, Edge, IE, and some other browsers:
* See https://github.com/SeleniumHQ/selenium/is... |
Returns a time - based one - time password based on the Google Authenticator password algorithm. Works with Authy. If totp_key is not specified defaults to using the one provided in seleniumbase/ config/ settings. py Google Auth passwords expire and change at 30 - second intervals. If the fetched password expires in th... | def get_google_auth_password(self, totp_key=None):
""" Returns a time-based one-time password based on the
Google Authenticator password algorithm. Works with Authy.
If "totp_key" is not specified, defaults to using the one
provided in seleniumbase/config/settings.py
... |
This method converts a selector to a CSS_SELECTOR. jQuery commands require a CSS_SELECTOR for finding elements. This method should only be used for jQuery/ JavaScript actions. Pure JavaScript doesn t support using a: contains ( LINK_TEXT ). | def convert_to_css_selector(self, selector, by):
""" This method converts a selector to a CSS_SELECTOR.
jQuery commands require a CSS_SELECTOR for finding elements.
This method should only be used for jQuery/JavaScript actions.
Pure JavaScript doesn't support using a:contains... |
This method uses JavaScript to update a text field. | def set_value(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" This method uses JavaScript to update a text field. """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
if p... |
Same as self. set_value () | def js_update_text(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" Same as self.set_value() """
if self.timeout_multiplier and timeout == settings.LARGE_TIMEOUT:
timeout = self.__get_new_timeout(timeout)
self.set_value(
... |
This method uses jQuery to update a text field. If the new_value string ends with the newline character WebDriver will finish the call which simulates pressing { Enter/ Return } after the text is entered. | def jquery_update_text_value(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" This method uses jQuery to update a text field.
If the new_value string ends with the newline character,
WebDriver will finish the call, which... |
The shorter version of self. jquery_update_text_value () ( The longer version remains for backwards compatibility. ) | def jquery_update_text(self, selector, new_value, by=By.CSS_SELECTOR,
timeout=settings.LARGE_TIMEOUT):
""" The shorter version of self.jquery_update_text_value()
(The longer version remains for backwards compatibility.) """
if self.timeout_multiplier and timeout ==... |
Selects an HTML <select > option by specification. Option specifications are by text index or value. Defaults to text if option_by is unspecified or unknown. | def __select_option(self, dropdown_selector, option,
dropdown_by=By.CSS_SELECTOR, option_by="text",
timeout=settings.SMALL_TIMEOUT):
""" Selects an HTML <select> option by specification.
Option specifications are by "text", "index", or "value".
... |
Selects an HTML <select > option by option text. | def select_option_by_text(self, dropdown_selector, option,
dropdown_by=By.CSS_SELECTOR,
timeout=settings.SMALL_TIMEOUT):
""" Selects an HTML <select> option by option text.
@Params
dropdown_selector - the <select> selector
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.