text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def orientation(self, value): """ Sets the current orientation of the device :Args: - value: orientation to set it to. :Usage: :: driver.orientation = 'landscape...
allowed_values = ['LANDSCAPE', 'PORTRAIT'] if value.upper() in allowed_values: self.execute(Command.SET_SCREEN_ORIENTATION, {'orientation': value}) else: raise WebDriverException("You can only set the orientation to 'LANDSCAPE' and 'PORTRAIT'")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def until(self, method, message=''): """Calls the method provided with the driver as an argument until the \ return value does not evaluate to ``False``. :param ...
screen = None stacktrace = None end_time = time.time() + self._timeout while True: try: value = method(self._driver) if value: return value except self._ignored_exceptions as exc: screen = getat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def until_not(self, method, message=''): """Calls the method provided with the driver as an argument until the \ return value evaluates to ``False``. :param meth...
end_time = time.time() + self._timeout while True: try: value = method(self._driver) if not value: return value except self._ignored_exceptions: return True time.sleep(self._poll) if time...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quit(self): """Quits the driver and close every associated window."""
try: RemoteWebDriver.quit(self) except Exception: # We don't care about the message because something probably has gone wrong pass if self.w3c: self.service.stop() else: self.binary.kill() if self.profile is not None:...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def context(self, context): """Sets the context that Selenium commands are running in using a `with` statement. The state of the context on the server is saved b...
initial_context = self.execute('GET_CONTEXT').pop('value') self.set_context(context) try: yield finally: self.set_context(initial_context)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_addon(self, path, temporary=None): """ Installs Firefox addon. Returns identifier of installed addon. This identifier can later be used to uninstall ...
payload = {"path": path} if temporary is not None: payload["temporary"] = temporary return self.execute("INSTALL_ADDON", payload)["value"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def binary(self, new_binary): """Sets location of the browser binary, either by string or ``FirefoxBinary`` instance. """
if not isinstance(new_binary, FirefoxBinary): new_binary = FirefoxBinary(new_binary) self._binary = new_binary
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def profile(self, new_profile): """Sets location of the browser profile to use, either by string or ``FirefoxProfile``. """
if not isinstance(new_profile, FirefoxProfile): new_profile = FirefoxProfile(new_profile) self._profile = new_profile
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_network_connection(self, network): """ Set the network connection for the remote device. Example of setting airplane mode:: driver.mobile.set_network_con...
mode = network.mask if isinstance(network, self.ConnectionType) else network return self.ConnectionType(self._driver.execute( Command.SET_NETWORK_CONNECTION, { 'name': 'network_connection', 'parameters': {'type': mode}})['value'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unzip_to_temp_dir(zip_file_name): """Unzip zipfile to a temporary directory. The directory of the unzipped files is returned if success, otherwise None is re...
if not zip_file_name or not os.path.exists(zip_file_name): return None zf = zipfile.ZipFile(zip_file_name) if zf.testzip() is not None: return None # Unzip the files into a temporary directory LOGGER.info("Extracting zipped file: %s" % zip_file_name) tempdir = tempfile.mkdtem...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tap(self, on_element): """ Taps on a given element. :Args: - on_element: The element to tap. """
self._actions.append(lambda: self._driver.execute( Command.SINGLE_TAP, {'element': on_element.id})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def double_tap(self, on_element): """ Double taps on a given element. :Args: - on_element: The element to tap. """
self._actions.append(lambda: self._driver.execute( Command.DOUBLE_TAP, {'element': on_element.id})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def tap_and_hold(self, xcoord, ycoord): """ Touch down at given coordinates. :Args: - xcoord: X Coordinate to touch down. - ycoord: Y Coordinate to touch down. "...
self._actions.append(lambda: self._driver.execute( Command.TOUCH_DOWN, { 'x': int(xcoord), 'y': int(ycoord)})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move(self, xcoord, ycoord): """ Move held tap to specified location. :Args: - xcoord: X Coordinate to move. - ycoord: Y Coordinate to move. """
self._actions.append(lambda: self._driver.execute( Command.TOUCH_MOVE, { 'x': int(xcoord), 'y': int(ycoord)})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release(self, xcoord, ycoord): """ Release previously issued tap 'and hold' command at specified location. :Args: - xcoord: X Coordinate to release. - ycoord...
self._actions.append(lambda: self._driver.execute( Command.TOUCH_UP, { 'x': int(xcoord), 'y': int(ycoord)})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scroll(self, xoffset, yoffset): """ Touch and scroll, moving by xoffset and yoffset. :Args: - xoffset: X offset to scroll to. - yoffset: Y offset to scroll t...
self._actions.append(lambda: self._driver.execute( Command.TOUCH_SCROLL, { 'xoffset': int(xoffset), 'yoffset': int(yoffset)})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scroll_from_element(self, on_element, xoffset, yoffset): """ Touch and scroll starting at on_element, moving by xoffset and yoffset. :Args: - on_element: The...
self._actions.append(lambda: self._driver.execute( Command.TOUCH_SCROLL, { 'element': on_element.id, 'xoffset': int(xoffset), 'yoffset': int(yoffset)})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def long_press(self, on_element): """ Long press on an element. :Args: - on_element: The element to long press. """
self._actions.append(lambda: self._driver.execute( Command.LONG_PRESS, {'element': on_element.id})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flick(self, xspeed, yspeed): """ Flicks, starting anywhere on the screen. :Args: - xspeed: The X speed in pixels per second. - yspeed: The Y speed in pixels ...
self._actions.append(lambda: self._driver.execute( Command.FLICK, { 'xspeed': int(xspeed), 'yspeed': int(yspeed)})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flick_element(self, on_element, xoffset, yoffset, speed): """ Flick starting at on_element, and moving by the xoffset and yoffset with specified speed. :Args...
self._actions.append(lambda: self._driver.execute( Command.FLICK, { 'element': on_element.id, 'xoffset': int(xoffset), 'yoffset': int(yoffset), 'speed': int(speed)})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def active_element(self): """ Returns the element with focus, or BODY if nothing has focus. :Usage: :: element = driver.switch_to.active_element """
if self._driver.w3c: return self._driver.execute(Command.W3C_GET_ACTIVE_ELEMENT)['value'] else: return self._driver.execute(Command.GET_ACTIVE_ELEMENT)['value']
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def frame(self, frame_reference): """ Switches focus to the specified frame, by index, name, or webelement. :Args: - frame_reference: The name of the window to s...
if isinstance(frame_reference, basestring) and self._driver.w3c: try: frame_reference = self._driver.find_element(By.ID, frame_reference) except NoSuchElementException: try: frame_reference = self._driver.find_element(By.NAME, frame_re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def new_window(self, type_hint=None): """Switches to a new top-level browsing context. The type hint can be one of "tab" or "window". If not specified the browse...
value = self._driver.execute(Command.NEW_WINDOW, {'type': type_hint})['value'] self._w3c_window(value['handle'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def window(self, window_name): """ Switches focus to the specified window. :Args: - window_name: The name or window handle of the window to switch to. :Usage: ::...
if self._driver.w3c: self._w3c_window(window_name) return data = {'name': window_name} self._driver.execute(Command.SWITCH_TO_WINDOW, data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def perform(self): """ Performs all stored actions. """
if self._driver.w3c: self.w3c_actions.perform() else: for action in self._actions: action()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset_actions(self): """ Clears actions that are already stored locally and on the remote end """
if self._driver.w3c: self.w3c_actions.clear_actions() self._actions = []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def click_and_hold(self, on_element=None): """ Holds down the left mouse button on an element. :Args: - on_element: The element to mouse down. If None, clicks on...
if on_element: self.move_to_element(on_element) if self._driver.w3c: self.w3c_actions.pointer_action.click_and_hold() self.w3c_actions.key_action.pause() else: self._actions.append(lambda: self._driver.execute( Com...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def double_click(self, on_element=None): """ Double-clicks an element. :Args: - on_element: The element to double-click. If None, clicks on current mouse positio...
if on_element: self.move_to_element(on_element) if self._driver.w3c: self.w3c_actions.pointer_action.double_click() for _ in range(4): self.w3c_actions.key_action.pause() else: self._actions.append(lambda: self._driver.execute( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drag_and_drop(self, source, target): """ Holds down the left mouse button on the source element, then moves to the target element and releases the mouse butt...
self.click_and_hold(source) self.release(target) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def drag_and_drop_by_offset(self, source, xoffset, yoffset): """ Holds down the left mouse button on the source element, then moves to the target offset and rele...
self.click_and_hold(source) self.move_by_offset(xoffset, yoffset) self.release() return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_by_offset(self, xoffset, yoffset): """ Moving the mouse to an offset from current mouse position. :Args: - xoffset: X offset to move to, as a positive o...
if self._driver.w3c: self.w3c_actions.pointer_action.move_by(xoffset, yoffset) self.w3c_actions.key_action.pause() else: self._actions.append(lambda: self._driver.execute( Command.MOVE_TO, { 'xoffset': int(xoffset), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_to_element(self, to_element): """ Moving the mouse to the middle of an element. :Args: - to_element: The WebElement to move to. """
if self._driver.w3c: self.w3c_actions.pointer_action.move_to(to_element) self.w3c_actions.key_action.pause() else: self._actions.append(lambda: self._driver.execute( Command.MOVE_TO, {'element': to_element.id})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_to_element_with_offset(self, to_element, xoffset, yoffset): """ Move the mouse by an offset of the specified element. Offsets are relative to the top-le...
if self._driver.w3c: self.w3c_actions.pointer_action.move_to(to_element, xoffset, yoffset) self.w3c_actions.key_action.pause() else: self._actions.append( lambda: self._driver.execute(Command.MOVE_TO, { 'element': to_element.id, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pause(self, seconds): """ Pause all inputs for the specified duration in seconds """
if self._driver.w3c: self.w3c_actions.pointer_action.pause(seconds) self.w3c_actions.key_action.pause(seconds) else: self._actions.append(lambda: time.sleep(seconds)) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def release(self, on_element=None): """ Releasing a held mouse button on an element. :Args: - on_element: The element to mouse up. If None, releases on current m...
if on_element: self.move_to_element(on_element) if self._driver.w3c: self.w3c_actions.pointer_action.release() self.w3c_actions.key_action.pause() else: self._actions.append(lambda: self._driver.execute(Command.MOUSE_UP, {})) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_keys(self, *keys_to_send): """ Sends keys to current focused element. :Args: - keys_to_send: The keys to send. Modifier keys constants can be found in t...
typing = keys_to_typing(keys_to_send) if self._driver.w3c: for key in typing: self.key_down(key) self.key_up(key) else: self._actions.append(lambda: self._driver.execute( Command.SEND_KEYS_TO_ACTIVE_ELEMENT, {'value': typin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_keys_to_element(self, element, *keys_to_send): """ Sends keys to an element. :Args: - element: The element to send keys. - keys_to_send: The keys to sen...
self.click(element) self.send_keys(*keys_to_send) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def browser_attach_timeout(self, value): """ Sets the options Browser Attach Timeout :Args: - value: Timeout in milliseconds """
if not isinstance(value, int): raise ValueError('Browser Attach Timeout must be an integer.') self._options[self.BROWSER_ATTACH_TIMEOUT] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def element_scroll_behavior(self, value): """ Sets the options Element Scroll Behavior :Args: - value: 0 - Top, 1 - Bottom """
if value not in [ElementScrollBehavior.TOP, ElementScrollBehavior.BOTTOM]: raise ValueError('Element Scroll Behavior out of range.') self._options[self.ELEMENT_SCROLL_BEHAVIOR] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def file_upload_dialog_timeout(self, value): """ Sets the options File Upload Dialog Timeout value :Args: - value: Timeout in milliseconds """
if not isinstance(value, int): raise ValueError('File Upload Dialog Timeout must be an integer.') self._options[self.FILE_UPLOAD_DIALOG_TIMEOUT] = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_capabilities(self): """Marshals the IE options to the correct object."""
caps = self._caps opts = self._options.copy() if len(self._arguments) > 0: opts[self.SWITCHES] = ' '.join(self._arguments) if len(self._additional) > 0: opts.update(self._additional) if len(opts) > 0: caps[Options.KEY] = opts return...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_extension(self, extension): """ Adds the path to the extension to a list that will be used to extract it to the ChromeDriver :Args: - extension: path to ...
if extension: extension_to_add = os.path.abspath(os.path.expanduser(extension)) if os.path.exists(extension_to_add): self._extension_files.append(extension_to_add) else: raise IOError("Path to the extension doesn't exist") else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_capabilities(self): """ Creates a capabilities with all the options that have been set :Returns: A dictionary with everything """
caps = self._caps chrome_options = self.experimental_options.copy() chrome_options["extensions"] = self.extensions if self.binary_location: chrome_options["binary"] = self.binary_location chrome_options["args"] = self.arguments if self.debugger_address: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_element(driver, by): """Looks up an element. Logs and re-raises ``WebDriverException`` if thrown."""
try: return driver.find_element(*by) except NoSuchElementException as e: raise e except WebDriverException as e: raise e
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text(self): """ Gets the text of the Alert. """
if self.driver.w3c: return self.driver.execute(Command.W3C_GET_ALERT_TEXT)["value"] else: return self.driver.execute(Command.GET_ALERT_TEXT)["value"]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dismiss(self): """ Dismisses the alert available. """
if self.driver.w3c: self.driver.execute(Command.W3C_DISMISS_ALERT) else: self.driver.execute(Command.DISMISS_ALERT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def accept(self): """ Accepts the alert available. Usage:: Alert(driver).accept() # Confirm a alert dialog. """
if self.driver.w3c: self.driver.execute(Command.W3C_ACCEPT_ALERT) else: self.driver.execute(Command.ACCEPT_ALERT)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_keys(self, keysToSend): """ Send Keys to the Alert. :Args: - keysToSend: The text to be sent to Alert. """
if self.driver.w3c: self.driver.execute(Command.W3C_SET_ALERT_VALUE, {'value': keys_to_typing(keysToSend), 'text': keysToSend}) else: self.driver.execute(Command.SET_ALERT_VALUE, {'text': keysToSend})
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def port(self, port): """ Sets the port that WebDriver will be running on """
if not isinstance(port, int): raise WebDriverException("Port needs to be an integer") try: port = int(port) if port < 1 or port > 65535: raise WebDriverException("Port number must be in the range 1..65535") except (ValueError, TypeError): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encoded(self): """ A zipped, base64 encoded string of profile directory for use with remote WebDriver JSON wire protocol """
self.update_preferences() fp = BytesIO() zipped = zipfile.ZipFile(fp, 'w', zipfile.ZIP_DEFLATED) path_root = len(self.path) + 1 # account for trailing slash for base, dirs, files in os.walk(self.path): for fyle in files: filename = os.path.join(base,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_user_prefs(self, user_prefs): """ writes the current user prefs dictionary to disk """
with open(self.userPrefs, "w") as f: for key, value in user_prefs.items(): f.write('user_pref("%s", %s);\n' % (key, json.dumps(value)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def submit(self): """Submits a form."""
if self._w3c: form = self.find_element(By.XPATH, "./ancestor-or-self::form") self._parent.execute_script( "var e = arguments[0].ownerDocument.createEvent('Event');" "e.initEvent('submit', true, true);" "if (arguments[0].dispatchEvent(e)) {...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_property(self, name): """ Gets the given property of the element. :Args: - name - Name of the property to retrieve. :Usage: :: text_length = target_eleme...
try: return self._execute(Command.GET_ELEMENT_PROPERTY, {"name": name})["value"] except WebDriverException: # if we hit an end point that doesnt understand getElementProperty lets fake it return self.parent.execute_script('return arguments[0][arguments[1]]', self, na...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_attribute(self, name): """Gets the given attribute or property of the element. This method will first try to return the value of a property with the give...
attributeValue = '' if self._w3c: attributeValue = self.parent.execute_script( "return (%s).apply(null, arguments);" % getAttribute_js, self, name) else: resp = self._execute(Command.GET_ELEMENT_ATTRIBUTE, {'name': name}) attr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def send_keys(self, *value): """Simulates typing into the element. :Args: - value - A string for typing, or setting form fields. For setting file inputs, this co...
# transfer file to another machine only if remote driver is used # the same behaviour as for java binding if self.parent._is_remote: local_file = self.parent.file_detector.is_local_file(*value) if local_file is not None: value = self._upload(local_file) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_displayed(self): """Whether the element is visible to a user."""
# Only go into this conditional for browsers that don't use the atom themselves if self._w3c: return self.parent.execute_script( "return (%s).apply(null, arguments);" % isDisplayed_js, self) else: return self._execute(Command.IS_ELEMENT_DI...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def location_once_scrolled_into_view(self): """THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can cl...
if self._w3c: old_loc = self._execute(Command.W3C_EXECUTE_SCRIPT, { 'script': "arguments[0].scrollIntoView(true); return arguments[0].getBoundingClientRect()", 'args': [self]})['value'] return {"x": round(old_loc['x']), "y": round(old_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def size(self): """The size of the element."""
size = {} if self._w3c: size = self._execute(Command.GET_ELEMENT_RECT)['value'] else: size = self._execute(Command.GET_ELEMENT_SIZE)['value'] new_size = {"height": size["height"], "width": size["width"]} return new_size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def location(self): """The location of the element in the renderable canvas."""
if self._w3c: old_loc = self._execute(Command.GET_ELEMENT_RECT)['value'] else: old_loc = self._execute(Command.GET_ELEMENT_LOCATION)['value'] new_loc = {"x": round(old_loc['x']), "y": round(old_loc['y'])} return new_loc
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rect(self): """A dictionary with the size and location of the element."""
if self._w3c: return self._execute(Command.GET_ELEMENT_RECT)['value'] else: rect = self.size.copy() rect.update(self.location) return rect
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def screenshot(self, filename): """ Saves a screenshot of the current element to a PNG image file. Returns False if there is any IOError, else returns True. Use ...
if not filename.lower().endswith('.png'): warnings.warn("name used for saved screenshot does not match file " "type. It should end with a `.png` extension", UserWarning) png = self.screenshot_as_png try: with open(filename, 'wb') as f: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _execute(self, command, params=None): """Executes a command against the underlying HTML element. Args: command: The name of the command to _execute as a stri...
if not params: params = {} params['id'] = self._id return self._parent.execute(command, params)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def quit(self): """ Closes the browser and shuts down the WebKitGTKDriver executable that is started when starting the WebKitGTKDriver """
try: RemoteWebDriver.quit(self) except http_client.BadStatusLine: pass finally: self.service.stop()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Starts the Service. :Exceptions: - WebDriverException : Raised either when it can't start the service or when it can't connect to the servic...
try: cmd = [self.path] cmd.extend(self.command_line_args()) self.process = subprocess.Popen(cmd, env=self.env, close_fds=platform.system() != 'Windows', stdout=self.log_file, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def launch_browser(self, profile, timeout=30): """Launches the browser for the given profile name. It is assumed the profile already exists. """
self.profile = profile self._start_from_profile_path(self.profile.path) self._wait_until_connectable(timeout=timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def kill(self): """Kill the browser. This is useful when the browser is stuck. """
if self.process: self.process.kill() self.process.wait()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _wait_until_connectable(self, timeout=30): """Blocks until the extension is connectable in the firefox."""
count = 0 while not utils.is_connectable(self.profile.port): if self.process.poll() is not None: # Browser has exited raise WebDriverException( "The browser appears to have exited " "before we could connect. If you spec...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_firefox_start_cmd(self): """Return the command to start firefox."""
start_cmd = "" if platform.system() == "Darwin": start_cmd = "/Applications/Firefox.app/Contents/MacOS/firefox-bin" # fallback to homebrew installation for mac users if not os.path.exists(start_cmd): start_cmd = os.path.expanduser("~") + start_cmd ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def which(self, fname): """Returns the fully qualified path by searching Path of the given name"""
for pe in os.environ['PATH'].split(os.pathsep): checkname = os.path.join(pe, fname) if os.access(checkname, os.X_OK) and not os.path.isdir(checkname): return checkname return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_remote_connection_headers(cls, parsed_url, keep_alive=False): """ Get headers for remote request. :Args: - parsed_url - The parsed url - keep_alive (Bool...
system = platform.system().lower() if system == "darwin": system = "mac" headers = { 'Accept': 'application/json', 'Content-Type': 'application/json;charset=UTF-8', 'User-Agent': 'selenium/{} (python {})'.format(__version__, system) } ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def execute(self, command, params): """ Send a command to the remote server. Any path subtitutions required for the URL mapped to the command should be included ...
command_info = self._commands[command] assert command_info is not None, 'Unrecognised command %s' % command path = string.Template(command_info[1]).substitute(params) if hasattr(self, 'w3c') and self.w3c and isinstance(params, dict) and 'sessionId' in params: del params['ses...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _request(self, method, url, body=None): """ Send an HTTP request to the remote server. :Args: - method - A string for the HTTP method to send the request wit...
LOGGER.debug('%s %s %s' % (method, url, body)) parsed_url = parse.urlparse(url) headers = self.get_remote_connection_headers(parsed_url, self.keep_alive) resp = None if body and method != 'POST' and method != 'PUT': body = None if self.keep_alive: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_selected_options(self): """Returns a list of all selected options belonging to this select tag"""
ret = [] for opt in self.options: if opt.is_selected(): ret.append(opt) return ret
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_by_index(self, index): """Select the option at the given index. This is done by examing the "index" attribute of an element, and not merely by countin...
match = str(index) for opt in self.options: if opt.get_attribute("index") == match: self._setSelected(opt) return raise NoSuchElementException("Could not locate element with index %d" % index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deselect_all(self): """Clear all selected entries. This is only valid when the SELECT supports multiple selections. throws NotImplementedError If the SELECT ...
if not self.is_multiple: raise NotImplementedError("You may only deselect all options of a multi-select") for opt in self.options: self._unsetSelected(opt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deselect_by_index(self, index): """Deselect the option at the given index. This is done by examing the "index" attribute of an element, and not merely by cou...
if not self.is_multiple: raise NotImplementedError("You may only deselect options of a multi-select") for opt in self.options: if opt.get_attribute("index") == str(index): self._unsetSelected(opt) return raise NoSuchElementException("Could...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _upload(auth_http, project_id, bucket_name, file_path, object_name, acl): """Uploads a file to Google Cloud Storage. Args: auth_http: An authorized httplib2....
with open(file_path, 'rb') as f: data = f.read() content_type, content_encoding = mimetypes.guess_type(file_path) headers = { 'x-goog-project-id': project_id, 'x-goog-api-version': API_VERSION, 'x-goog-acl': acl, 'Content-Length': '%d' % len(data) } if conte...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _authenticate(secrets_file): """Runs the OAuth 2.0 installed application flow. Returns: An authorized httplib2.Http instance. """
flow = oauthclient.flow_from_clientsecrets( secrets_file, scope=OAUTH_SCOPE, message=('Failed to initialized OAuth 2.0 flow with secrets ' 'file: %s' % secrets_file)) storage = oauthfile.Storage(OAUTH_CREDENTIALS_FILE) credentials = storage.get() if credentials ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def auto_detect(self, value): """ Sets autodetect setting. :Args: - value: The autodetect value. """
if isinstance(value, bool): if self.autodetect is not value: self._verify_proxy_type_compatibility(ProxyType.AUTODETECT) self.proxyType = ProxyType.AUTODETECT self.autodetect = value else: raise ValueError("Autodetect proxy value n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ftp_proxy(self, value): """ Sets ftp proxy setting. :Args: - value: The ftp proxy value. """
self._verify_proxy_type_compatibility(ProxyType.MANUAL) self.proxyType = ProxyType.MANUAL self.ftpProxy = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def http_proxy(self, value): """ Sets http proxy setting. :Args: - value: The http proxy value. """
self._verify_proxy_type_compatibility(ProxyType.MANUAL) self.proxyType = ProxyType.MANUAL self.httpProxy = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def no_proxy(self, value): """ Sets noproxy setting. :Args: - value: The noproxy value. """
self._verify_proxy_type_compatibility(ProxyType.MANUAL) self.proxyType = ProxyType.MANUAL self.noProxy = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def proxy_autoconfig_url(self, value): """ Sets proxy autoconfig url setting. :Args: - value: The proxy autoconfig url value. """
self._verify_proxy_type_compatibility(ProxyType.PAC) self.proxyType = ProxyType.PAC self.proxyAutoconfigUrl = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ssl_proxy(self, value): """ Sets https proxy setting. :Args: - value: The https proxy value. """
self._verify_proxy_type_compatibility(ProxyType.MANUAL) self.proxyType = ProxyType.MANUAL self.sslProxy = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def socks_proxy(self, value): """ Sets socks proxy setting. :Args: - value: The socks proxy value. """
self._verify_proxy_type_compatibility(ProxyType.MANUAL) self.proxyType = ProxyType.MANUAL self.socksProxy = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def socks_username(self, value): """ Sets socks proxy username setting. :Args: - value: The socks proxy username value. """
self._verify_proxy_type_compatibility(ProxyType.MANUAL) self.proxyType = ProxyType.MANUAL self.socksUsername = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def socks_password(self, value): """ Sets socks proxy password setting. :Args: - value: The socks proxy password value. """
self._verify_proxy_type_compatibility(ProxyType.MANUAL) self.proxyType = ProxyType.MANUAL self.socksPassword = value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_to_capabilities(self, capabilities): """ Adds proxy information as capability in specified capabilities. :Args: - capabilities: The capabilities to which...
proxy_caps = {} proxy_caps['proxyType'] = self.proxyType['string'] if self.autodetect: proxy_caps['autodetect'] = self.autodetect if self.ftpProxy: proxy_caps['ftpProxy'] = self.ftpProxy if self.httpProxy: proxy_caps['httpProxy'] = self.httpPr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def find_connectable_ip(host, port=None): """Resolve a hostname to an IP, preferring IPv4 addresses. We prefer IPv4 so that we don't change behavior from previou...
try: addrinfos = socket.getaddrinfo(host, None) except socket.gaierror: return None ip = None for family, _, _, _, sockaddr in addrinfos: connectable = True if port: connectable = is_connectable(port, sockaddr[0]) if connectable and family == socket...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join_host_port(host, port): """Joins a hostname and port together. This is a minimal implementation intended to cope with IPv6 literals. For example, _join_h...
if ':' in host and not host.startswith('['): return '[%s]:%d' % (host, port) return '%s:%d' % (host, port)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_connectable(port, host="localhost"): """ Tries to connect to the server at port to see if it is running. :Args: - port - The port to connect. """
socket_ = None try: socket_ = socket.create_connection((host, port), 1) result = True except _is_connectable_exceptions: result = False finally: if socket_: socket_.close() return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keys_to_typing(value): """Processes the values that will be typed in the element."""
typing = [] for val in value: if isinstance(val, Keys): typing.append(val) elif isinstance(val, int): val = str(val) for i in range(len(val)): typing.append(val[i]) else: for i in range(len(val)): typing.app...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_html(doc, output="/tmp", style="dep"): """Doc method extension for saving the current state as a displaCy visualization. """
# generate filename from first six non-punct tokens file_name = "-".join([w.text for w in doc[:6] if not w.is_punct]) + ".html" html = displacy.render(doc, style=style, page=True) # render markup if output is not None: output_path = Path(output) if not output_path.exists(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def overlap_tokens(doc, other_doc): """Get the tokens from the original Doc that are also in the comparison Doc. """
overlap = [] other_tokens = [token.text for token in other_doc] for token in doc: if token.text in other_tokens: overlap.append(token) return overlap
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iob2json(input_data, n_sents=10, *args, **kwargs): """ Convert IOB files into JSON format for use with train cli. """
docs = [] for group in minibatch(docs, n_sents): group = list(group) first = group.pop(0) to_extend = first["paragraphs"][0]["sentences"] for sent in group[1:]: to_extend.extend(sent["paragraphs"][0]["sentences"]) docs.append(first) return docs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render( docs, style="dep", page=False, minify=False, jupyter=None, options={}, manual=False ): """Render displaCy visualisation. docs (list or Doc): Documen...
factories = { "dep": (DependencyRenderer, parse_deps), "ent": (EntityRenderer, parse_ents), } if style not in factories: raise ValueError(Errors.E087.format(style=style)) if isinstance(docs, (Doc, Span, dict)): docs = [docs] docs = [obj if not isinstance(obj, Span) e...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def serve( docs, style="dep", page=True, minify=False, options={}, manual=False, port=5000, host="0.0.0.0", ): """Serve displaCy visualisation. docs (list or Doc...
from wsgiref import simple_server if is_in_jupyter(): user_warning(Warnings.W011) render(docs, style=style, page=page, minify=minify, options=options, manual=manual) httpd = simple_server.make_server(host, port, app) print("\nUsing the '{}' visualizer".format(style)) print("Serving on...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_render_wrapper(func): """Set an optional wrapper function that is called around the generated HTML markup on displacy.render. This can be used to allow i...
global RENDER_WRAPPER if not hasattr(func, "__call__"): raise ValueError(Errors.E110.format(obj=type(func))) RENDER_WRAPPER = func
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def evaluate( model, data_path, gpu_id=-1, gold_preproc=False, displacy_path=None, displacy_limit=25, return_scores=False, ): """ Evaluate a model. To render a s...
msg = Printer() util.fix_random_seed() if gpu_id >= 0: util.use_gpu(gpu_id) util.set_env_log(False) data_path = util.ensure_path(data_path) displacy_path = util.ensure_path(displacy_path) if not data_path.exists(): msg.fail("Evaluation data not found", data_path, exits=1) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def profile(model, inputs=None, n_texts=10000): """ Profile a spaCy pipeline, to find out which functions take the most time. Input should be formatted as one JS...
msg = Printer() if inputs is not None: inputs = _read_inputs(inputs, msg) if inputs is None: n_inputs = 25000 with msg.loading("Loading IMDB dataset via Thinc..."): imdb_train, _ = thinc.extra.datasets.imdb() inputs, _ = zip(*imdb_train) msg.info("Loa...