partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
ActionChains.move_by_offset
Moving the mouse to an offset from current mouse position. :Args: - xoffset: X offset to move to, as a positive or negative integer. - yoffset: Y offset to move to, as a positive or negative integer.
py/selenium/webdriver/common/action_chains.py
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 or negative integer. - yoffset: Y offset to move to, as a positive or negative integer. """ 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), 'yoffset': int(yoffset)})) return self
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 or negative integer. - yoffset: Y offset to move to, as a positive or negative integer. """ 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), 'yoffset': int(yoffset)})) return self
[ "Moving", "the", "mouse", "to", "an", "offset", "from", "current", "mouse", "position", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L247-L263
[ "def", "move_by_offset", "(", "self", ",", "xoffset", ",", "yoffset", ")", ":", "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", ")", ",", "'yoffset'", ":", "int", "(", "yoffset", ")", "}", ")", ")", "return", "self" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
ActionChains.move_to_element
Moving the mouse to the middle of an element. :Args: - to_element: The WebElement to move to.
py/selenium/webdriver/common/action_chains.py
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
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
[ "Moving", "the", "mouse", "to", "the", "middle", "of", "an", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L265-L278
[ "def", "move_to_element", "(", "self", ",", "to_element", ")", ":", "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" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
ActionChains.move_to_element_with_offset
Move the mouse by an offset of the specified element. Offsets are relative to the top-left corner of the element. :Args: - to_element: The WebElement to move to. - xoffset: X offset to move to. - yoffset: Y offset to move to.
py/selenium/webdriver/common/action_chains.py
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-left corner of the element. :Args: - to_element: The WebElement to move to. - xoffset: X offset to move to. - yoffset: Y offset to move to. """ 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, 'xoffset': int(xoffset), 'yoffset': int(yoffset)})) return self
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-left corner of the element. :Args: - to_element: The WebElement to move to. - xoffset: X offset to move to. - yoffset: Y offset to move to. """ 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, 'xoffset': int(xoffset), 'yoffset': int(yoffset)})) return self
[ "Move", "the", "mouse", "by", "an", "offset", "of", "the", "specified", "element", ".", "Offsets", "are", "relative", "to", "the", "top", "-", "left", "corner", "of", "the", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L280-L299
[ "def", "move_to_element_with_offset", "(", "self", ",", "to_element", ",", "xoffset", ",", "yoffset", ")", ":", "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", ",", "'xoffset'", ":", "int", "(", "xoffset", ")", ",", "'yoffset'", ":", "int", "(", "yoffset", ")", "}", ")", ")", "return", "self" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
ActionChains.pause
Pause all inputs for the specified duration in seconds
py/selenium/webdriver/common/action_chains.py
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
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
[ "Pause", "all", "inputs", "for", "the", "specified", "duration", "in", "seconds" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L301-L308
[ "def", "pause", "(", "self", ",", "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" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
ActionChains.release
Releasing a held mouse button on an element. :Args: - on_element: The element to mouse up. If None, releases on current mouse position.
py/selenium/webdriver/common/action_chains.py
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 mouse position. """ 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
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 mouse position. """ 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
[ "Releasing", "a", "held", "mouse", "button", "on", "an", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L310-L325
[ "def", "release", "(", "self", ",", "on_element", "=", "None", ")", ":", "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" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
ActionChains.send_keys
Sends keys to current focused element. :Args: - keys_to_send: The keys to send. Modifier keys constants can be found in the 'Keys' class.
py/selenium/webdriver/common/action_chains.py
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 the 'Keys' class. """ 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': typing})) return self
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 the 'Keys' class. """ 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': typing})) return self
[ "Sends", "keys", "to", "current", "focused", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L327-L343
[ "def", "send_keys", "(", "self", ",", "*", "keys_to_send", ")", ":", "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'", ":", "typing", "}", ")", ")", "return", "self" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
ActionChains.send_keys_to_element
Sends keys to an element. :Args: - element: The element to send keys. - keys_to_send: The keys to send. Modifier keys constants can be found in the 'Keys' class.
py/selenium/webdriver/common/action_chains.py
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 send. Modifier keys constants can be found in the 'Keys' class. """ self.click(element) self.send_keys(*keys_to_send) return self
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 send. Modifier keys constants can be found in the 'Keys' class. """ self.click(element) self.send_keys(*keys_to_send) return self
[ "Sends", "keys", "to", "an", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L345-L356
[ "def", "send_keys_to_element", "(", "self", ",", "element", ",", "*", "keys_to_send", ")", ":", "self", ".", "click", "(", "element", ")", "self", ".", "send_keys", "(", "*", "keys_to_send", ")", "return", "self" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Options.browser_attach_timeout
Sets the options Browser Attach Timeout :Args: - value: Timeout in milliseconds
py/selenium/webdriver/ie/options.py
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
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
[ "Sets", "the", "options", "Browser", "Attach", "Timeout" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/ie/options.py#L65-L75
[ "def", "browser_attach_timeout", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "int", ")", ":", "raise", "ValueError", "(", "'Browser Attach Timeout must be an integer.'", ")", "self", ".", "_options", "[", "self", ".", "BROWSER_ATTACH_TIMEOUT", "]", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Options.element_scroll_behavior
Sets the options Element Scroll Behavior :Args: - value: 0 - Top, 1 - Bottom
py/selenium/webdriver/ie/options.py
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
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
[ "Sets", "the", "options", "Element", "Scroll", "Behavior" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/ie/options.py#L83-L93
[ "def", "element_scroll_behavior", "(", "self", ",", "value", ")", ":", "if", "value", "not", "in", "[", "ElementScrollBehavior", ".", "TOP", ",", "ElementScrollBehavior", ".", "BOTTOM", "]", ":", "raise", "ValueError", "(", "'Element Scroll Behavior out of range.'", ")", "self", ".", "_options", "[", "self", ".", "ELEMENT_SCROLL_BEHAVIOR", "]", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Options.file_upload_dialog_timeout
Sets the options File Upload Dialog Timeout value :Args: - value: Timeout in milliseconds
py/selenium/webdriver/ie/options.py
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
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
[ "Sets", "the", "options", "File", "Upload", "Dialog", "Timeout", "value" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/ie/options.py#L117-L127
[ "def", "file_upload_dialog_timeout", "(", "self", ",", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "int", ")", ":", "raise", "ValueError", "(", "'File Upload Dialog Timeout must be an integer.'", ")", "self", ".", "_options", "[", "self", ".", "FILE_UPLOAD_DIALOG_TIMEOUT", "]", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Options.to_capabilities
Marshals the IE options to the correct object.
py/selenium/webdriver/ie/options.py
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 caps
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 caps
[ "Marshals", "the", "IE", "options", "to", "the", "correct", "object", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/ie/options.py#L321-L334
[ "def", "to_capabilities", "(", "self", ")", ":", "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", "caps" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Options.extensions
:Returns: A list of encoded extensions that will be loaded into chrome
py/selenium/webdriver/chrome/options.py
def extensions(self): """ :Returns: A list of encoded extensions that will be loaded into chrome """ encoded_extensions = [] for ext in self._extension_files: file_ = open(ext, 'rb') # Should not use base64.encodestring() which inserts newlines every # 76 characters (per RFC 1521). Chromedriver has to remove those # unnecessary newlines before decoding, causing performance hit. encoded_extensions.append(base64.b64encode(file_.read()).decode('UTF-8')) file_.close() return encoded_extensions + self._extensions
def extensions(self): """ :Returns: A list of encoded extensions that will be loaded into chrome """ encoded_extensions = [] for ext in self._extension_files: file_ = open(ext, 'rb') # Should not use base64.encodestring() which inserts newlines every # 76 characters (per RFC 1521). Chromedriver has to remove those # unnecessary newlines before decoding, causing performance hit. encoded_extensions.append(base64.b64encode(file_.read()).decode('UTF-8')) file_.close() return encoded_extensions + self._extensions
[ ":", "Returns", ":", "A", "list", "of", "encoded", "extensions", "that", "will", "be", "loaded", "into", "chrome" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/chrome/options.py#L73-L86
[ "def", "extensions", "(", "self", ")", ":", "encoded_extensions", "=", "[", "]", "for", "ext", "in", "self", ".", "_extension_files", ":", "file_", "=", "open", "(", "ext", ",", "'rb'", ")", "# Should not use base64.encodestring() which inserts newlines every", "# 76 characters (per RFC 1521). Chromedriver has to remove those", "# unnecessary newlines before decoding, causing performance hit.", "encoded_extensions", ".", "append", "(", "base64", ".", "b64encode", "(", "file_", ".", "read", "(", ")", ")", ".", "decode", "(", "'UTF-8'", ")", ")", "file_", ".", "close", "(", ")", "return", "encoded_extensions", "+", "self", ".", "_extensions" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Options.add_extension
Adds the path to the extension to a list that will be used to extract it to the ChromeDriver :Args: - extension: path to the \\*.crx file
py/selenium/webdriver/chrome/options.py
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 the \\*.crx file """ 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: raise ValueError("argument can not be null")
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 the \\*.crx file """ 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: raise ValueError("argument can not be null")
[ "Adds", "the", "path", "to", "the", "extension", "to", "a", "list", "that", "will", "be", "used", "to", "extract", "it", "to", "the", "ChromeDriver" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/chrome/options.py#L88-L103
[ "def", "add_extension", "(", "self", ",", "extension", ")", ":", "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", ":", "raise", "ValueError", "(", "\"argument can not be null\"", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Options.headless
Sets the headless argument :Args: value: boolean value indicating to set the headless option
py/selenium/webdriver/chrome/options.py
def headless(self, value): """ Sets the headless argument :Args: value: boolean value indicating to set the headless option """ args = {'--headless'} if value is True: self._arguments.extend(args) else: self._arguments = list(set(self._arguments) - args)
def headless(self, value): """ Sets the headless argument :Args: value: boolean value indicating to set the headless option """ args = {'--headless'} if value is True: self._arguments.extend(args) else: self._arguments = list(set(self._arguments) - args)
[ "Sets", "the", "headless", "argument" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/chrome/options.py#L143-L154
[ "def", "headless", "(", "self", ",", "value", ")", ":", "args", "=", "{", "'--headless'", "}", "if", "value", "is", "True", ":", "self", ".", "_arguments", ".", "extend", "(", "args", ")", "else", ":", "self", ".", "_arguments", "=", "list", "(", "set", "(", "self", ".", "_arguments", ")", "-", "args", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Options.to_capabilities
Creates a capabilities with all the options that have been set :Returns: A dictionary with everything
py/selenium/webdriver/chrome/options.py
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: chrome_options["debuggerAddress"] = self.debugger_address caps[self.KEY] = chrome_options return caps
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: chrome_options["debuggerAddress"] = self.debugger_address caps[self.KEY] = chrome_options return caps
[ "Creates", "a", "capabilities", "with", "all", "the", "options", "that", "have", "been", "set" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/chrome/options.py#L156-L173
[ "def", "to_capabilities", "(", "self", ")", ":", "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", ":", "chrome_options", "[", "\"debuggerAddress\"", "]", "=", "self", ".", "debugger_address", "caps", "[", "self", ".", "KEY", "]", "=", "chrome_options", "return", "caps" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
_find_element
Looks up an element. Logs and re-raises ``WebDriverException`` if thrown.
py/selenium/webdriver/support/expected_conditions.py
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
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
[ "Looks", "up", "an", "element", ".", "Logs", "and", "re", "-", "raises", "WebDriverException", "if", "thrown", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/expected_conditions.py#L407-L415
[ "def", "_find_element", "(", "driver", ",", "by", ")", ":", "try", ":", "return", "driver", ".", "find_element", "(", "*", "by", ")", "except", "NoSuchElementException", "as", "e", ":", "raise", "e", "except", "WebDriverException", "as", "e", ":", "raise", "e" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Alert.text
Gets the text of the Alert.
py/selenium/webdriver/common/alert.py
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"]
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"]
[ "Gets", "the", "text", "of", "the", "Alert", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/alert.py#L62-L69
[ "def", "text", "(", "self", ")", ":", "if", "self", ".", "driver", ".", "w3c", ":", "return", "self", ".", "driver", ".", "execute", "(", "Command", ".", "W3C_GET_ALERT_TEXT", ")", "[", "\"value\"", "]", "else", ":", "return", "self", ".", "driver", ".", "execute", "(", "Command", ".", "GET_ALERT_TEXT", ")", "[", "\"value\"", "]" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Alert.dismiss
Dismisses the alert available.
py/selenium/webdriver/common/alert.py
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)
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)
[ "Dismisses", "the", "alert", "available", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/alert.py#L71-L78
[ "def", "dismiss", "(", "self", ")", ":", "if", "self", ".", "driver", ".", "w3c", ":", "self", ".", "driver", ".", "execute", "(", "Command", ".", "W3C_DISMISS_ALERT", ")", "else", ":", "self", ".", "driver", ".", "execute", "(", "Command", ".", "DISMISS_ALERT", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Alert.accept
Accepts the alert available. Usage:: Alert(driver).accept() # Confirm a alert dialog.
py/selenium/webdriver/common/alert.py
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)
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)
[ "Accepts", "the", "alert", "available", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/alert.py#L80-L90
[ "def", "accept", "(", "self", ")", ":", "if", "self", ".", "driver", ".", "w3c", ":", "self", ".", "driver", ".", "execute", "(", "Command", ".", "W3C_ACCEPT_ALERT", ")", "else", ":", "self", ".", "driver", ".", "execute", "(", "Command", ".", "ACCEPT_ALERT", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Alert.send_keys
Send Keys to the Alert. :Args: - keysToSend: The text to be sent to Alert.
py/selenium/webdriver/common/alert.py
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})
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})
[ "Send", "Keys", "to", "the", "Alert", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/alert.py#L92-L105
[ "def", "send_keys", "(", "self", ",", "keysToSend", ")", ":", "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", "}", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxProfile.port
Sets the port that WebDriver will be running on
py/selenium/webdriver/firefox/firefox_profile.py
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): raise WebDriverException("Port needs to be an integer") self._port = port self.set_preference("webdriver_firefox_port", self._port)
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): raise WebDriverException("Port needs to be an integer") self._port = port self.set_preference("webdriver_firefox_port", self._port)
[ "Sets", "the", "port", "that", "WebDriver", "will", "be", "running", "on" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_profile.py#L119-L132
[ "def", "port", "(", "self", ",", "port", ")", ":", "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", ")", ":", "raise", "WebDriverException", "(", "\"Port needs to be an integer\"", ")", "self", ".", "_port", "=", "port", "self", ".", "set_preference", "(", "\"webdriver_firefox_port\"", ",", "self", ".", "_port", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxProfile.encoded
A zipped, base64 encoded string of profile directory for use with remote WebDriver JSON wire protocol
py/selenium/webdriver/firefox/firefox_profile.py
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, fyle) zipped.write(filename, filename[path_root:]) zipped.close() return base64.b64encode(fp.getvalue()).decode('UTF-8')
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, fyle) zipped.write(filename, filename[path_root:]) zipped.close() return base64.b64encode(fp.getvalue()).decode('UTF-8')
[ "A", "zipped", "base64", "encoded", "string", "of", "profile", "directory", "for", "use", "with", "remote", "WebDriver", "JSON", "wire", "protocol" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_profile.py#L156-L170
[ "def", "encoded", "(", "self", ")", ":", "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", ",", "fyle", ")", "zipped", ".", "write", "(", "filename", ",", "filename", "[", "path_root", ":", "]", ")", "zipped", ".", "close", "(", ")", "return", "base64", ".", "b64encode", "(", "fp", ".", "getvalue", "(", ")", ")", ".", "decode", "(", "'UTF-8'", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxProfile._write_user_prefs
writes the current user prefs dictionary to disk
py/selenium/webdriver/firefox/firefox_profile.py
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)))
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)))
[ "writes", "the", "current", "user", "prefs", "dictionary", "to", "disk" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_profile.py#L178-L184
[ "def", "_write_user_prefs", "(", "self", ",", "user_prefs", ")", ":", "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", ")", ")", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxProfile._install_extension
Installs addon from a filepath, url or directory of addons in the profile. - path: url, absolute path to .xpi, or directory of addons - unpack: whether to unpack unless specified otherwise in the install.rdf
py/selenium/webdriver/firefox/firefox_profile.py
def _install_extension(self, addon, unpack=True): """ Installs addon from a filepath, url or directory of addons in the profile. - path: url, absolute path to .xpi, or directory of addons - unpack: whether to unpack unless specified otherwise in the install.rdf """ if addon == WEBDRIVER_EXT: addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT) tmpdir = None xpifile = None if addon.endswith('.xpi'): tmpdir = tempfile.mkdtemp(suffix='.' + os.path.split(addon)[-1]) compressed_file = zipfile.ZipFile(addon, 'r') for name in compressed_file.namelist(): if name.endswith('/'): if not os.path.isdir(os.path.join(tmpdir, name)): os.makedirs(os.path.join(tmpdir, name)) else: if not os.path.isdir(os.path.dirname(os.path.join(tmpdir, name))): os.makedirs(os.path.dirname(os.path.join(tmpdir, name))) data = compressed_file.read(name) with open(os.path.join(tmpdir, name), 'wb') as f: f.write(data) xpifile = addon addon = tmpdir # determine the addon id addon_details = self._addon_details(addon) addon_id = addon_details.get('id') assert addon_id, 'The addon id could not be found: %s' % addon # copy the addon to the profile addon_path = os.path.join(self.extensionsDir, addon_id) if not unpack and not addon_details['unpack'] and xpifile: if not os.path.exists(self.extensionsDir): os.makedirs(self.extensionsDir) os.chmod(self.extensionsDir, 0o755) shutil.copy(xpifile, addon_path + '.xpi') else: if not os.path.exists(addon_path): shutil.copytree(addon, addon_path, symlinks=True) # remove the temporary directory, if any if tmpdir: shutil.rmtree(tmpdir)
def _install_extension(self, addon, unpack=True): """ Installs addon from a filepath, url or directory of addons in the profile. - path: url, absolute path to .xpi, or directory of addons - unpack: whether to unpack unless specified otherwise in the install.rdf """ if addon == WEBDRIVER_EXT: addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT) tmpdir = None xpifile = None if addon.endswith('.xpi'): tmpdir = tempfile.mkdtemp(suffix='.' + os.path.split(addon)[-1]) compressed_file = zipfile.ZipFile(addon, 'r') for name in compressed_file.namelist(): if name.endswith('/'): if not os.path.isdir(os.path.join(tmpdir, name)): os.makedirs(os.path.join(tmpdir, name)) else: if not os.path.isdir(os.path.dirname(os.path.join(tmpdir, name))): os.makedirs(os.path.dirname(os.path.join(tmpdir, name))) data = compressed_file.read(name) with open(os.path.join(tmpdir, name), 'wb') as f: f.write(data) xpifile = addon addon = tmpdir # determine the addon id addon_details = self._addon_details(addon) addon_id = addon_details.get('id') assert addon_id, 'The addon id could not be found: %s' % addon # copy the addon to the profile addon_path = os.path.join(self.extensionsDir, addon_id) if not unpack and not addon_details['unpack'] and xpifile: if not os.path.exists(self.extensionsDir): os.makedirs(self.extensionsDir) os.chmod(self.extensionsDir, 0o755) shutil.copy(xpifile, addon_path + '.xpi') else: if not os.path.exists(addon_path): shutil.copytree(addon, addon_path, symlinks=True) # remove the temporary directory, if any if tmpdir: shutil.rmtree(tmpdir)
[ "Installs", "addon", "from", "a", "filepath", "url", "or", "directory", "of", "addons", "in", "the", "profile", ".", "-", "path", ":", "url", "absolute", "path", "to", ".", "xpi", "or", "directory", "of", "addons", "-", "unpack", ":", "whether", "to", "unpack", "unless", "specified", "otherwise", "in", "the", "install", ".", "rdf" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_profile.py#L203-L249
[ "def", "_install_extension", "(", "self", ",", "addon", ",", "unpack", "=", "True", ")", ":", "if", "addon", "==", "WEBDRIVER_EXT", ":", "addon", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "WEBDRIVER_EXT", ")", "tmpdir", "=", "None", "xpifile", "=", "None", "if", "addon", ".", "endswith", "(", "'.xpi'", ")", ":", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", "suffix", "=", "'.'", "+", "os", ".", "path", ".", "split", "(", "addon", ")", "[", "-", "1", "]", ")", "compressed_file", "=", "zipfile", ".", "ZipFile", "(", "addon", ",", "'r'", ")", "for", "name", "in", "compressed_file", ".", "namelist", "(", ")", ":", "if", "name", ".", "endswith", "(", "'/'", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "name", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "name", ")", ")", "else", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "name", ")", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "name", ")", ")", ")", "data", "=", "compressed_file", ".", "read", "(", "name", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "tmpdir", ",", "name", ")", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "data", ")", "xpifile", "=", "addon", "addon", "=", "tmpdir", "# determine the addon id", "addon_details", "=", "self", ".", "_addon_details", "(", "addon", ")", "addon_id", "=", "addon_details", ".", "get", "(", "'id'", ")", "assert", "addon_id", ",", "'The addon id could not be found: %s'", "%", "addon", "# copy the addon to the profile", "addon_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "extensionsDir", ",", "addon_id", ")", "if", "not", "unpack", "and", "not", "addon_details", "[", "'unpack'", "]", "and", "xpifile", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "extensionsDir", ")", ":", "os", ".", "makedirs", "(", "self", ".", "extensionsDir", ")", "os", ".", "chmod", "(", "self", ".", "extensionsDir", ",", "0o755", ")", "shutil", ".", "copy", "(", "xpifile", ",", "addon_path", "+", "'.xpi'", ")", "else", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "addon_path", ")", ":", "shutil", ".", "copytree", "(", "addon", ",", "addon_path", ",", "symlinks", "=", "True", ")", "# remove the temporary directory, if any", "if", "tmpdir", ":", "shutil", ".", "rmtree", "(", "tmpdir", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxProfile._addon_details
Returns a dictionary of details about the addon. :param addon_path: path to the add-on directory or XPI Returns:: {'id': u'rainbow@colors.org', # id of the addon 'version': u'1.4', # version of the addon 'name': u'Rainbow', # name of the addon 'unpack': False } # whether to unpack the addon
py/selenium/webdriver/firefox/firefox_profile.py
def _addon_details(self, addon_path): """ Returns a dictionary of details about the addon. :param addon_path: path to the add-on directory or XPI Returns:: {'id': u'rainbow@colors.org', # id of the addon 'version': u'1.4', # version of the addon 'name': u'Rainbow', # name of the addon 'unpack': False } # whether to unpack the addon """ details = { 'id': None, 'unpack': False, 'name': None, 'version': None } def get_namespace_id(doc, url): attributes = doc.documentElement.attributes namespace = "" for i in range(attributes.length): if attributes.item(i).value == url: if ":" in attributes.item(i).name: # If the namespace is not the default one remove 'xlmns:' namespace = attributes.item(i).name.split(':')[1] + ":" break return namespace def get_text(element): """Retrieve the text value of a given node""" rc = [] for node in element.childNodes: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc).strip() def parse_manifest_json(content): """Extracts the details from the contents of a WebExtensions `manifest.json` file.""" manifest = json.loads(content) try: id = manifest['applications']['gecko']['id'] except KeyError: id = manifest['name'].replace(" ", "") + "@" + manifest['version'] return { 'id': id, 'version': manifest['version'], 'name': manifest['version'], 'unpack': False, } if not os.path.exists(addon_path): raise IOError('Add-on path does not exist: %s' % addon_path) try: if zipfile.is_zipfile(addon_path): # Bug 944361 - We cannot use 'with' together with zipFile because # it will cause an exception thrown in Python 2.6. try: compressed_file = zipfile.ZipFile(addon_path, 'r') if 'manifest.json' in compressed_file.namelist(): return parse_manifest_json(compressed_file.read('manifest.json')) manifest = compressed_file.read('install.rdf') finally: compressed_file.close() elif os.path.isdir(addon_path): manifest_json_filename = os.path.join(addon_path, 'manifest.json') if os.path.exists(manifest_json_filename): with open(manifest_json_filename, 'r') as f: return parse_manifest_json(f.read()) with open(os.path.join(addon_path, 'install.rdf'), 'r') as f: manifest = f.read() else: raise IOError('Add-on path is neither an XPI nor a directory: %s' % addon_path) except (IOError, KeyError) as e: raise AddonFormatError(str(e), sys.exc_info()[2]) try: doc = minidom.parseString(manifest) # Get the namespaces abbreviations em = get_namespace_id(doc, 'http://www.mozilla.org/2004/em-rdf#') rdf = get_namespace_id(doc, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') description = doc.getElementsByTagName(rdf + 'Description').item(0) if description is None: description = doc.getElementsByTagName('Description').item(0) for node in description.childNodes: # Remove the namespace prefix from the tag for comparison entry = node.nodeName.replace(em, "") if entry in details.keys(): details.update({entry: get_text(node)}) if details.get('id') is None: for i in range(description.attributes.length): attribute = description.attributes.item(i) if attribute.name == em + 'id': details.update({'id': attribute.value}) except Exception as e: raise AddonFormatError(str(e), sys.exc_info()[2]) # turn unpack into a true/false value if isinstance(details['unpack'], str): details['unpack'] = details['unpack'].lower() == 'true' # If no ID is set, the add-on is invalid if details.get('id') is None: raise AddonFormatError('Add-on id could not be found.') return details
def _addon_details(self, addon_path): """ Returns a dictionary of details about the addon. :param addon_path: path to the add-on directory or XPI Returns:: {'id': u'rainbow@colors.org', # id of the addon 'version': u'1.4', # version of the addon 'name': u'Rainbow', # name of the addon 'unpack': False } # whether to unpack the addon """ details = { 'id': None, 'unpack': False, 'name': None, 'version': None } def get_namespace_id(doc, url): attributes = doc.documentElement.attributes namespace = "" for i in range(attributes.length): if attributes.item(i).value == url: if ":" in attributes.item(i).name: # If the namespace is not the default one remove 'xlmns:' namespace = attributes.item(i).name.split(':')[1] + ":" break return namespace def get_text(element): """Retrieve the text value of a given node""" rc = [] for node in element.childNodes: if node.nodeType == node.TEXT_NODE: rc.append(node.data) return ''.join(rc).strip() def parse_manifest_json(content): """Extracts the details from the contents of a WebExtensions `manifest.json` file.""" manifest = json.loads(content) try: id = manifest['applications']['gecko']['id'] except KeyError: id = manifest['name'].replace(" ", "") + "@" + manifest['version'] return { 'id': id, 'version': manifest['version'], 'name': manifest['version'], 'unpack': False, } if not os.path.exists(addon_path): raise IOError('Add-on path does not exist: %s' % addon_path) try: if zipfile.is_zipfile(addon_path): # Bug 944361 - We cannot use 'with' together with zipFile because # it will cause an exception thrown in Python 2.6. try: compressed_file = zipfile.ZipFile(addon_path, 'r') if 'manifest.json' in compressed_file.namelist(): return parse_manifest_json(compressed_file.read('manifest.json')) manifest = compressed_file.read('install.rdf') finally: compressed_file.close() elif os.path.isdir(addon_path): manifest_json_filename = os.path.join(addon_path, 'manifest.json') if os.path.exists(manifest_json_filename): with open(manifest_json_filename, 'r') as f: return parse_manifest_json(f.read()) with open(os.path.join(addon_path, 'install.rdf'), 'r') as f: manifest = f.read() else: raise IOError('Add-on path is neither an XPI nor a directory: %s' % addon_path) except (IOError, KeyError) as e: raise AddonFormatError(str(e), sys.exc_info()[2]) try: doc = minidom.parseString(manifest) # Get the namespaces abbreviations em = get_namespace_id(doc, 'http://www.mozilla.org/2004/em-rdf#') rdf = get_namespace_id(doc, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#') description = doc.getElementsByTagName(rdf + 'Description').item(0) if description is None: description = doc.getElementsByTagName('Description').item(0) for node in description.childNodes: # Remove the namespace prefix from the tag for comparison entry = node.nodeName.replace(em, "") if entry in details.keys(): details.update({entry: get_text(node)}) if details.get('id') is None: for i in range(description.attributes.length): attribute = description.attributes.item(i) if attribute.name == em + 'id': details.update({'id': attribute.value}) except Exception as e: raise AddonFormatError(str(e), sys.exc_info()[2]) # turn unpack into a true/false value if isinstance(details['unpack'], str): details['unpack'] = details['unpack'].lower() == 'true' # If no ID is set, the add-on is invalid if details.get('id') is None: raise AddonFormatError('Add-on id could not be found.') return details
[ "Returns", "a", "dictionary", "of", "details", "about", "the", "addon", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_profile.py#L251-L364
[ "def", "_addon_details", "(", "self", ",", "addon_path", ")", ":", "details", "=", "{", "'id'", ":", "None", ",", "'unpack'", ":", "False", ",", "'name'", ":", "None", ",", "'version'", ":", "None", "}", "def", "get_namespace_id", "(", "doc", ",", "url", ")", ":", "attributes", "=", "doc", ".", "documentElement", ".", "attributes", "namespace", "=", "\"\"", "for", "i", "in", "range", "(", "attributes", ".", "length", ")", ":", "if", "attributes", ".", "item", "(", "i", ")", ".", "value", "==", "url", ":", "if", "\":\"", "in", "attributes", ".", "item", "(", "i", ")", ".", "name", ":", "# If the namespace is not the default one remove 'xlmns:'", "namespace", "=", "attributes", ".", "item", "(", "i", ")", ".", "name", ".", "split", "(", "':'", ")", "[", "1", "]", "+", "\":\"", "break", "return", "namespace", "def", "get_text", "(", "element", ")", ":", "\"\"\"Retrieve the text value of a given node\"\"\"", "rc", "=", "[", "]", "for", "node", "in", "element", ".", "childNodes", ":", "if", "node", ".", "nodeType", "==", "node", ".", "TEXT_NODE", ":", "rc", ".", "append", "(", "node", ".", "data", ")", "return", "''", ".", "join", "(", "rc", ")", ".", "strip", "(", ")", "def", "parse_manifest_json", "(", "content", ")", ":", "\"\"\"Extracts the details from the contents of a WebExtensions `manifest.json` file.\"\"\"", "manifest", "=", "json", ".", "loads", "(", "content", ")", "try", ":", "id", "=", "manifest", "[", "'applications'", "]", "[", "'gecko'", "]", "[", "'id'", "]", "except", "KeyError", ":", "id", "=", "manifest", "[", "'name'", "]", ".", "replace", "(", "\" \"", ",", "\"\"", ")", "+", "\"@\"", "+", "manifest", "[", "'version'", "]", "return", "{", "'id'", ":", "id", ",", "'version'", ":", "manifest", "[", "'version'", "]", ",", "'name'", ":", "manifest", "[", "'version'", "]", ",", "'unpack'", ":", "False", ",", "}", "if", "not", "os", ".", "path", ".", "exists", "(", "addon_path", ")", ":", "raise", "IOError", "(", "'Add-on path does not exist: %s'", "%", "addon_path", ")", "try", ":", "if", "zipfile", ".", "is_zipfile", "(", "addon_path", ")", ":", "# Bug 944361 - We cannot use 'with' together with zipFile because", "# it will cause an exception thrown in Python 2.6.", "try", ":", "compressed_file", "=", "zipfile", ".", "ZipFile", "(", "addon_path", ",", "'r'", ")", "if", "'manifest.json'", "in", "compressed_file", ".", "namelist", "(", ")", ":", "return", "parse_manifest_json", "(", "compressed_file", ".", "read", "(", "'manifest.json'", ")", ")", "manifest", "=", "compressed_file", ".", "read", "(", "'install.rdf'", ")", "finally", ":", "compressed_file", ".", "close", "(", ")", "elif", "os", ".", "path", ".", "isdir", "(", "addon_path", ")", ":", "manifest_json_filename", "=", "os", ".", "path", ".", "join", "(", "addon_path", ",", "'manifest.json'", ")", "if", "os", ".", "path", ".", "exists", "(", "manifest_json_filename", ")", ":", "with", "open", "(", "manifest_json_filename", ",", "'r'", ")", "as", "f", ":", "return", "parse_manifest_json", "(", "f", ".", "read", "(", ")", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "addon_path", ",", "'install.rdf'", ")", ",", "'r'", ")", "as", "f", ":", "manifest", "=", "f", ".", "read", "(", ")", "else", ":", "raise", "IOError", "(", "'Add-on path is neither an XPI nor a directory: %s'", "%", "addon_path", ")", "except", "(", "IOError", ",", "KeyError", ")", "as", "e", ":", "raise", "AddonFormatError", "(", "str", "(", "e", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "try", ":", "doc", "=", "minidom", ".", "parseString", "(", "manifest", ")", "# Get the namespaces abbreviations", "em", "=", "get_namespace_id", "(", "doc", ",", "'http://www.mozilla.org/2004/em-rdf#'", ")", "rdf", "=", "get_namespace_id", "(", "doc", ",", "'http://www.w3.org/1999/02/22-rdf-syntax-ns#'", ")", "description", "=", "doc", ".", "getElementsByTagName", "(", "rdf", "+", "'Description'", ")", ".", "item", "(", "0", ")", "if", "description", "is", "None", ":", "description", "=", "doc", ".", "getElementsByTagName", "(", "'Description'", ")", ".", "item", "(", "0", ")", "for", "node", "in", "description", ".", "childNodes", ":", "# Remove the namespace prefix from the tag for comparison", "entry", "=", "node", ".", "nodeName", ".", "replace", "(", "em", ",", "\"\"", ")", "if", "entry", "in", "details", ".", "keys", "(", ")", ":", "details", ".", "update", "(", "{", "entry", ":", "get_text", "(", "node", ")", "}", ")", "if", "details", ".", "get", "(", "'id'", ")", "is", "None", ":", "for", "i", "in", "range", "(", "description", ".", "attributes", ".", "length", ")", ":", "attribute", "=", "description", ".", "attributes", ".", "item", "(", "i", ")", "if", "attribute", ".", "name", "==", "em", "+", "'id'", ":", "details", ".", "update", "(", "{", "'id'", ":", "attribute", ".", "value", "}", ")", "except", "Exception", "as", "e", ":", "raise", "AddonFormatError", "(", "str", "(", "e", ")", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "# turn unpack into a true/false value", "if", "isinstance", "(", "details", "[", "'unpack'", "]", ",", "str", ")", ":", "details", "[", "'unpack'", "]", "=", "details", "[", "'unpack'", "]", ".", "lower", "(", ")", "==", "'true'", "# If no ID is set, the add-on is invalid", "if", "details", ".", "get", "(", "'id'", ")", "is", "None", ":", "raise", "AddonFormatError", "(", "'Add-on id could not be found.'", ")", "return", "details" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.submit
Submits a form.
py/selenium/webdriver/remote/webelement.py
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)) { arguments[0].submit() }", form) else: self._execute(Command.SUBMIT_ELEMENT)
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)) { arguments[0].submit() }", form) else: self._execute(Command.SUBMIT_ELEMENT)
[ "Submits", "a", "form", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L82-L91
[ "def", "submit", "(", "self", ")", ":", "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)) { arguments[0].submit() }\"", ",", "form", ")", "else", ":", "self", ".", "_execute", "(", "Command", ".", "SUBMIT_ELEMENT", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.get_property
Gets the given property of the element. :Args: - name - Name of the property to retrieve. :Usage: :: text_length = target_element.get_property("text_length")
py/selenium/webdriver/remote/webelement.py
def get_property(self, name): """ Gets the given property of the element. :Args: - name - Name of the property to retrieve. :Usage: :: text_length = target_element.get_property("text_length") """ 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, name)
def get_property(self, name): """ Gets the given property of the element. :Args: - name - Name of the property to retrieve. :Usage: :: text_length = target_element.get_property("text_length") """ 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, name)
[ "Gets", "the", "given", "property", "of", "the", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L97-L113
[ "def", "get_property", "(", "self", ",", "name", ")", ":", "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", ",", "name", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.get_attribute
Gets the given attribute or property of the element. This method will first try to return the value of a property with the given name. If a property with that name doesn't exist, it returns the value of the attribute with the same name. If there's no attribute with that name, ``None`` is returned. Values which are considered truthy, that is equals "true" or "false", are returned as booleans. All other non-``None`` values are returned as strings. For attributes or properties which do not exist, ``None`` is returned. :Args: - name - Name of the attribute/property to retrieve. Example:: # Check if the "active" CSS class is applied to an element. is_active = "active" in target_element.get_attribute("class")
py/selenium/webdriver/remote/webelement.py
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 given name. If a property with that name doesn't exist, it returns the value of the attribute with the same name. If there's no attribute with that name, ``None`` is returned. Values which are considered truthy, that is equals "true" or "false", are returned as booleans. All other non-``None`` values are returned as strings. For attributes or properties which do not exist, ``None`` is returned. :Args: - name - Name of the attribute/property to retrieve. Example:: # Check if the "active" CSS class is applied to an element. is_active = "active" in target_element.get_attribute("class") """ 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}) attributeValue = resp.get('value') if attributeValue is not None: if name != 'value' and attributeValue.lower() in ('true', 'false'): attributeValue = attributeValue.lower() return attributeValue
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 given name. If a property with that name doesn't exist, it returns the value of the attribute with the same name. If there's no attribute with that name, ``None`` is returned. Values which are considered truthy, that is equals "true" or "false", are returned as booleans. All other non-``None`` values are returned as strings. For attributes or properties which do not exist, ``None`` is returned. :Args: - name - Name of the attribute/property to retrieve. Example:: # Check if the "active" CSS class is applied to an element. is_active = "active" in target_element.get_attribute("class") """ 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}) attributeValue = resp.get('value') if attributeValue is not None: if name != 'value' and attributeValue.lower() in ('true', 'false'): attributeValue = attributeValue.lower() return attributeValue
[ "Gets", "the", "given", "attribute", "or", "property", "of", "the", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L115-L149
[ "def", "get_attribute", "(", "self", ",", "name", ")", ":", "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", "}", ")", "attributeValue", "=", "resp", ".", "get", "(", "'value'", ")", "if", "attributeValue", "is", "not", "None", ":", "if", "name", "!=", "'value'", "and", "attributeValue", ".", "lower", "(", ")", "in", "(", "'true'", ",", "'false'", ")", ":", "attributeValue", "=", "attributeValue", ".", "lower", "(", ")", "return", "attributeValue" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.send_keys
Simulates typing into the element. :Args: - value - A string for typing, or setting form fields. For setting file inputs, this could be a local file path. Use this to send simple key events or to fill out form fields:: form_textfield = driver.find_element_by_name('username') form_textfield.send_keys("admin") This can also be used to set file inputs. :: file_input = driver.find_element_by_name('profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif"))
py/selenium/webdriver/remote/webelement.py
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 could be a local file path. Use this to send simple key events or to fill out form fields:: form_textfield = driver.find_element_by_name('username') form_textfield.send_keys("admin") This can also be used to set file inputs. :: file_input = driver.find_element_by_name('profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif")) """ # 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) self._execute(Command.SEND_KEYS_TO_ELEMENT, {'text': "".join(keys_to_typing(value)), 'value': keys_to_typing(value)})
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 could be a local file path. Use this to send simple key events or to fill out form fields:: form_textfield = driver.find_element_by_name('username') form_textfield.send_keys("admin") This can also be used to set file inputs. :: file_input = driver.find_element_by_name('profilePic') file_input.send_keys("path/to/profilepic.gif") # Generally it's better to wrap the file path in one of the methods # in os.path to return the actual path to support cross OS testing. # file_input.send_keys(os.path.abspath("path/to/profilepic.gif")) """ # 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) self._execute(Command.SEND_KEYS_TO_ELEMENT, {'text': "".join(keys_to_typing(value)), 'value': keys_to_typing(value)})
[ "Simulates", "typing", "into", "the", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L480-L512
[ "def", "send_keys", "(", "self", ",", "*", "value", ")", ":", "# 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", ")", "self", ".", "_execute", "(", "Command", ".", "SEND_KEYS_TO_ELEMENT", ",", "{", "'text'", ":", "\"\"", ".", "join", "(", "keys_to_typing", "(", "value", ")", ")", ",", "'value'", ":", "keys_to_typing", "(", "value", ")", "}", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.is_displayed
Whether the element is visible to a user.
py/selenium/webdriver/remote/webelement.py
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_DISPLAYED)['value']
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_DISPLAYED)['value']
[ "Whether", "the", "element", "is", "visible", "to", "a", "user", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L515-L523
[ "def", "is_displayed", "(", "self", ")", ":", "# 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_DISPLAYED", ")", "[", "'value'", "]" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.location_once_scrolled_into_view
THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view. Returns the top lefthand corner location on the screen, or ``None`` if the element is not visible.
py/selenium/webdriver/remote/webelement.py
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 click it. This method should cause the element to be scrolled into view. Returns the top lefthand corner location on the screen, or ``None`` if the element is not visible. """ 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_loc['y'])} else: return self._execute(Command.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW)['value']
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 click it. This method should cause the element to be scrolled into view. Returns the top lefthand corner location on the screen, or ``None`` if the element is not visible. """ 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_loc['y'])} else: return self._execute(Command.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW)['value']
[ "THIS", "PROPERTY", "MAY", "CHANGE", "WITHOUT", "WARNING", ".", "Use", "this", "to", "discover", "where", "on", "the", "screen", "an", "element", "is", "so", "that", "we", "can", "click", "it", ".", "This", "method", "should", "cause", "the", "element", "to", "be", "scrolled", "into", "view", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L526-L542
[ "def", "location_once_scrolled_into_view", "(", "self", ")", ":", "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_loc", "[", "'y'", "]", ")", "}", "else", ":", "return", "self", ".", "_execute", "(", "Command", ".", "GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW", ")", "[", "'value'", "]" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.size
The size of the element.
py/selenium/webdriver/remote/webelement.py
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
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
[ "The", "size", "of", "the", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L545-L554
[ "def", "size", "(", "self", ")", ":", "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" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.location
The location of the element in the renderable canvas.
py/selenium/webdriver/remote/webelement.py
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
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
[ "The", "location", "of", "the", "element", "in", "the", "renderable", "canvas", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L562-L570
[ "def", "location", "(", "self", ")", ":", "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" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.rect
A dictionary with the size and location of the element.
py/selenium/webdriver/remote/webelement.py
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
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
[ "A", "dictionary", "with", "the", "size", "and", "location", "of", "the", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L573-L580
[ "def", "rect", "(", "self", ")", ":", "if", "self", ".", "_w3c", ":", "return", "self", ".", "_execute", "(", "Command", ".", "GET_ELEMENT_RECT", ")", "[", "'value'", "]", "else", ":", "rect", "=", "self", ".", "size", ".", "copy", "(", ")", "rect", ".", "update", "(", "self", ".", "location", ")", "return", "rect" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.screenshot
Saves a screenshot of the current element to a PNG image file. Returns False if there is any IOError, else returns True. Use full paths in your filename. :Args: - filename: The full path you wish to save your screenshot to. This should end with a `.png` extension. :Usage: :: element.screenshot('/Screenshots/foo.png')
py/selenium/webdriver/remote/webelement.py
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 full paths in your filename. :Args: - filename: The full path you wish to save your screenshot to. This should end with a `.png` extension. :Usage: :: element.screenshot('/Screenshots/foo.png') """ 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: f.write(png) except IOError: return False finally: del png return True
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 full paths in your filename. :Args: - filename: The full path you wish to save your screenshot to. This should end with a `.png` extension. :Usage: :: element.screenshot('/Screenshots/foo.png') """ 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: f.write(png) except IOError: return False finally: del png return True
[ "Saves", "a", "screenshot", "of", "the", "current", "element", "to", "a", "PNG", "image", "file", ".", "Returns", "False", "if", "there", "is", "any", "IOError", "else", "returns", "True", ".", "Use", "full", "paths", "in", "your", "filename", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L606-L632
[ "def", "screenshot", "(", "self", ",", "filename", ")", ":", "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", ":", "f", ".", "write", "(", "png", ")", "except", "IOError", ":", "return", "False", "finally", ":", "del", "png", "return", "True" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement._execute
Executes a command against the underlying HTML element. Args: command: The name of the command to _execute as a string. params: A dictionary of named parameters to send with the command. Returns: The command's JSON response loaded into a dictionary object.
py/selenium/webdriver/remote/webelement.py
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 string. params: A dictionary of named parameters to send with the command. Returns: The command's JSON response loaded into a dictionary object. """ if not params: params = {} params['id'] = self._id return self._parent.execute(command, params)
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 string. params: A dictionary of named parameters to send with the command. Returns: The command's JSON response loaded into a dictionary object. """ if not params: params = {} params['id'] = self._id return self._parent.execute(command, params)
[ "Executes", "a", "command", "against", "the", "underlying", "HTML", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L659-L672
[ "def", "_execute", "(", "self", ",", "command", ",", "params", "=", "None", ")", ":", "if", "not", "params", ":", "params", "=", "{", "}", "params", "[", "'id'", "]", "=", "self", ".", "_id", "return", "self", ".", "_parent", ".", "execute", "(", "command", ",", "params", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.find_element
Find an element given a By strategy and locator. Prefer the find_element_by_* methods when possible. :Usage: :: element = element.find_element(By.ID, 'foo') :rtype: WebElement
py/selenium/webdriver/remote/webelement.py
def find_element(self, by=By.ID, value=None): """ Find an element given a By strategy and locator. Prefer the find_element_by_* methods when possible. :Usage: :: element = element.find_element(By.ID, 'foo') :rtype: WebElement """ if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENT, {"using": by, "value": value})['value']
def find_element(self, by=By.ID, value=None): """ Find an element given a By strategy and locator. Prefer the find_element_by_* methods when possible. :Usage: :: element = element.find_element(By.ID, 'foo') :rtype: WebElement """ if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENT, {"using": by, "value": value})['value']
[ "Find", "an", "element", "given", "a", "By", "strategy", "and", "locator", ".", "Prefer", "the", "find_element_by_", "*", "methods", "when", "possible", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L674-L700
[ "def", "find_element", "(", "self", ",", "by", "=", "By", ".", "ID", ",", "value", "=", "None", ")", ":", "if", "self", ".", "_w3c", ":", "if", "by", "==", "By", ".", "ID", ":", "by", "=", "By", ".", "CSS_SELECTOR", "value", "=", "'[id=\"%s\"]'", "%", "value", "elif", "by", "==", "By", ".", "TAG_NAME", ":", "by", "=", "By", ".", "CSS_SELECTOR", "elif", "by", "==", "By", ".", "CLASS_NAME", ":", "by", "=", "By", ".", "CSS_SELECTOR", "value", "=", "\".%s\"", "%", "value", "elif", "by", "==", "By", ".", "NAME", ":", "by", "=", "By", ".", "CSS_SELECTOR", "value", "=", "'[name=\"%s\"]'", "%", "value", "return", "self", ".", "_execute", "(", "Command", ".", "FIND_CHILD_ELEMENT", ",", "{", "\"using\"", ":", "by", ",", "\"value\"", ":", "value", "}", ")", "[", "'value'", "]" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebElement.find_elements
Find elements given a By strategy and locator. Prefer the find_elements_by_* methods when possible. :Usage: :: element = element.find_elements(By.CLASS_NAME, 'foo') :rtype: list of WebElement
py/selenium/webdriver/remote/webelement.py
def find_elements(self, by=By.ID, value=None): """ Find elements given a By strategy and locator. Prefer the find_elements_by_* methods when possible. :Usage: :: element = element.find_elements(By.CLASS_NAME, 'foo') :rtype: list of WebElement """ if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENTS, {"using": by, "value": value})['value']
def find_elements(self, by=By.ID, value=None): """ Find elements given a By strategy and locator. Prefer the find_elements_by_* methods when possible. :Usage: :: element = element.find_elements(By.CLASS_NAME, 'foo') :rtype: list of WebElement """ if self._w3c: if by == By.ID: by = By.CSS_SELECTOR value = '[id="%s"]' % value elif by == By.TAG_NAME: by = By.CSS_SELECTOR elif by == By.CLASS_NAME: by = By.CSS_SELECTOR value = ".%s" % value elif by == By.NAME: by = By.CSS_SELECTOR value = '[name="%s"]' % value return self._execute(Command.FIND_CHILD_ELEMENTS, {"using": by, "value": value})['value']
[ "Find", "elements", "given", "a", "By", "strategy", "and", "locator", ".", "Prefer", "the", "find_elements_by_", "*", "methods", "when", "possible", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/webelement.py#L702-L728
[ "def", "find_elements", "(", "self", ",", "by", "=", "By", ".", "ID", ",", "value", "=", "None", ")", ":", "if", "self", ".", "_w3c", ":", "if", "by", "==", "By", ".", "ID", ":", "by", "=", "By", ".", "CSS_SELECTOR", "value", "=", "'[id=\"%s\"]'", "%", "value", "elif", "by", "==", "By", ".", "TAG_NAME", ":", "by", "=", "By", ".", "CSS_SELECTOR", "elif", "by", "==", "By", ".", "CLASS_NAME", ":", "by", "=", "By", ".", "CSS_SELECTOR", "value", "=", "\".%s\"", "%", "value", "elif", "by", "==", "By", ".", "NAME", ":", "by", "=", "By", ".", "CSS_SELECTOR", "value", "=", "'[name=\"%s\"]'", "%", "value", "return", "self", ".", "_execute", "(", "Command", ".", "FIND_CHILD_ELEMENTS", ",", "{", "\"using\"", ":", "by", ",", "\"value\"", ":", "value", "}", ")", "[", "'value'", "]" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
WebDriver.quit
Closes the browser and shuts down the WebKitGTKDriver executable that is started when starting the WebKitGTKDriver
py/selenium/webdriver/webkitgtk/webdriver.py
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()
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()
[ "Closes", "the", "browser", "and", "shuts", "down", "the", "WebKitGTKDriver", "executable", "that", "is", "started", "when", "starting", "the", "WebKitGTKDriver" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/webkitgtk/webdriver.py#L68-L78
[ "def", "quit", "(", "self", ")", ":", "try", ":", "RemoteWebDriver", ".", "quit", "(", "self", ")", "except", "http_client", ".", "BadStatusLine", ":", "pass", "finally", ":", "self", ".", "service", ".", "stop", "(", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Service.start
Starts the Service. :Exceptions: - WebDriverException : Raised either when it can't start the service or when it can't connect to the service
py/selenium/webdriver/common/service.py
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 service """ 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, stderr=self.log_file, stdin=PIPE) except TypeError: raise except OSError as err: if err.errno == errno.ENOENT: raise WebDriverException( "'%s' executable needs to be in PATH. %s" % ( os.path.basename(self.path), self.start_error_message) ) elif err.errno == errno.EACCES: raise WebDriverException( "'%s' executable may have wrong permissions. %s" % ( os.path.basename(self.path), self.start_error_message) ) else: raise except Exception as e: raise WebDriverException( "The executable %s needs to be available in the path. %s\n%s" % (os.path.basename(self.path), self.start_error_message, str(e))) count = 0 while True: self.assert_process_still_running() if self.is_connectable(): break count += 1 time.sleep(1) if count == 30: raise WebDriverException("Can not connect to the Service %s" % self.path)
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 service """ 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, stderr=self.log_file, stdin=PIPE) except TypeError: raise except OSError as err: if err.errno == errno.ENOENT: raise WebDriverException( "'%s' executable needs to be in PATH. %s" % ( os.path.basename(self.path), self.start_error_message) ) elif err.errno == errno.EACCES: raise WebDriverException( "'%s' executable may have wrong permissions. %s" % ( os.path.basename(self.path), self.start_error_message) ) else: raise except Exception as e: raise WebDriverException( "The executable %s needs to be available in the path. %s\n%s" % (os.path.basename(self.path), self.start_error_message, str(e))) count = 0 while True: self.assert_process_still_running() if self.is_connectable(): break count += 1 time.sleep(1) if count == 30: raise WebDriverException("Can not connect to the Service %s" % self.path)
[ "Starts", "the", "Service", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/service.py#L61-L104
[ "def", "start", "(", "self", ")", ":", "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", ",", "stderr", "=", "self", ".", "log_file", ",", "stdin", "=", "PIPE", ")", "except", "TypeError", ":", "raise", "except", "OSError", "as", "err", ":", "if", "err", ".", "errno", "==", "errno", ".", "ENOENT", ":", "raise", "WebDriverException", "(", "\"'%s' executable needs to be in PATH. %s\"", "%", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "path", ")", ",", "self", ".", "start_error_message", ")", ")", "elif", "err", ".", "errno", "==", "errno", ".", "EACCES", ":", "raise", "WebDriverException", "(", "\"'%s' executable may have wrong permissions. %s\"", "%", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "path", ")", ",", "self", ".", "start_error_message", ")", ")", "else", ":", "raise", "except", "Exception", "as", "e", ":", "raise", "WebDriverException", "(", "\"The executable %s needs to be available in the path. %s\\n%s\"", "%", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "path", ")", ",", "self", ".", "start_error_message", ",", "str", "(", "e", ")", ")", ")", "count", "=", "0", "while", "True", ":", "self", ".", "assert_process_still_running", "(", ")", "if", "self", ".", "is_connectable", "(", ")", ":", "break", "count", "+=", "1", "time", ".", "sleep", "(", "1", ")", "if", "count", "==", "30", ":", "raise", "WebDriverException", "(", "\"Can not connect to the Service %s\"", "%", "self", ".", "path", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Service.stop
Stops the service.
py/selenium/webdriver/common/service.py
def stop(self): """ Stops the service. """ if self.log_file != PIPE and not (self.log_file == DEVNULL and _HAS_NATIVE_DEVNULL): try: self.log_file.close() except Exception: pass if self.process is None: return try: self.send_remote_shutdown_command() except TypeError: pass try: if self.process: for stream in [self.process.stdin, self.process.stdout, self.process.stderr]: try: stream.close() except AttributeError: pass self.process.terminate() self.process.wait() self.process.kill() self.process = None except OSError: pass
def stop(self): """ Stops the service. """ if self.log_file != PIPE and not (self.log_file == DEVNULL and _HAS_NATIVE_DEVNULL): try: self.log_file.close() except Exception: pass if self.process is None: return try: self.send_remote_shutdown_command() except TypeError: pass try: if self.process: for stream in [self.process.stdin, self.process.stdout, self.process.stderr]: try: stream.close() except AttributeError: pass self.process.terminate() self.process.wait() self.process.kill() self.process = None except OSError: pass
[ "Stops", "the", "service", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/service.py#L137-L169
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "log_file", "!=", "PIPE", "and", "not", "(", "self", ".", "log_file", "==", "DEVNULL", "and", "_HAS_NATIVE_DEVNULL", ")", ":", "try", ":", "self", ".", "log_file", ".", "close", "(", ")", "except", "Exception", ":", "pass", "if", "self", ".", "process", "is", "None", ":", "return", "try", ":", "self", ".", "send_remote_shutdown_command", "(", ")", "except", "TypeError", ":", "pass", "try", ":", "if", "self", ".", "process", ":", "for", "stream", "in", "[", "self", ".", "process", ".", "stdin", ",", "self", ".", "process", ".", "stdout", ",", "self", ".", "process", ".", "stderr", "]", ":", "try", ":", "stream", ".", "close", "(", ")", "except", "AttributeError", ":", "pass", "self", ".", "process", ".", "terminate", "(", ")", "self", ".", "process", ".", "wait", "(", ")", "self", ".", "process", ".", "kill", "(", ")", "self", ".", "process", "=", "None", "except", "OSError", ":", "pass" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxBinary.launch_browser
Launches the browser for the given profile name. It is assumed the profile already exists.
py/selenium/webdriver/firefox/firefox_binary.py
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)
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)
[ "Launches", "the", "browser", "for", "the", "given", "profile", "name", ".", "It", "is", "assumed", "the", "profile", "already", "exists", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_binary.py#L66-L73
[ "def", "launch_browser", "(", "self", ",", "profile", ",", "timeout", "=", "30", ")", ":", "self", ".", "profile", "=", "profile", "self", ".", "_start_from_profile_path", "(", "self", ".", "profile", ".", "path", ")", "self", ".", "_wait_until_connectable", "(", "timeout", "=", "timeout", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxBinary.kill
Kill the browser. This is useful when the browser is stuck.
py/selenium/webdriver/firefox/firefox_binary.py
def kill(self): """Kill the browser. This is useful when the browser is stuck. """ if self.process: self.process.kill() self.process.wait()
def kill(self): """Kill the browser. This is useful when the browser is stuck. """ if self.process: self.process.kill() self.process.wait()
[ "Kill", "the", "browser", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_binary.py#L75-L82
[ "def", "kill", "(", "self", ")", ":", "if", "self", ".", "process", ":", "self", ".", "process", ".", "kill", "(", ")", "self", ".", "process", ".", "wait", "(", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxBinary._wait_until_connectable
Blocks until the extension is connectable in the firefox.
py/selenium/webdriver/firefox/firefox_binary.py
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 specified a log_file in " "the FirefoxBinary constructor, check it for details.") if count >= timeout: self.kill() raise WebDriverException( "Can't load the profile. Possible firefox version mismatch. " "You must use GeckoDriver instead for Firefox 48+. Profile " "Dir: %s If you specified a log_file in the " "FirefoxBinary constructor, check it for details." % (self.profile.path)) count += 1 time.sleep(1) return True
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 specified a log_file in " "the FirefoxBinary constructor, check it for details.") if count >= timeout: self.kill() raise WebDriverException( "Can't load the profile. Possible firefox version mismatch. " "You must use GeckoDriver instead for Firefox 48+. Profile " "Dir: %s If you specified a log_file in the " "FirefoxBinary constructor, check it for details." % (self.profile.path)) count += 1 time.sleep(1) return True
[ "Blocks", "until", "the", "extension", "is", "connectable", "in", "the", "firefox", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_binary.py#L97-L117
[ "def", "_wait_until_connectable", "(", "self", ",", "timeout", "=", "30", ")", ":", "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 specified a log_file in \"", "\"the FirefoxBinary constructor, check it for details.\"", ")", "if", "count", ">=", "timeout", ":", "self", ".", "kill", "(", ")", "raise", "WebDriverException", "(", "\"Can't load the profile. Possible firefox version mismatch. \"", "\"You must use GeckoDriver instead for Firefox 48+. Profile \"", "\"Dir: %s If you specified a log_file in the \"", "\"FirefoxBinary constructor, check it for details.\"", "%", "(", "self", ".", "profile", ".", "path", ")", ")", "count", "+=", "1", "time", ".", "sleep", "(", "1", ")", "return", "True" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxBinary._get_firefox_start_cmd
Return the command to start firefox.
py/selenium/webdriver/firefox/firefox_binary.py
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 elif platform.system() == "Windows": start_cmd = (self._find_exe_in_registry() or self._default_windows_location()) elif platform.system() == 'Java' and os._name == 'nt': start_cmd = self._default_windows_location() else: for ffname in ["firefox", "iceweasel"]: start_cmd = self.which(ffname) if start_cmd is not None: break else: # couldn't find firefox on the system path raise RuntimeError( "Could not find firefox in your system PATH." + " Please specify the firefox binary location or install firefox") return start_cmd
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 elif platform.system() == "Windows": start_cmd = (self._find_exe_in_registry() or self._default_windows_location()) elif platform.system() == 'Java' and os._name == 'nt': start_cmd = self._default_windows_location() else: for ffname in ["firefox", "iceweasel"]: start_cmd = self.which(ffname) if start_cmd is not None: break else: # couldn't find firefox on the system path raise RuntimeError( "Could not find firefox in your system PATH." + " Please specify the firefox binary location or install firefox") return start_cmd
[ "Return", "the", "command", "to", "start", "firefox", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_binary.py#L148-L170
[ "def", "_get_firefox_start_cmd", "(", "self", ")", ":", "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", "elif", "platform", ".", "system", "(", ")", "==", "\"Windows\"", ":", "start_cmd", "=", "(", "self", ".", "_find_exe_in_registry", "(", ")", "or", "self", ".", "_default_windows_location", "(", ")", ")", "elif", "platform", ".", "system", "(", ")", "==", "'Java'", "and", "os", ".", "_name", "==", "'nt'", ":", "start_cmd", "=", "self", ".", "_default_windows_location", "(", ")", "else", ":", "for", "ffname", "in", "[", "\"firefox\"", ",", "\"iceweasel\"", "]", ":", "start_cmd", "=", "self", ".", "which", "(", "ffname", ")", "if", "start_cmd", "is", "not", "None", ":", "break", "else", ":", "# couldn't find firefox on the system path", "raise", "RuntimeError", "(", "\"Could not find firefox in your system PATH.\"", "+", "\" Please specify the firefox binary location or install firefox\"", ")", "return", "start_cmd" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
FirefoxBinary.which
Returns the fully qualified path by searching Path of the given name
py/selenium/webdriver/firefox/firefox_binary.py
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
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
[ "Returns", "the", "fully", "qualified", "path", "by", "searching", "Path", "of", "the", "given", "name" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/firefox/firefox_binary.py#L210-L217
[ "def", "which", "(", "self", ",", "fname", ")", ":", "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" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
RemoteConnection.get_remote_connection_headers
Get headers for remote request. :Args: - parsed_url - The parsed url - keep_alive (Boolean) - Is this a keep-alive connection (default: False)
py/selenium/webdriver/remote/remote_connection.py
def get_remote_connection_headers(cls, parsed_url, keep_alive=False): """ Get headers for remote request. :Args: - parsed_url - The parsed url - keep_alive (Boolean) - Is this a keep-alive connection (default: False) """ 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) } if parsed_url.username: base64string = base64.b64encode('{0.username}:{0.password}'.format(parsed_url).encode()) headers.update({ 'Authorization': 'Basic {}'.format(base64string.decode()) }) if keep_alive: headers.update({ 'Connection': 'keep-alive' }) return headers
def get_remote_connection_headers(cls, parsed_url, keep_alive=False): """ Get headers for remote request. :Args: - parsed_url - The parsed url - keep_alive (Boolean) - Is this a keep-alive connection (default: False) """ 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) } if parsed_url.username: base64string = base64.b64encode('{0.username}:{0.password}'.format(parsed_url).encode()) headers.update({ 'Authorization': 'Basic {}'.format(base64string.decode()) }) if keep_alive: headers.update({ 'Connection': 'keep-alive' }) return headers
[ "Get", "headers", "for", "remote", "request", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/remote_connection.py#L74-L104
[ "def", "get_remote_connection_headers", "(", "cls", ",", "parsed_url", ",", "keep_alive", "=", "False", ")", ":", "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", ")", "}", "if", "parsed_url", ".", "username", ":", "base64string", "=", "base64", ".", "b64encode", "(", "'{0.username}:{0.password}'", ".", "format", "(", "parsed_url", ")", ".", "encode", "(", ")", ")", "headers", ".", "update", "(", "{", "'Authorization'", ":", "'Basic {}'", ".", "format", "(", "base64string", ".", "decode", "(", ")", ")", "}", ")", "if", "keep_alive", ":", "headers", ".", "update", "(", "{", "'Connection'", ":", "'keep-alive'", "}", ")", "return", "headers" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
RemoteConnection.execute
Send a command to the remote server. Any path subtitutions required for the URL mapped to the command should be included in the command parameters. :Args: - command - A string specifying the command to execute. - params - A dictionary of named parameters to send with the command as its JSON payload.
py/selenium/webdriver/remote/remote_connection.py
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 in the command parameters. :Args: - command - A string specifying the command to execute. - params - A dictionary of named parameters to send with the command as its JSON payload. """ 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['sessionId'] data = utils.dump_json(params) url = '%s%s' % (self._url, path) return self._request(command_info[0], url, body=data)
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 in the command parameters. :Args: - command - A string specifying the command to execute. - params - A dictionary of named parameters to send with the command as its JSON payload. """ 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['sessionId'] data = utils.dump_json(params) url = '%s%s' % (self._url, path) return self._request(command_info[0], url, body=data)
[ "Send", "a", "command", "to", "the", "remote", "server", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/remote_connection.py#L356-L375
[ "def", "execute", "(", "self", ",", "command", ",", "params", ")", ":", "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", "[", "'sessionId'", "]", "data", "=", "utils", ".", "dump_json", "(", "params", ")", "url", "=", "'%s%s'", "%", "(", "self", ".", "_url", ",", "path", ")", "return", "self", ".", "_request", "(", "command_info", "[", "0", "]", ",", "url", ",", "body", "=", "data", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
RemoteConnection._request
Send an HTTP request to the remote server. :Args: - method - A string for the HTTP method to send the request with. - url - A string for the URL to send the request to. - body - A string for request body. Ignored unless method is POST or PUT. :Returns: A dictionary with the server's parsed JSON response.
py/selenium/webdriver/remote/remote_connection.py
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 with. - url - A string for the URL to send the request to. - body - A string for request body. Ignored unless method is POST or PUT. :Returns: A dictionary with the server's parsed JSON response. """ 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: resp = self._conn.request(method, url, body=body, headers=headers) statuscode = resp.status else: http = urllib3.PoolManager(timeout=self._timeout) resp = http.request(method, url, body=body, headers=headers) statuscode = resp.status if not hasattr(resp, 'getheader'): if hasattr(resp.headers, 'getheader'): resp.getheader = lambda x: resp.headers.getheader(x) elif hasattr(resp.headers, 'get'): resp.getheader = lambda x: resp.headers.get(x) data = resp.data.decode('UTF-8') try: if 300 <= statuscode < 304: return self._request('GET', resp.getheader('location')) if 399 < statuscode <= 500: return {'status': statuscode, 'value': data} content_type = [] if resp.getheader('Content-Type') is not None: content_type = resp.getheader('Content-Type').split(';') if not any([x.startswith('image/png') for x in content_type]): try: data = utils.load_json(data.strip()) except ValueError: if 199 < statuscode < 300: status = ErrorCode.SUCCESS else: status = ErrorCode.UNKNOWN_ERROR return {'status': status, 'value': data.strip()} # Some of the drivers incorrectly return a response # with no 'value' field when they should return null. if 'value' not in data: data['value'] = None return data else: data = {'status': 0, 'value': data} return data finally: LOGGER.debug("Finished Request") resp.close()
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 with. - url - A string for the URL to send the request to. - body - A string for request body. Ignored unless method is POST or PUT. :Returns: A dictionary with the server's parsed JSON response. """ 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: resp = self._conn.request(method, url, body=body, headers=headers) statuscode = resp.status else: http = urllib3.PoolManager(timeout=self._timeout) resp = http.request(method, url, body=body, headers=headers) statuscode = resp.status if not hasattr(resp, 'getheader'): if hasattr(resp.headers, 'getheader'): resp.getheader = lambda x: resp.headers.getheader(x) elif hasattr(resp.headers, 'get'): resp.getheader = lambda x: resp.headers.get(x) data = resp.data.decode('UTF-8') try: if 300 <= statuscode < 304: return self._request('GET', resp.getheader('location')) if 399 < statuscode <= 500: return {'status': statuscode, 'value': data} content_type = [] if resp.getheader('Content-Type') is not None: content_type = resp.getheader('Content-Type').split(';') if not any([x.startswith('image/png') for x in content_type]): try: data = utils.load_json(data.strip()) except ValueError: if 199 < statuscode < 300: status = ErrorCode.SUCCESS else: status = ErrorCode.UNKNOWN_ERROR return {'status': status, 'value': data.strip()} # Some of the drivers incorrectly return a response # with no 'value' field when they should return null. if 'value' not in data: data['value'] = None return data else: data = {'status': 0, 'value': data} return data finally: LOGGER.debug("Finished Request") resp.close()
[ "Send", "an", "HTTP", "request", "to", "the", "remote", "server", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/remote/remote_connection.py#L377-L442
[ "def", "_request", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ")", ":", "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", ":", "resp", "=", "self", ".", "_conn", ".", "request", "(", "method", ",", "url", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "statuscode", "=", "resp", ".", "status", "else", ":", "http", "=", "urllib3", ".", "PoolManager", "(", "timeout", "=", "self", ".", "_timeout", ")", "resp", "=", "http", ".", "request", "(", "method", ",", "url", ",", "body", "=", "body", ",", "headers", "=", "headers", ")", "statuscode", "=", "resp", ".", "status", "if", "not", "hasattr", "(", "resp", ",", "'getheader'", ")", ":", "if", "hasattr", "(", "resp", ".", "headers", ",", "'getheader'", ")", ":", "resp", ".", "getheader", "=", "lambda", "x", ":", "resp", ".", "headers", ".", "getheader", "(", "x", ")", "elif", "hasattr", "(", "resp", ".", "headers", ",", "'get'", ")", ":", "resp", ".", "getheader", "=", "lambda", "x", ":", "resp", ".", "headers", ".", "get", "(", "x", ")", "data", "=", "resp", ".", "data", ".", "decode", "(", "'UTF-8'", ")", "try", ":", "if", "300", "<=", "statuscode", "<", "304", ":", "return", "self", ".", "_request", "(", "'GET'", ",", "resp", ".", "getheader", "(", "'location'", ")", ")", "if", "399", "<", "statuscode", "<=", "500", ":", "return", "{", "'status'", ":", "statuscode", ",", "'value'", ":", "data", "}", "content_type", "=", "[", "]", "if", "resp", ".", "getheader", "(", "'Content-Type'", ")", "is", "not", "None", ":", "content_type", "=", "resp", ".", "getheader", "(", "'Content-Type'", ")", ".", "split", "(", "';'", ")", "if", "not", "any", "(", "[", "x", ".", "startswith", "(", "'image/png'", ")", "for", "x", "in", "content_type", "]", ")", ":", "try", ":", "data", "=", "utils", ".", "load_json", "(", "data", ".", "strip", "(", ")", ")", "except", "ValueError", ":", "if", "199", "<", "statuscode", "<", "300", ":", "status", "=", "ErrorCode", ".", "SUCCESS", "else", ":", "status", "=", "ErrorCode", ".", "UNKNOWN_ERROR", "return", "{", "'status'", ":", "status", ",", "'value'", ":", "data", ".", "strip", "(", ")", "}", "# Some of the drivers incorrectly return a response", "# with no 'value' field when they should return null.", "if", "'value'", "not", "in", "data", ":", "data", "[", "'value'", "]", "=", "None", "return", "data", "else", ":", "data", "=", "{", "'status'", ":", "0", ",", "'value'", ":", "data", "}", "return", "data", "finally", ":", "LOGGER", ".", "debug", "(", "\"Finished Request\"", ")", "resp", ".", "close", "(", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Select.all_selected_options
Returns a list of all selected options belonging to this select tag
py/selenium/webdriver/support/select.py
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
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
[ "Returns", "a", "list", "of", "all", "selected", "options", "belonging", "to", "this", "select", "tag" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/select.py#L50-L56
[ "def", "all_selected_options", "(", "self", ")", ":", "ret", "=", "[", "]", "for", "opt", "in", "self", ".", "options", ":", "if", "opt", ".", "is_selected", "(", ")", ":", "ret", ".", "append", "(", "opt", ")", "return", "ret" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Select.select_by_value
Select all options that have a value matching the argument. That is, when given "foo" this would select an option like: <option value="foo">Bar</option> :Args: - value - The value to match against throws NoSuchElementException If there is no option with specified value in SELECT
py/selenium/webdriver/support/select.py
def select_by_value(self, value): """Select all options that have a value matching the argument. That is, when given "foo" this would select an option like: <option value="foo">Bar</option> :Args: - value - The value to match against throws NoSuchElementException If there is no option with specified value in SELECT """ css = "option[value =%s]" % self._escapeString(value) opts = self._el.find_elements(By.CSS_SELECTOR, css) matched = False for opt in opts: self._setSelected(opt) if not self.is_multiple: return matched = True if not matched: raise NoSuchElementException("Cannot locate option with value: %s" % value)
def select_by_value(self, value): """Select all options that have a value matching the argument. That is, when given "foo" this would select an option like: <option value="foo">Bar</option> :Args: - value - The value to match against throws NoSuchElementException If there is no option with specified value in SELECT """ css = "option[value =%s]" % self._escapeString(value) opts = self._el.find_elements(By.CSS_SELECTOR, css) matched = False for opt in opts: self._setSelected(opt) if not self.is_multiple: return matched = True if not matched: raise NoSuchElementException("Cannot locate option with value: %s" % value)
[ "Select", "all", "options", "that", "have", "a", "value", "matching", "the", "argument", ".", "That", "is", "when", "given", "foo", "this", "would", "select", "an", "option", "like", ":" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/select.py#L67-L87
[ "def", "select_by_value", "(", "self", ",", "value", ")", ":", "css", "=", "\"option[value =%s]\"", "%", "self", ".", "_escapeString", "(", "value", ")", "opts", "=", "self", ".", "_el", ".", "find_elements", "(", "By", ".", "CSS_SELECTOR", ",", "css", ")", "matched", "=", "False", "for", "opt", "in", "opts", ":", "self", ".", "_setSelected", "(", "opt", ")", "if", "not", "self", ".", "is_multiple", ":", "return", "matched", "=", "True", "if", "not", "matched", ":", "raise", "NoSuchElementException", "(", "\"Cannot locate option with value: %s\"", "%", "value", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Select.select_by_index
Select the option at the given index. This is done by examing the "index" attribute of an element, and not merely by counting. :Args: - index - The option at this index will be selected throws NoSuchElementException If there is no option with specified index in SELECT
py/selenium/webdriver/support/select.py
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 counting. :Args: - index - The option at this index will be selected throws NoSuchElementException If there is no option with specified index in SELECT """ 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)
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 counting. :Args: - index - The option at this index will be selected throws NoSuchElementException If there is no option with specified index in SELECT """ 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)
[ "Select", "the", "option", "at", "the", "given", "index", ".", "This", "is", "done", "by", "examing", "the", "index", "attribute", "of", "an", "element", "and", "not", "merely", "by", "counting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/select.py#L89-L103
[ "def", "select_by_index", "(", "self", ",", "index", ")", ":", "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", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Select.select_by_visible_text
Select all options that display text matching the argument. That is, when given "Bar" this would select an option like: <option value="foo">Bar</option> :Args: - text - The visible text to match against throws NoSuchElementException If there is no option with specified text in SELECT
py/selenium/webdriver/support/select.py
def select_by_visible_text(self, text): """Select all options that display text matching the argument. That is, when given "Bar" this would select an option like: <option value="foo">Bar</option> :Args: - text - The visible text to match against throws NoSuchElementException If there is no option with specified text in SELECT """ xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text) opts = self._el.find_elements(By.XPATH, xpath) matched = False for opt in opts: self._setSelected(opt) if not self.is_multiple: return matched = True if len(opts) == 0 and " " in text: subStringWithoutSpace = self._get_longest_token(text) if subStringWithoutSpace == "": candidates = self.options else: xpath = ".//option[contains(.,%s)]" % self._escapeString(subStringWithoutSpace) candidates = self._el.find_elements(By.XPATH, xpath) for candidate in candidates: if text == candidate.text: self._setSelected(candidate) if not self.is_multiple: return matched = True if not matched: raise NoSuchElementException("Could not locate element with visible text: %s" % text)
def select_by_visible_text(self, text): """Select all options that display text matching the argument. That is, when given "Bar" this would select an option like: <option value="foo">Bar</option> :Args: - text - The visible text to match against throws NoSuchElementException If there is no option with specified text in SELECT """ xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text) opts = self._el.find_elements(By.XPATH, xpath) matched = False for opt in opts: self._setSelected(opt) if not self.is_multiple: return matched = True if len(opts) == 0 and " " in text: subStringWithoutSpace = self._get_longest_token(text) if subStringWithoutSpace == "": candidates = self.options else: xpath = ".//option[contains(.,%s)]" % self._escapeString(subStringWithoutSpace) candidates = self._el.find_elements(By.XPATH, xpath) for candidate in candidates: if text == candidate.text: self._setSelected(candidate) if not self.is_multiple: return matched = True if not matched: raise NoSuchElementException("Could not locate element with visible text: %s" % text)
[ "Select", "all", "options", "that", "display", "text", "matching", "the", "argument", ".", "That", "is", "when", "given", "Bar", "this", "would", "select", "an", "option", "like", ":" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/select.py#L105-L140
[ "def", "select_by_visible_text", "(", "self", ",", "text", ")", ":", "xpath", "=", "\".//option[normalize-space(.) = %s]\"", "%", "self", ".", "_escapeString", "(", "text", ")", "opts", "=", "self", ".", "_el", ".", "find_elements", "(", "By", ".", "XPATH", ",", "xpath", ")", "matched", "=", "False", "for", "opt", "in", "opts", ":", "self", ".", "_setSelected", "(", "opt", ")", "if", "not", "self", ".", "is_multiple", ":", "return", "matched", "=", "True", "if", "len", "(", "opts", ")", "==", "0", "and", "\" \"", "in", "text", ":", "subStringWithoutSpace", "=", "self", ".", "_get_longest_token", "(", "text", ")", "if", "subStringWithoutSpace", "==", "\"\"", ":", "candidates", "=", "self", ".", "options", "else", ":", "xpath", "=", "\".//option[contains(.,%s)]\"", "%", "self", ".", "_escapeString", "(", "subStringWithoutSpace", ")", "candidates", "=", "self", ".", "_el", ".", "find_elements", "(", "By", ".", "XPATH", ",", "xpath", ")", "for", "candidate", "in", "candidates", ":", "if", "text", "==", "candidate", ".", "text", ":", "self", ".", "_setSelected", "(", "candidate", ")", "if", "not", "self", ".", "is_multiple", ":", "return", "matched", "=", "True", "if", "not", "matched", ":", "raise", "NoSuchElementException", "(", "\"Could not locate element with visible text: %s\"", "%", "text", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Select.deselect_all
Clear all selected entries. This is only valid when the SELECT supports multiple selections. throws NotImplementedError If the SELECT does not support multiple selections
py/selenium/webdriver/support/select.py
def deselect_all(self): """Clear all selected entries. This is only valid when the SELECT supports multiple selections. throws NotImplementedError If the SELECT does not support multiple selections """ 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)
def deselect_all(self): """Clear all selected entries. This is only valid when the SELECT supports multiple selections. throws NotImplementedError If the SELECT does not support multiple selections """ 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)
[ "Clear", "all", "selected", "entries", ".", "This", "is", "only", "valid", "when", "the", "SELECT", "supports", "multiple", "selections", ".", "throws", "NotImplementedError", "If", "the", "SELECT", "does", "not", "support", "multiple", "selections" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/select.py#L142-L149
[ "def", "deselect_all", "(", "self", ")", ":", "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", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Select.deselect_by_value
Deselect all options that have a value matching the argument. That is, when given "foo" this would deselect an option like: <option value="foo">Bar</option> :Args: - value - The value to match against throws NoSuchElementException If there is no option with specified value in SELECT
py/selenium/webdriver/support/select.py
def deselect_by_value(self, value): """Deselect all options that have a value matching the argument. That is, when given "foo" this would deselect an option like: <option value="foo">Bar</option> :Args: - value - The value to match against throws NoSuchElementException If there is no option with specified value in SELECT """ if not self.is_multiple: raise NotImplementedError("You may only deselect options of a multi-select") matched = False css = "option[value = %s]" % self._escapeString(value) opts = self._el.find_elements(By.CSS_SELECTOR, css) for opt in opts: self._unsetSelected(opt) matched = True if not matched: raise NoSuchElementException("Could not locate element with value: %s" % value)
def deselect_by_value(self, value): """Deselect all options that have a value matching the argument. That is, when given "foo" this would deselect an option like: <option value="foo">Bar</option> :Args: - value - The value to match against throws NoSuchElementException If there is no option with specified value in SELECT """ if not self.is_multiple: raise NotImplementedError("You may only deselect options of a multi-select") matched = False css = "option[value = %s]" % self._escapeString(value) opts = self._el.find_elements(By.CSS_SELECTOR, css) for opt in opts: self._unsetSelected(opt) matched = True if not matched: raise NoSuchElementException("Could not locate element with value: %s" % value)
[ "Deselect", "all", "options", "that", "have", "a", "value", "matching", "the", "argument", ".", "That", "is", "when", "given", "foo", "this", "would", "deselect", "an", "option", "like", ":" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/select.py#L151-L171
[ "def", "deselect_by_value", "(", "self", ",", "value", ")", ":", "if", "not", "self", ".", "is_multiple", ":", "raise", "NotImplementedError", "(", "\"You may only deselect options of a multi-select\"", ")", "matched", "=", "False", "css", "=", "\"option[value = %s]\"", "%", "self", ".", "_escapeString", "(", "value", ")", "opts", "=", "self", ".", "_el", ".", "find_elements", "(", "By", ".", "CSS_SELECTOR", ",", "css", ")", "for", "opt", "in", "opts", ":", "self", ".", "_unsetSelected", "(", "opt", ")", "matched", "=", "True", "if", "not", "matched", ":", "raise", "NoSuchElementException", "(", "\"Could not locate element with value: %s\"", "%", "value", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Select.deselect_by_index
Deselect the option at the given index. This is done by examing the "index" attribute of an element, and not merely by counting. :Args: - index - The option at this index will be deselected throws NoSuchElementException If there is no option with specified index in SELECT
py/selenium/webdriver/support/select.py
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 counting. :Args: - index - The option at this index will be deselected throws NoSuchElementException If there is no option with specified index in SELECT """ 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 not locate element with index %d" % index)
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 counting. :Args: - index - The option at this index will be deselected throws NoSuchElementException If there is no option with specified index in SELECT """ 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 not locate element with index %d" % index)
[ "Deselect", "the", "option", "at", "the", "given", "index", ".", "This", "is", "done", "by", "examing", "the", "index", "attribute", "of", "an", "element", "and", "not", "merely", "by", "counting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/select.py#L173-L188
[ "def", "deselect_by_index", "(", "self", ",", "index", ")", ":", "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 not locate element with index %d\"", "%", "index", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Select.deselect_by_visible_text
Deselect all options that display text matching the argument. That is, when given "Bar" this would deselect an option like: <option value="foo">Bar</option> :Args: - text - The visible text to match against
py/selenium/webdriver/support/select.py
def deselect_by_visible_text(self, text): """Deselect all options that display text matching the argument. That is, when given "Bar" this would deselect an option like: <option value="foo">Bar</option> :Args: - text - The visible text to match against """ if not self.is_multiple: raise NotImplementedError("You may only deselect options of a multi-select") matched = False xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text) opts = self._el.find_elements(By.XPATH, xpath) for opt in opts: self._unsetSelected(opt) matched = True if not matched: raise NoSuchElementException("Could not locate element with visible text: %s" % text)
def deselect_by_visible_text(self, text): """Deselect all options that display text matching the argument. That is, when given "Bar" this would deselect an option like: <option value="foo">Bar</option> :Args: - text - The visible text to match against """ if not self.is_multiple: raise NotImplementedError("You may only deselect options of a multi-select") matched = False xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text) opts = self._el.find_elements(By.XPATH, xpath) for opt in opts: self._unsetSelected(opt) matched = True if not matched: raise NoSuchElementException("Could not locate element with visible text: %s" % text)
[ "Deselect", "all", "options", "that", "display", "text", "matching", "the", "argument", ".", "That", "is", "when", "given", "Bar", "this", "would", "deselect", "an", "option", "like", ":" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/support/select.py#L190-L208
[ "def", "deselect_by_visible_text", "(", "self", ",", "text", ")", ":", "if", "not", "self", ".", "is_multiple", ":", "raise", "NotImplementedError", "(", "\"You may only deselect options of a multi-select\"", ")", "matched", "=", "False", "xpath", "=", "\".//option[normalize-space(.) = %s]\"", "%", "self", ".", "_escapeString", "(", "text", ")", "opts", "=", "self", ".", "_el", ".", "find_elements", "(", "By", ".", "XPATH", ",", "xpath", ")", "for", "opt", "in", "opts", ":", "self", ".", "_unsetSelected", "(", "opt", ")", "matched", "=", "True", "if", "not", "matched", ":", "raise", "NoSuchElementException", "(", "\"Could not locate element with visible text: %s\"", "%", "text", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Options.to_capabilities
Creates a capabilities with all the options that have been set and returns a dictionary with everything
py/selenium/webdriver/opera/options.py
def to_capabilities(self): """ Creates a capabilities with all the options that have been set and returns a dictionary with everything """ capabilities = ChromeOptions.to_capabilities(self) capabilities.update(self._caps) opera_options = capabilities[self.KEY] if self.android_package_name: opera_options["androidPackage"] = self.android_package_name if self.android_device_socket: opera_options["androidDeviceSocket"] = self.android_device_socket if self.android_command_line_file: opera_options["androidCommandLineFile"] = \ self.android_command_line_file return capabilities
def to_capabilities(self): """ Creates a capabilities with all the options that have been set and returns a dictionary with everything """ capabilities = ChromeOptions.to_capabilities(self) capabilities.update(self._caps) opera_options = capabilities[self.KEY] if self.android_package_name: opera_options["androidPackage"] = self.android_package_name if self.android_device_socket: opera_options["androidDeviceSocket"] = self.android_device_socket if self.android_command_line_file: opera_options["androidCommandLineFile"] = \ self.android_command_line_file return capabilities
[ "Creates", "a", "capabilities", "with", "all", "the", "options", "that", "have", "been", "set", "and", "returns", "a", "dictionary", "with", "everything" ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/opera/options.py#L82-L98
[ "def", "to_capabilities", "(", "self", ")", ":", "capabilities", "=", "ChromeOptions", ".", "to_capabilities", "(", "self", ")", "capabilities", ".", "update", "(", "self", ".", "_caps", ")", "opera_options", "=", "capabilities", "[", "self", ".", "KEY", "]", "if", "self", ".", "android_package_name", ":", "opera_options", "[", "\"androidPackage\"", "]", "=", "self", ".", "android_package_name", "if", "self", ".", "android_device_socket", ":", "opera_options", "[", "\"androidDeviceSocket\"", "]", "=", "self", ".", "android_device_socket", "if", "self", ".", "android_command_line_file", ":", "opera_options", "[", "\"androidCommandLineFile\"", "]", "=", "self", ".", "android_command_line_file", "return", "capabilities" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
_upload
Uploads a file to Google Cloud Storage. Args: auth_http: An authorized httplib2.Http instance. project_id: The project to upload to. bucket_name: The bucket to upload to. file_path: Path to the file to upload. object_name: The name within the bucket to upload to. acl: The ACL to assign to the uploaded file.
third_party/py/googlestorage/publish_release.py
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.Http instance. project_id: The project to upload to. bucket_name: The bucket to upload to. file_path: Path to the file to upload. object_name: The name within the bucket to upload to. acl: The ACL to assign to the uploaded file. """ 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 content_type: headers['Content-Type'] = content_type if content_type: headers['Content-Encoding'] = content_encoding try: response, content = auth_http.request( 'http://%s.storage.googleapis.com/%s' % (bucket_name, object_name), method='PUT', headers=headers, body=data) except httplib2.ServerNotFoundError, se: raise Error(404, 'Server not found.') if response.status >= 300: raise Error(response.status, response.reason) return content
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.Http instance. project_id: The project to upload to. bucket_name: The bucket to upload to. file_path: Path to the file to upload. object_name: The name within the bucket to upload to. acl: The ACL to assign to the uploaded file. """ 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 content_type: headers['Content-Type'] = content_type if content_type: headers['Content-Encoding'] = content_encoding try: response, content = auth_http.request( 'http://%s.storage.googleapis.com/%s' % (bucket_name, object_name), method='PUT', headers=headers, body=data) except httplib2.ServerNotFoundError, se: raise Error(404, 'Server not found.') if response.status >= 300: raise Error(response.status, response.reason) return content
[ "Uploads", "a", "file", "to", "Google", "Cloud", "Storage", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/third_party/py/googlestorage/publish_release.py#L102-L138
[ "def", "_upload", "(", "auth_http", ",", "project_id", ",", "bucket_name", ",", "file_path", ",", "object_name", ",", "acl", ")", ":", "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", "content_type", ":", "headers", "[", "'Content-Type'", "]", "=", "content_type", "if", "content_type", ":", "headers", "[", "'Content-Encoding'", "]", "=", "content_encoding", "try", ":", "response", ",", "content", "=", "auth_http", ".", "request", "(", "'http://%s.storage.googleapis.com/%s'", "%", "(", "bucket_name", ",", "object_name", ")", ",", "method", "=", "'PUT'", ",", "headers", "=", "headers", ",", "body", "=", "data", ")", "except", "httplib2", ".", "ServerNotFoundError", ",", "se", ":", "raise", "Error", "(", "404", ",", "'Server not found.'", ")", "if", "response", ".", "status", ">=", "300", ":", "raise", "Error", "(", "response", ".", "status", ",", "response", ".", "reason", ")", "return", "content" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
_authenticate
Runs the OAuth 2.0 installed application flow. Returns: An authorized httplib2.Http instance.
third_party/py/googlestorage/publish_release.py
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 is None or credentials.invalid: credentials = oauthtools.run_flow(flow, storage, oauthtools.argparser.parse_args(args=[])) http = httplib2.Http() return credentials.authorize(http)
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 is None or credentials.invalid: credentials = oauthtools.run_flow(flow, storage, oauthtools.argparser.parse_args(args=[])) http = httplib2.Http() return credentials.authorize(http)
[ "Runs", "the", "OAuth", "2", ".", "0", "installed", "application", "flow", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/third_party/py/googlestorage/publish_release.py#L141-L157
[ "def", "_authenticate", "(", "secrets_file", ")", ":", "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", "is", "None", "or", "credentials", ".", "invalid", ":", "credentials", "=", "oauthtools", ".", "run_flow", "(", "flow", ",", "storage", ",", "oauthtools", ".", "argparser", ".", "parse_args", "(", "args", "=", "[", "]", ")", ")", "http", "=", "httplib2", ".", "Http", "(", ")", "return", "credentials", ".", "authorize", "(", "http", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.auto_detect
Sets autodetect setting. :Args: - value: The autodetect value.
py/selenium/webdriver/common/proxy.py
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 needs to be a boolean")
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 needs to be a boolean")
[ "Sets", "autodetect", "setting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L136-L149
[ "def", "auto_detect", "(", "self", ",", "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 needs to be a boolean\"", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.ftp_proxy
Sets ftp proxy setting. :Args: - value: The ftp proxy value.
py/selenium/webdriver/common/proxy.py
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
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
[ "Sets", "ftp", "proxy", "setting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L159-L168
[ "def", "ftp_proxy", "(", "self", ",", "value", ")", ":", "self", ".", "_verify_proxy_type_compatibility", "(", "ProxyType", ".", "MANUAL", ")", "self", ".", "proxyType", "=", "ProxyType", ".", "MANUAL", "self", ".", "ftpProxy", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.http_proxy
Sets http proxy setting. :Args: - value: The http proxy value.
py/selenium/webdriver/common/proxy.py
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
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
[ "Sets", "http", "proxy", "setting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L178-L187
[ "def", "http_proxy", "(", "self", ",", "value", ")", ":", "self", ".", "_verify_proxy_type_compatibility", "(", "ProxyType", ".", "MANUAL", ")", "self", ".", "proxyType", "=", "ProxyType", ".", "MANUAL", "self", ".", "httpProxy", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.no_proxy
Sets noproxy setting. :Args: - value: The noproxy value.
py/selenium/webdriver/common/proxy.py
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
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
[ "Sets", "noproxy", "setting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L197-L206
[ "def", "no_proxy", "(", "self", ",", "value", ")", ":", "self", ".", "_verify_proxy_type_compatibility", "(", "ProxyType", ".", "MANUAL", ")", "self", ".", "proxyType", "=", "ProxyType", ".", "MANUAL", "self", ".", "noProxy", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.proxy_autoconfig_url
Sets proxy autoconfig url setting. :Args: - value: The proxy autoconfig url value.
py/selenium/webdriver/common/proxy.py
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
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
[ "Sets", "proxy", "autoconfig", "url", "setting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L216-L225
[ "def", "proxy_autoconfig_url", "(", "self", ",", "value", ")", ":", "self", ".", "_verify_proxy_type_compatibility", "(", "ProxyType", ".", "PAC", ")", "self", ".", "proxyType", "=", "ProxyType", ".", "PAC", "self", ".", "proxyAutoconfigUrl", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.ssl_proxy
Sets https proxy setting. :Args: - value: The https proxy value.
py/selenium/webdriver/common/proxy.py
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
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
[ "Sets", "https", "proxy", "setting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L235-L244
[ "def", "ssl_proxy", "(", "self", ",", "value", ")", ":", "self", ".", "_verify_proxy_type_compatibility", "(", "ProxyType", ".", "MANUAL", ")", "self", ".", "proxyType", "=", "ProxyType", ".", "MANUAL", "self", ".", "sslProxy", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.socks_proxy
Sets socks proxy setting. :Args: - value: The socks proxy value.
py/selenium/webdriver/common/proxy.py
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
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
[ "Sets", "socks", "proxy", "setting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L254-L263
[ "def", "socks_proxy", "(", "self", ",", "value", ")", ":", "self", ".", "_verify_proxy_type_compatibility", "(", "ProxyType", ".", "MANUAL", ")", "self", ".", "proxyType", "=", "ProxyType", ".", "MANUAL", "self", ".", "socksProxy", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.socks_username
Sets socks proxy username setting. :Args: - value: The socks proxy username value.
py/selenium/webdriver/common/proxy.py
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
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
[ "Sets", "socks", "proxy", "username", "setting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L273-L282
[ "def", "socks_username", "(", "self", ",", "value", ")", ":", "self", ".", "_verify_proxy_type_compatibility", "(", "ProxyType", ".", "MANUAL", ")", "self", ".", "proxyType", "=", "ProxyType", ".", "MANUAL", "self", ".", "socksUsername", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.socks_password
Sets socks proxy password setting. :Args: - value: The socks proxy password value.
py/selenium/webdriver/common/proxy.py
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
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
[ "Sets", "socks", "proxy", "password", "setting", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L292-L301
[ "def", "socks_password", "(", "self", ",", "value", ")", ":", "self", ".", "_verify_proxy_type_compatibility", "(", "ProxyType", ".", "MANUAL", ")", "self", ".", "proxyType", "=", "ProxyType", ".", "MANUAL", "self", ".", "socksPassword", "=", "value" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
Proxy.add_to_capabilities
Adds proxy information as capability in specified capabilities. :Args: - capabilities: The capabilities to which proxy will be added.
py/selenium/webdriver/common/proxy.py
def add_to_capabilities(self, capabilities): """ Adds proxy information as capability in specified capabilities. :Args: - capabilities: The capabilities to which proxy will be added. """ 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.httpProxy if self.proxyAutoconfigUrl: proxy_caps['proxyAutoconfigUrl'] = self.proxyAutoconfigUrl if self.sslProxy: proxy_caps['sslProxy'] = self.sslProxy if self.noProxy: proxy_caps['noProxy'] = self.noProxy if self.socksProxy: proxy_caps['socksProxy'] = self.socksProxy if self.socksUsername: proxy_caps['socksUsername'] = self.socksUsername if self.socksPassword: proxy_caps['socksPassword'] = self.socksPassword capabilities['proxy'] = proxy_caps
def add_to_capabilities(self, capabilities): """ Adds proxy information as capability in specified capabilities. :Args: - capabilities: The capabilities to which proxy will be added. """ 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.httpProxy if self.proxyAutoconfigUrl: proxy_caps['proxyAutoconfigUrl'] = self.proxyAutoconfigUrl if self.sslProxy: proxy_caps['sslProxy'] = self.sslProxy if self.noProxy: proxy_caps['noProxy'] = self.noProxy if self.socksProxy: proxy_caps['socksProxy'] = self.socksProxy if self.socksUsername: proxy_caps['socksUsername'] = self.socksUsername if self.socksPassword: proxy_caps['socksPassword'] = self.socksPassword capabilities['proxy'] = proxy_caps
[ "Adds", "proxy", "information", "as", "capability", "in", "specified", "capabilities", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/proxy.py#L307-L334
[ "def", "add_to_capabilities", "(", "self", ",", "capabilities", ")", ":", "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", ".", "httpProxy", "if", "self", ".", "proxyAutoconfigUrl", ":", "proxy_caps", "[", "'proxyAutoconfigUrl'", "]", "=", "self", ".", "proxyAutoconfigUrl", "if", "self", ".", "sslProxy", ":", "proxy_caps", "[", "'sslProxy'", "]", "=", "self", ".", "sslProxy", "if", "self", ".", "noProxy", ":", "proxy_caps", "[", "'noProxy'", "]", "=", "self", ".", "noProxy", "if", "self", ".", "socksProxy", ":", "proxy_caps", "[", "'socksProxy'", "]", "=", "self", ".", "socksProxy", "if", "self", ".", "socksUsername", ":", "proxy_caps", "[", "'socksUsername'", "]", "=", "self", ".", "socksUsername", "if", "self", ".", "socksPassword", ":", "proxy_caps", "[", "'socksPassword'", "]", "=", "self", ".", "socksPassword", "capabilities", "[", "'proxy'", "]", "=", "proxy_caps" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
find_connectable_ip
Resolve a hostname to an IP, preferring IPv4 addresses. We prefer IPv4 so that we don't change behavior from previous IPv4-only implementations, and because some drivers (e.g., FirefoxDriver) do not support IPv6 connections. If the optional port number is provided, only IPs that listen on the given port are considered. :Args: - host - A hostname. - port - Optional port number. :Returns: A single IP address, as a string. If any IPv4 address is found, one is returned. Otherwise, if any IPv6 address is found, one is returned. If neither, then None is returned.
py/selenium/webdriver/common/utils.py
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 previous IPv4-only implementations, and because some drivers (e.g., FirefoxDriver) do not support IPv6 connections. If the optional port number is provided, only IPs that listen on the given port are considered. :Args: - host - A hostname. - port - Optional port number. :Returns: A single IP address, as a string. If any IPv4 address is found, one is returned. Otherwise, if any IPv6 address is found, one is returned. If neither, then None is returned. """ 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.AF_INET: return sockaddr[0] if connectable and not ip and family == socket.AF_INET6: ip = sockaddr[0] return ip
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 previous IPv4-only implementations, and because some drivers (e.g., FirefoxDriver) do not support IPv6 connections. If the optional port number is provided, only IPs that listen on the given port are considered. :Args: - host - A hostname. - port - Optional port number. :Returns: A single IP address, as a string. If any IPv4 address is found, one is returned. Otherwise, if any IPv6 address is found, one is returned. If neither, then None is returned. """ 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.AF_INET: return sockaddr[0] if connectable and not ip and family == socket.AF_INET6: ip = sockaddr[0] return ip
[ "Resolve", "a", "hostname", "to", "an", "IP", "preferring", "IPv4", "addresses", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/utils.py#L46-L81
[ "def", "find_connectable_ip", "(", "host", ",", "port", "=", "None", ")", ":", "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", ".", "AF_INET", ":", "return", "sockaddr", "[", "0", "]", "if", "connectable", "and", "not", "ip", "and", "family", "==", "socket", ".", "AF_INET6", ":", "ip", "=", "sockaddr", "[", "0", "]", "return", "ip" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
join_host_port
Joins a hostname and port together. This is a minimal implementation intended to cope with IPv6 literals. For example, _join_host_port('::1', 80) == '[::1]:80'. :Args: - host - A hostname. - port - An integer port.
py/selenium/webdriver/common/utils.py
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_host_port('::1', 80) == '[::1]:80'. :Args: - host - A hostname. - port - An integer port. """ if ':' in host and not host.startswith('['): return '[%s]:%d' % (host, port) return '%s:%d' % (host, port)
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_host_port('::1', 80) == '[::1]:80'. :Args: - host - A hostname. - port - An integer port. """ if ':' in host and not host.startswith('['): return '[%s]:%d' % (host, port) return '%s:%d' % (host, port)
[ "Joins", "a", "hostname", "and", "port", "together", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/utils.py#L84-L97
[ "def", "join_host_port", "(", "host", ",", "port", ")", ":", "if", "':'", "in", "host", "and", "not", "host", ".", "startswith", "(", "'['", ")", ":", "return", "'[%s]:%d'", "%", "(", "host", ",", "port", ")", "return", "'%s:%d'", "%", "(", "host", ",", "port", ")" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
is_connectable
Tries to connect to the server at port to see if it is running. :Args: - port - The port to connect.
py/selenium/webdriver/common/utils.py
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
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
[ "Tries", "to", "connect", "to", "the", "server", "at", "port", "to", "see", "if", "it", "is", "running", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/utils.py#L100-L116
[ "def", "is_connectable", "(", "port", ",", "host", "=", "\"localhost\"", ")", ":", "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" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
is_url_connectable
Tries to connect to the HTTP server at /status path and specified port to see if it responds successfully. :Args: - port - The port to connect.
py/selenium/webdriver/common/utils.py
def is_url_connectable(port): """ Tries to connect to the HTTP server at /status path and specified port to see if it responds successfully. :Args: - port - The port to connect. """ try: from urllib import request as url_request except ImportError: import urllib2 as url_request try: res = url_request.urlopen("http://127.0.0.1:%s/status" % port) if res.getcode() == 200: return True else: return False except Exception: return False
def is_url_connectable(port): """ Tries to connect to the HTTP server at /status path and specified port to see if it responds successfully. :Args: - port - The port to connect. """ try: from urllib import request as url_request except ImportError: import urllib2 as url_request try: res = url_request.urlopen("http://127.0.0.1:%s/status" % port) if res.getcode() == 200: return True else: return False except Exception: return False
[ "Tries", "to", "connect", "to", "the", "HTTP", "server", "at", "/", "status", "path", "and", "specified", "port", "to", "see", "if", "it", "responds", "successfully", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/utils.py#L119-L139
[ "def", "is_url_connectable", "(", "port", ")", ":", "try", ":", "from", "urllib", "import", "request", "as", "url_request", "except", "ImportError", ":", "import", "urllib2", "as", "url_request", "try", ":", "res", "=", "url_request", ".", "urlopen", "(", "\"http://127.0.0.1:%s/status\"", "%", "port", ")", "if", "res", ".", "getcode", "(", ")", "==", "200", ":", "return", "True", "else", ":", "return", "False", "except", "Exception", ":", "return", "False" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
keys_to_typing
Processes the values that will be typed in the element.
py/selenium/webdriver/common/utils.py
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.append(val[i]) return typing
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.append(val[i]) return typing
[ "Processes", "the", "values", "that", "will", "be", "typed", "in", "the", "element", "." ]
SeleniumHQ/selenium
python
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/utils.py#L142-L155
[ "def", "keys_to_typing", "(", "value", ")", ":", "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", ".", "append", "(", "val", "[", "i", "]", ")", "return", "typing" ]
df40c28b41d4b3953f90eaff84838a9ac052b84a
train
to_html
Doc method extension for saving the current state as a displaCy visualization.
examples/pipeline/custom_attr_methods.py
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(): output_path.mkdir() output_file = Path(output) / file_name output_file.open("w", encoding="utf-8").write(html) # save to file print("Saved HTML to {}".format(output_file)) else: print(html)
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(): output_path.mkdir() output_file = Path(output) / file_name output_file.open("w", encoding="utf-8").write(html) # save to file print("Saved HTML to {}".format(output_file)) else: print(html)
[ "Doc", "method", "extension", "for", "saving", "the", "current", "state", "as", "a", "displaCy", "visualization", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/pipeline/custom_attr_methods.py#L43-L58
[ "def", "to_html", "(", "doc", ",", "output", "=", "\"/tmp\"", ",", "style", "=", "\"dep\"", ")", ":", "# 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", "(", ")", ":", "output_path", ".", "mkdir", "(", ")", "output_file", "=", "Path", "(", "output", ")", "/", "file_name", "output_file", ".", "open", "(", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", ".", "write", "(", "html", ")", "# save to file", "print", "(", "\"Saved HTML to {}\"", ".", "format", "(", "output_file", ")", ")", "else", ":", "print", "(", "html", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
overlap_tokens
Get the tokens from the original Doc that are also in the comparison Doc.
examples/pipeline/custom_attr_methods.py
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
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
[ "Get", "the", "tokens", "from", "the", "original", "Doc", "that", "are", "also", "in", "the", "comparison", "Doc", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/examples/pipeline/custom_attr_methods.py#L61-L69
[ "def", "overlap_tokens", "(", "doc", ",", "other_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" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
iob2json
Convert IOB files into JSON format for use with train cli.
spacy/cli/converters/iob2json.py
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
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
[ "Convert", "IOB", "files", "into", "JSON", "format", "for", "use", "with", "train", "cli", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/converters/iob2json.py#L10-L22
[ "def", "iob2json", "(", "input_data", ",", "n_sents", "=", "10", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "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" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
render
Render displaCy visualisation. docs (list or Doc): Document(s) to visualise. style (unicode): Visualisation style, 'dep' or 'ent'. page (bool): Render markup as full HTML page. minify (bool): Minify HTML markup. jupyter (bool): Override Jupyter auto-detection. options (dict): Visualiser-specific options, e.g. colors. manual (bool): Don't parse `Doc` and instead expect a dict/list of dicts. RETURNS (unicode): Rendered HTML markup. DOCS: https://spacy.io/api/top-level#displacy.render USAGE: https://spacy.io/usage/visualizers
spacy/displacy/__init__.py
def render( docs, style="dep", page=False, minify=False, jupyter=None, options={}, manual=False ): """Render displaCy visualisation. docs (list or Doc): Document(s) to visualise. style (unicode): Visualisation style, 'dep' or 'ent'. page (bool): Render markup as full HTML page. minify (bool): Minify HTML markup. jupyter (bool): Override Jupyter auto-detection. options (dict): Visualiser-specific options, e.g. colors. manual (bool): Don't parse `Doc` and instead expect a dict/list of dicts. RETURNS (unicode): Rendered HTML markup. DOCS: https://spacy.io/api/top-level#displacy.render USAGE: https://spacy.io/usage/visualizers """ 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) else obj.as_doc() for obj in docs] if not all(isinstance(obj, (Doc, Span, dict)) for obj in docs): raise ValueError(Errors.E096) renderer, converter = factories[style] renderer = renderer(options=options) parsed = [converter(doc, options) for doc in docs] if not manual else docs _html["parsed"] = renderer.render(parsed, page=page, minify=minify).strip() html = _html["parsed"] if RENDER_WRAPPER is not None: html = RENDER_WRAPPER(html) if jupyter or (jupyter is None and is_in_jupyter()): # return HTML rendered by IPython display() from IPython.core.display import display, HTML return display(HTML(html)) return html
def render( docs, style="dep", page=False, minify=False, jupyter=None, options={}, manual=False ): """Render displaCy visualisation. docs (list or Doc): Document(s) to visualise. style (unicode): Visualisation style, 'dep' or 'ent'. page (bool): Render markup as full HTML page. minify (bool): Minify HTML markup. jupyter (bool): Override Jupyter auto-detection. options (dict): Visualiser-specific options, e.g. colors. manual (bool): Don't parse `Doc` and instead expect a dict/list of dicts. RETURNS (unicode): Rendered HTML markup. DOCS: https://spacy.io/api/top-level#displacy.render USAGE: https://spacy.io/usage/visualizers """ 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) else obj.as_doc() for obj in docs] if not all(isinstance(obj, (Doc, Span, dict)) for obj in docs): raise ValueError(Errors.E096) renderer, converter = factories[style] renderer = renderer(options=options) parsed = [converter(doc, options) for doc in docs] if not manual else docs _html["parsed"] = renderer.render(parsed, page=page, minify=minify).strip() html = _html["parsed"] if RENDER_WRAPPER is not None: html = RENDER_WRAPPER(html) if jupyter or (jupyter is None and is_in_jupyter()): # return HTML rendered by IPython display() from IPython.core.display import display, HTML return display(HTML(html)) return html
[ "Render", "displaCy", "visualisation", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L21-L61
[ "def", "render", "(", "docs", ",", "style", "=", "\"dep\"", ",", "page", "=", "False", ",", "minify", "=", "False", ",", "jupyter", "=", "None", ",", "options", "=", "{", "}", ",", "manual", "=", "False", ")", ":", "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", ")", "else", "obj", ".", "as_doc", "(", ")", "for", "obj", "in", "docs", "]", "if", "not", "all", "(", "isinstance", "(", "obj", ",", "(", "Doc", ",", "Span", ",", "dict", ")", ")", "for", "obj", "in", "docs", ")", ":", "raise", "ValueError", "(", "Errors", ".", "E096", ")", "renderer", ",", "converter", "=", "factories", "[", "style", "]", "renderer", "=", "renderer", "(", "options", "=", "options", ")", "parsed", "=", "[", "converter", "(", "doc", ",", "options", ")", "for", "doc", "in", "docs", "]", "if", "not", "manual", "else", "docs", "_html", "[", "\"parsed\"", "]", "=", "renderer", ".", "render", "(", "parsed", ",", "page", "=", "page", ",", "minify", "=", "minify", ")", ".", "strip", "(", ")", "html", "=", "_html", "[", "\"parsed\"", "]", "if", "RENDER_WRAPPER", "is", "not", "None", ":", "html", "=", "RENDER_WRAPPER", "(", "html", ")", "if", "jupyter", "or", "(", "jupyter", "is", "None", "and", "is_in_jupyter", "(", ")", ")", ":", "# return HTML rendered by IPython display()", "from", "IPython", ".", "core", ".", "display", "import", "display", ",", "HTML", "return", "display", "(", "HTML", "(", "html", ")", ")", "return", "html" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
serve
Serve displaCy visualisation. docs (list or Doc): Document(s) to visualise. style (unicode): Visualisation style, 'dep' or 'ent'. page (bool): Render markup as full HTML page. minify (bool): Minify HTML markup. options (dict): Visualiser-specific options, e.g. colors. manual (bool): Don't parse `Doc` and instead expect a dict/list of dicts. port (int): Port to serve visualisation. host (unicode): Host to serve visualisation. DOCS: https://spacy.io/api/top-level#displacy.serve USAGE: https://spacy.io/usage/visualizers
spacy/displacy/__init__.py
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): Document(s) to visualise. style (unicode): Visualisation style, 'dep' or 'ent'. page (bool): Render markup as full HTML page. minify (bool): Minify HTML markup. options (dict): Visualiser-specific options, e.g. colors. manual (bool): Don't parse `Doc` and instead expect a dict/list of dicts. port (int): Port to serve visualisation. host (unicode): Host to serve visualisation. DOCS: https://spacy.io/api/top-level#displacy.serve USAGE: https://spacy.io/usage/visualizers """ 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 http://{}:{} ...\n".format(host, port)) try: httpd.serve_forever() except KeyboardInterrupt: print("Shutting down server on port {}.".format(port)) finally: httpd.server_close()
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): Document(s) to visualise. style (unicode): Visualisation style, 'dep' or 'ent'. page (bool): Render markup as full HTML page. minify (bool): Minify HTML markup. options (dict): Visualiser-specific options, e.g. colors. manual (bool): Don't parse `Doc` and instead expect a dict/list of dicts. port (int): Port to serve visualisation. host (unicode): Host to serve visualisation. DOCS: https://spacy.io/api/top-level#displacy.serve USAGE: https://spacy.io/usage/visualizers """ 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 http://{}:{} ...\n".format(host, port)) try: httpd.serve_forever() except KeyboardInterrupt: print("Shutting down server on port {}.".format(port)) finally: httpd.server_close()
[ "Serve", "displaCy", "visualisation", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L64-L102
[ "def", "serve", "(", "docs", ",", "style", "=", "\"dep\"", ",", "page", "=", "True", ",", "minify", "=", "False", ",", "options", "=", "{", "}", ",", "manual", "=", "False", ",", "port", "=", "5000", ",", "host", "=", "\"0.0.0.0\"", ",", ")", ":", "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 http://{}:{} ...\\n\"", ".", "format", "(", "host", ",", "port", ")", ")", "try", ":", "httpd", ".", "serve_forever", "(", ")", "except", "KeyboardInterrupt", ":", "print", "(", "\"Shutting down server on port {}.\"", ".", "format", "(", "port", ")", ")", "finally", ":", "httpd", ".", "server_close", "(", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
parse_deps
Generate dependency parse in {'words': [], 'arcs': []} format. doc (Doc): Document do parse. RETURNS (dict): Generated dependency parse keyed by words and arcs.
spacy/displacy/__init__.py
def parse_deps(orig_doc, options={}): """Generate dependency parse in {'words': [], 'arcs': []} format. doc (Doc): Document do parse. RETURNS (dict): Generated dependency parse keyed by words and arcs. """ doc = Doc(orig_doc.vocab).from_bytes(orig_doc.to_bytes()) if not doc.is_parsed: user_warning(Warnings.W005) if options.get("collapse_phrases", False): with doc.retokenize() as retokenizer: for np in list(doc.noun_chunks): attrs = { "tag": np.root.tag_, "lemma": np.root.lemma_, "ent_type": np.root.ent_type_, } retokenizer.merge(np, attrs=attrs) if options.get("collapse_punct", True): spans = [] for word in doc[:-1]: if word.is_punct or not word.nbor(1).is_punct: continue start = word.i end = word.i + 1 while end < len(doc) and doc[end].is_punct: end += 1 span = doc[start:end] spans.append((span, word.tag_, word.lemma_, word.ent_type_)) with doc.retokenize() as retokenizer: for span, tag, lemma, ent_type in spans: attrs = {"tag": tag, "lemma": lemma, "ent_type": ent_type} retokenizer.merge(span, attrs=attrs) if options.get("fine_grained"): words = [{"text": w.text, "tag": w.tag_} for w in doc] else: words = [{"text": w.text, "tag": w.pos_} for w in doc] arcs = [] for word in doc: if word.i < word.head.i: arcs.append( {"start": word.i, "end": word.head.i, "label": word.dep_, "dir": "left"} ) elif word.i > word.head.i: arcs.append( { "start": word.head.i, "end": word.i, "label": word.dep_, "dir": "right", } ) return {"words": words, "arcs": arcs, "settings": get_doc_settings(orig_doc)}
def parse_deps(orig_doc, options={}): """Generate dependency parse in {'words': [], 'arcs': []} format. doc (Doc): Document do parse. RETURNS (dict): Generated dependency parse keyed by words and arcs. """ doc = Doc(orig_doc.vocab).from_bytes(orig_doc.to_bytes()) if not doc.is_parsed: user_warning(Warnings.W005) if options.get("collapse_phrases", False): with doc.retokenize() as retokenizer: for np in list(doc.noun_chunks): attrs = { "tag": np.root.tag_, "lemma": np.root.lemma_, "ent_type": np.root.ent_type_, } retokenizer.merge(np, attrs=attrs) if options.get("collapse_punct", True): spans = [] for word in doc[:-1]: if word.is_punct or not word.nbor(1).is_punct: continue start = word.i end = word.i + 1 while end < len(doc) and doc[end].is_punct: end += 1 span = doc[start:end] spans.append((span, word.tag_, word.lemma_, word.ent_type_)) with doc.retokenize() as retokenizer: for span, tag, lemma, ent_type in spans: attrs = {"tag": tag, "lemma": lemma, "ent_type": ent_type} retokenizer.merge(span, attrs=attrs) if options.get("fine_grained"): words = [{"text": w.text, "tag": w.tag_} for w in doc] else: words = [{"text": w.text, "tag": w.pos_} for w in doc] arcs = [] for word in doc: if word.i < word.head.i: arcs.append( {"start": word.i, "end": word.head.i, "label": word.dep_, "dir": "left"} ) elif word.i > word.head.i: arcs.append( { "start": word.head.i, "end": word.i, "label": word.dep_, "dir": "right", } ) return {"words": words, "arcs": arcs, "settings": get_doc_settings(orig_doc)}
[ "Generate", "dependency", "parse", "in", "{", "words", ":", "[]", "arcs", ":", "[]", "}", "format", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L113-L165
[ "def", "parse_deps", "(", "orig_doc", ",", "options", "=", "{", "}", ")", ":", "doc", "=", "Doc", "(", "orig_doc", ".", "vocab", ")", ".", "from_bytes", "(", "orig_doc", ".", "to_bytes", "(", ")", ")", "if", "not", "doc", ".", "is_parsed", ":", "user_warning", "(", "Warnings", ".", "W005", ")", "if", "options", ".", "get", "(", "\"collapse_phrases\"", ",", "False", ")", ":", "with", "doc", ".", "retokenize", "(", ")", "as", "retokenizer", ":", "for", "np", "in", "list", "(", "doc", ".", "noun_chunks", ")", ":", "attrs", "=", "{", "\"tag\"", ":", "np", ".", "root", ".", "tag_", ",", "\"lemma\"", ":", "np", ".", "root", ".", "lemma_", ",", "\"ent_type\"", ":", "np", ".", "root", ".", "ent_type_", ",", "}", "retokenizer", ".", "merge", "(", "np", ",", "attrs", "=", "attrs", ")", "if", "options", ".", "get", "(", "\"collapse_punct\"", ",", "True", ")", ":", "spans", "=", "[", "]", "for", "word", "in", "doc", "[", ":", "-", "1", "]", ":", "if", "word", ".", "is_punct", "or", "not", "word", ".", "nbor", "(", "1", ")", ".", "is_punct", ":", "continue", "start", "=", "word", ".", "i", "end", "=", "word", ".", "i", "+", "1", "while", "end", "<", "len", "(", "doc", ")", "and", "doc", "[", "end", "]", ".", "is_punct", ":", "end", "+=", "1", "span", "=", "doc", "[", "start", ":", "end", "]", "spans", ".", "append", "(", "(", "span", ",", "word", ".", "tag_", ",", "word", ".", "lemma_", ",", "word", ".", "ent_type_", ")", ")", "with", "doc", ".", "retokenize", "(", ")", "as", "retokenizer", ":", "for", "span", ",", "tag", ",", "lemma", ",", "ent_type", "in", "spans", ":", "attrs", "=", "{", "\"tag\"", ":", "tag", ",", "\"lemma\"", ":", "lemma", ",", "\"ent_type\"", ":", "ent_type", "}", "retokenizer", ".", "merge", "(", "span", ",", "attrs", "=", "attrs", ")", "if", "options", ".", "get", "(", "\"fine_grained\"", ")", ":", "words", "=", "[", "{", "\"text\"", ":", "w", ".", "text", ",", "\"tag\"", ":", "w", ".", "tag_", "}", "for", "w", "in", "doc", "]", "else", ":", "words", "=", "[", "{", "\"text\"", ":", "w", ".", "text", ",", "\"tag\"", ":", "w", ".", "pos_", "}", "for", "w", "in", "doc", "]", "arcs", "=", "[", "]", "for", "word", "in", "doc", ":", "if", "word", ".", "i", "<", "word", ".", "head", ".", "i", ":", "arcs", ".", "append", "(", "{", "\"start\"", ":", "word", ".", "i", ",", "\"end\"", ":", "word", ".", "head", ".", "i", ",", "\"label\"", ":", "word", ".", "dep_", ",", "\"dir\"", ":", "\"left\"", "}", ")", "elif", "word", ".", "i", ">", "word", ".", "head", ".", "i", ":", "arcs", ".", "append", "(", "{", "\"start\"", ":", "word", ".", "head", ".", "i", ",", "\"end\"", ":", "word", ".", "i", ",", "\"label\"", ":", "word", ".", "dep_", ",", "\"dir\"", ":", "\"right\"", ",", "}", ")", "return", "{", "\"words\"", ":", "words", ",", "\"arcs\"", ":", "arcs", ",", "\"settings\"", ":", "get_doc_settings", "(", "orig_doc", ")", "}" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
parse_ents
Generate named entities in [{start: i, end: i, label: 'label'}] format. doc (Doc): Document do parse. RETURNS (dict): Generated entities keyed by text (original text) and ents.
spacy/displacy/__init__.py
def parse_ents(doc, options={}): """Generate named entities in [{start: i, end: i, label: 'label'}] format. doc (Doc): Document do parse. RETURNS (dict): Generated entities keyed by text (original text) and ents. """ ents = [ {"start": ent.start_char, "end": ent.end_char, "label": ent.label_} for ent in doc.ents ] if not ents: user_warning(Warnings.W006) title = doc.user_data.get("title", None) if hasattr(doc, "user_data") else None settings = get_doc_settings(doc) return {"text": doc.text, "ents": ents, "title": title, "settings": settings}
def parse_ents(doc, options={}): """Generate named entities in [{start: i, end: i, label: 'label'}] format. doc (Doc): Document do parse. RETURNS (dict): Generated entities keyed by text (original text) and ents. """ ents = [ {"start": ent.start_char, "end": ent.end_char, "label": ent.label_} for ent in doc.ents ] if not ents: user_warning(Warnings.W006) title = doc.user_data.get("title", None) if hasattr(doc, "user_data") else None settings = get_doc_settings(doc) return {"text": doc.text, "ents": ents, "title": title, "settings": settings}
[ "Generate", "named", "entities", "in", "[", "{", "start", ":", "i", "end", ":", "i", "label", ":", "label", "}", "]", "format", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L168-L182
[ "def", "parse_ents", "(", "doc", ",", "options", "=", "{", "}", ")", ":", "ents", "=", "[", "{", "\"start\"", ":", "ent", ".", "start_char", ",", "\"end\"", ":", "ent", ".", "end_char", ",", "\"label\"", ":", "ent", ".", "label_", "}", "for", "ent", "in", "doc", ".", "ents", "]", "if", "not", "ents", ":", "user_warning", "(", "Warnings", ".", "W006", ")", "title", "=", "doc", ".", "user_data", ".", "get", "(", "\"title\"", ",", "None", ")", "if", "hasattr", "(", "doc", ",", "\"user_data\"", ")", "else", "None", "settings", "=", "get_doc_settings", "(", "doc", ")", "return", "{", "\"text\"", ":", "doc", ".", "text", ",", "\"ents\"", ":", "ents", ",", "\"title\"", ":", "title", ",", "\"settings\"", ":", "settings", "}" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
set_render_wrapper
Set an optional wrapper function that is called around the generated HTML markup on displacy.render. This can be used to allow integration into other platforms, similar to Jupyter Notebooks that require functions to be called around the HTML. It can also be used to implement custom callbacks on render, or to embed the visualization in a custom page. func (callable): Function to call around markup before rendering it. Needs to take one argument, the HTML markup, and should return the desired output of displacy.render.
spacy/displacy/__init__.py
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 integration into other platforms, similar to Jupyter Notebooks that require functions to be called around the HTML. It can also be used to implement custom callbacks on render, or to embed the visualization in a custom page. func (callable): Function to call around markup before rendering it. Needs to take one argument, the HTML markup, and should return the desired output of displacy.render. """ global RENDER_WRAPPER if not hasattr(func, "__call__"): raise ValueError(Errors.E110.format(obj=type(func))) RENDER_WRAPPER = func
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 integration into other platforms, similar to Jupyter Notebooks that require functions to be called around the HTML. It can also be used to implement custom callbacks on render, or to embed the visualization in a custom page. func (callable): Function to call around markup before rendering it. Needs to take one argument, the HTML markup, and should return the desired output of displacy.render. """ global RENDER_WRAPPER if not hasattr(func, "__call__"): raise ValueError(Errors.E110.format(obj=type(func))) 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", "integration", "into", "other", "platforms", "similar", "to", "Jupyter", "Notebooks", "that", "require", "functions", "to", "be", "called", "around", "the", "HTML", ".", "It", "can", "also", "be", "used", "to", "implement", "custom", "callbacks", "on", "render", "or", "to", "embed", "the", "visualization", "in", "a", "custom", "page", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/displacy/__init__.py#L185-L199
[ "def", "set_render_wrapper", "(", "func", ")", ":", "global", "RENDER_WRAPPER", "if", "not", "hasattr", "(", "func", ",", "\"__call__\"", ")", ":", "raise", "ValueError", "(", "Errors", ".", "E110", ".", "format", "(", "obj", "=", "type", "(", "func", ")", ")", ")", "RENDER_WRAPPER", "=", "func" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
evaluate
Evaluate a model. To render a sample of parses in a HTML file, set an output directory as the displacy_path argument.
spacy/cli/evaluate.py
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 sample of parses in a HTML file, set an output directory as the displacy_path argument. """ 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) if displacy_path and not displacy_path.exists(): msg.fail("Visualization output directory not found", displacy_path, exits=1) corpus = GoldCorpus(data_path, data_path) nlp = util.load_model(model) dev_docs = list(corpus.dev_docs(nlp, gold_preproc=gold_preproc)) begin = timer() scorer = nlp.evaluate(dev_docs, verbose=False) end = timer() nwords = sum(len(doc_gold[0]) for doc_gold in dev_docs) results = { "Time": "%.2f s" % (end - begin), "Words": nwords, "Words/s": "%.0f" % (nwords / (end - begin)), "TOK": "%.2f" % scorer.token_acc, "POS": "%.2f" % scorer.tags_acc, "UAS": "%.2f" % scorer.uas, "LAS": "%.2f" % scorer.las, "NER P": "%.2f" % scorer.ents_p, "NER R": "%.2f" % scorer.ents_r, "NER F": "%.2f" % scorer.ents_f, } msg.table(results, title="Results") if displacy_path: docs, golds = zip(*dev_docs) render_deps = "parser" in nlp.meta.get("pipeline", []) render_ents = "ner" in nlp.meta.get("pipeline", []) render_parses( docs, displacy_path, model_name=model, limit=displacy_limit, deps=render_deps, ents=render_ents, ) msg.good("Generated {} parses as HTML".format(displacy_limit), displacy_path) if return_scores: return scorer.scores
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 sample of parses in a HTML file, set an output directory as the displacy_path argument. """ 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) if displacy_path and not displacy_path.exists(): msg.fail("Visualization output directory not found", displacy_path, exits=1) corpus = GoldCorpus(data_path, data_path) nlp = util.load_model(model) dev_docs = list(corpus.dev_docs(nlp, gold_preproc=gold_preproc)) begin = timer() scorer = nlp.evaluate(dev_docs, verbose=False) end = timer() nwords = sum(len(doc_gold[0]) for doc_gold in dev_docs) results = { "Time": "%.2f s" % (end - begin), "Words": nwords, "Words/s": "%.0f" % (nwords / (end - begin)), "TOK": "%.2f" % scorer.token_acc, "POS": "%.2f" % scorer.tags_acc, "UAS": "%.2f" % scorer.uas, "LAS": "%.2f" % scorer.las, "NER P": "%.2f" % scorer.ents_p, "NER R": "%.2f" % scorer.ents_r, "NER F": "%.2f" % scorer.ents_f, } msg.table(results, title="Results") if displacy_path: docs, golds = zip(*dev_docs) render_deps = "parser" in nlp.meta.get("pipeline", []) render_ents = "ner" in nlp.meta.get("pipeline", []) render_parses( docs, displacy_path, model_name=model, limit=displacy_limit, deps=render_deps, ents=render_ents, ) msg.good("Generated {} parses as HTML".format(displacy_limit), displacy_path) if return_scores: return scorer.scores
[ "Evaluate", "a", "model", ".", "To", "render", "a", "sample", "of", "parses", "in", "a", "HTML", "file", "set", "an", "output", "directory", "as", "the", "displacy_path", "argument", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/evaluate.py#L22-L81
[ "def", "evaluate", "(", "model", ",", "data_path", ",", "gpu_id", "=", "-", "1", ",", "gold_preproc", "=", "False", ",", "displacy_path", "=", "None", ",", "displacy_limit", "=", "25", ",", "return_scores", "=", "False", ",", ")", ":", "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", ")", "if", "displacy_path", "and", "not", "displacy_path", ".", "exists", "(", ")", ":", "msg", ".", "fail", "(", "\"Visualization output directory not found\"", ",", "displacy_path", ",", "exits", "=", "1", ")", "corpus", "=", "GoldCorpus", "(", "data_path", ",", "data_path", ")", "nlp", "=", "util", ".", "load_model", "(", "model", ")", "dev_docs", "=", "list", "(", "corpus", ".", "dev_docs", "(", "nlp", ",", "gold_preproc", "=", "gold_preproc", ")", ")", "begin", "=", "timer", "(", ")", "scorer", "=", "nlp", ".", "evaluate", "(", "dev_docs", ",", "verbose", "=", "False", ")", "end", "=", "timer", "(", ")", "nwords", "=", "sum", "(", "len", "(", "doc_gold", "[", "0", "]", ")", "for", "doc_gold", "in", "dev_docs", ")", "results", "=", "{", "\"Time\"", ":", "\"%.2f s\"", "%", "(", "end", "-", "begin", ")", ",", "\"Words\"", ":", "nwords", ",", "\"Words/s\"", ":", "\"%.0f\"", "%", "(", "nwords", "/", "(", "end", "-", "begin", ")", ")", ",", "\"TOK\"", ":", "\"%.2f\"", "%", "scorer", ".", "token_acc", ",", "\"POS\"", ":", "\"%.2f\"", "%", "scorer", ".", "tags_acc", ",", "\"UAS\"", ":", "\"%.2f\"", "%", "scorer", ".", "uas", ",", "\"LAS\"", ":", "\"%.2f\"", "%", "scorer", ".", "las", ",", "\"NER P\"", ":", "\"%.2f\"", "%", "scorer", ".", "ents_p", ",", "\"NER R\"", ":", "\"%.2f\"", "%", "scorer", ".", "ents_r", ",", "\"NER F\"", ":", "\"%.2f\"", "%", "scorer", ".", "ents_f", ",", "}", "msg", ".", "table", "(", "results", ",", "title", "=", "\"Results\"", ")", "if", "displacy_path", ":", "docs", ",", "golds", "=", "zip", "(", "*", "dev_docs", ")", "render_deps", "=", "\"parser\"", "in", "nlp", ".", "meta", ".", "get", "(", "\"pipeline\"", ",", "[", "]", ")", "render_ents", "=", "\"ner\"", "in", "nlp", ".", "meta", ".", "get", "(", "\"pipeline\"", ",", "[", "]", ")", "render_parses", "(", "docs", ",", "displacy_path", ",", "model_name", "=", "model", ",", "limit", "=", "displacy_limit", ",", "deps", "=", "render_deps", ",", "ents", "=", "render_ents", ",", ")", "msg", ".", "good", "(", "\"Generated {} parses as HTML\"", ".", "format", "(", "displacy_limit", ")", ",", "displacy_path", ")", "if", "return_scores", ":", "return", "scorer", ".", "scores" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
link
Create a symlink for models within the spacy/data directory. Accepts either the name of a pip package, or the local path to the model data directory. Linking models allows loading them via spacy.load(link_name).
spacy/cli/link.py
def link(origin, link_name, force=False, model_path=None): """ Create a symlink for models within the spacy/data directory. Accepts either the name of a pip package, or the local path to the model data directory. Linking models allows loading them via spacy.load(link_name). """ msg = Printer() if util.is_package(origin): model_path = util.get_package_path(origin) else: model_path = Path(origin) if model_path is None else Path(model_path) if not model_path.exists(): msg.fail( "Can't locate model data", "The data should be located in {}".format(path2str(model_path)), exits=1, ) data_path = util.get_data_path() if not data_path or not data_path.exists(): spacy_loc = Path(__file__).parent.parent msg.fail( "Can't find the spaCy data path to create model symlink", "Make sure a directory `/data` exists within your spaCy " "installation and try again. The data directory should be located " "here:".format(path=spacy_loc), exits=1, ) link_path = util.get_data_path() / link_name if link_path.is_symlink() and not force: msg.fail( "Link '{}' already exists".format(link_name), "To overwrite an existing link, use the --force flag", exits=1, ) elif link_path.is_symlink(): # does a symlink exist? # NB: It's important to check for is_symlink here and not for exists, # because invalid/outdated symlinks would return False otherwise. link_path.unlink() elif link_path.exists(): # does it exist otherwise? # NB: Check this last because valid symlinks also "exist". msg.fail( "Can't overwrite symlink '{}'".format(link_name), "This can happen if your data directory contains a directory or " "file of the same name.", exits=1, ) details = "%s --> %s" % (path2str(model_path), path2str(link_path)) try: symlink_to(link_path, model_path) except: # noqa: E722 # This is quite dirty, but just making sure other errors are caught. msg.fail( "Couldn't link model to '{}'".format(link_name), "Creating a symlink in spacy/data failed. Make sure you have the " "required permissions and try re-running the command as admin, or " "use a virtualenv. You can still import the model as a module and " "call its load() method, or create the symlink manually.", ) msg.text(details) raise msg.good("Linking successful", details) msg.text("You can now load the model via spacy.load('{}')".format(link_name))
def link(origin, link_name, force=False, model_path=None): """ Create a symlink for models within the spacy/data directory. Accepts either the name of a pip package, or the local path to the model data directory. Linking models allows loading them via spacy.load(link_name). """ msg = Printer() if util.is_package(origin): model_path = util.get_package_path(origin) else: model_path = Path(origin) if model_path is None else Path(model_path) if not model_path.exists(): msg.fail( "Can't locate model data", "The data should be located in {}".format(path2str(model_path)), exits=1, ) data_path = util.get_data_path() if not data_path or not data_path.exists(): spacy_loc = Path(__file__).parent.parent msg.fail( "Can't find the spaCy data path to create model symlink", "Make sure a directory `/data` exists within your spaCy " "installation and try again. The data directory should be located " "here:".format(path=spacy_loc), exits=1, ) link_path = util.get_data_path() / link_name if link_path.is_symlink() and not force: msg.fail( "Link '{}' already exists".format(link_name), "To overwrite an existing link, use the --force flag", exits=1, ) elif link_path.is_symlink(): # does a symlink exist? # NB: It's important to check for is_symlink here and not for exists, # because invalid/outdated symlinks would return False otherwise. link_path.unlink() elif link_path.exists(): # does it exist otherwise? # NB: Check this last because valid symlinks also "exist". msg.fail( "Can't overwrite symlink '{}'".format(link_name), "This can happen if your data directory contains a directory or " "file of the same name.", exits=1, ) details = "%s --> %s" % (path2str(model_path), path2str(link_path)) try: symlink_to(link_path, model_path) except: # noqa: E722 # This is quite dirty, but just making sure other errors are caught. msg.fail( "Couldn't link model to '{}'".format(link_name), "Creating a symlink in spacy/data failed. Make sure you have the " "required permissions and try re-running the command as admin, or " "use a virtualenv. You can still import the model as a module and " "call its load() method, or create the symlink manually.", ) msg.text(details) raise msg.good("Linking successful", details) msg.text("You can now load the model via spacy.load('{}')".format(link_name))
[ "Create", "a", "symlink", "for", "models", "within", "the", "spacy", "/", "data", "directory", ".", "Accepts", "either", "the", "name", "of", "a", "pip", "package", "or", "the", "local", "path", "to", "the", "model", "data", "directory", ".", "Linking", "models", "allows", "loading", "them", "via", "spacy", ".", "load", "(", "link_name", ")", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/link.py#L17-L78
[ "def", "link", "(", "origin", ",", "link_name", ",", "force", "=", "False", ",", "model_path", "=", "None", ")", ":", "msg", "=", "Printer", "(", ")", "if", "util", ".", "is_package", "(", "origin", ")", ":", "model_path", "=", "util", ".", "get_package_path", "(", "origin", ")", "else", ":", "model_path", "=", "Path", "(", "origin", ")", "if", "model_path", "is", "None", "else", "Path", "(", "model_path", ")", "if", "not", "model_path", ".", "exists", "(", ")", ":", "msg", ".", "fail", "(", "\"Can't locate model data\"", ",", "\"The data should be located in {}\"", ".", "format", "(", "path2str", "(", "model_path", ")", ")", ",", "exits", "=", "1", ",", ")", "data_path", "=", "util", ".", "get_data_path", "(", ")", "if", "not", "data_path", "or", "not", "data_path", ".", "exists", "(", ")", ":", "spacy_loc", "=", "Path", "(", "__file__", ")", ".", "parent", ".", "parent", "msg", ".", "fail", "(", "\"Can't find the spaCy data path to create model symlink\"", ",", "\"Make sure a directory `/data` exists within your spaCy \"", "\"installation and try again. The data directory should be located \"", "\"here:\"", ".", "format", "(", "path", "=", "spacy_loc", ")", ",", "exits", "=", "1", ",", ")", "link_path", "=", "util", ".", "get_data_path", "(", ")", "/", "link_name", "if", "link_path", ".", "is_symlink", "(", ")", "and", "not", "force", ":", "msg", ".", "fail", "(", "\"Link '{}' already exists\"", ".", "format", "(", "link_name", ")", ",", "\"To overwrite an existing link, use the --force flag\"", ",", "exits", "=", "1", ",", ")", "elif", "link_path", ".", "is_symlink", "(", ")", ":", "# does a symlink exist?", "# NB: It's important to check for is_symlink here and not for exists,", "# because invalid/outdated symlinks would return False otherwise.", "link_path", ".", "unlink", "(", ")", "elif", "link_path", ".", "exists", "(", ")", ":", "# does it exist otherwise?", "# NB: Check this last because valid symlinks also \"exist\".", "msg", ".", "fail", "(", "\"Can't overwrite symlink '{}'\"", ".", "format", "(", "link_name", ")", ",", "\"This can happen if your data directory contains a directory or \"", "\"file of the same name.\"", ",", "exits", "=", "1", ",", ")", "details", "=", "\"%s --> %s\"", "%", "(", "path2str", "(", "model_path", ")", ",", "path2str", "(", "link_path", ")", ")", "try", ":", "symlink_to", "(", "link_path", ",", "model_path", ")", "except", ":", "# noqa: E722", "# This is quite dirty, but just making sure other errors are caught.", "msg", ".", "fail", "(", "\"Couldn't link model to '{}'\"", ".", "format", "(", "link_name", ")", ",", "\"Creating a symlink in spacy/data failed. Make sure you have the \"", "\"required permissions and try re-running the command as admin, or \"", "\"use a virtualenv. You can still import the model as a module and \"", "\"call its load() method, or create the symlink manually.\"", ",", ")", "msg", ".", "text", "(", "details", ")", "raise", "msg", ".", "good", "(", "\"Linking successful\"", ",", "details", ")", "msg", ".", "text", "(", "\"You can now load the model via spacy.load('{}')\"", ".", "format", "(", "link_name", ")", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
validate
Validate that the currently installed version of spaCy is compatible with the installed models. Should be run after `pip install -U spacy`.
spacy/cli/validate.py
def validate(): """ Validate that the currently installed version of spaCy is compatible with the installed models. Should be run after `pip install -U spacy`. """ msg = Printer() with msg.loading("Loading compatibility table..."): r = requests.get(about.__compatibility__) if r.status_code != 200: msg.fail( "Server error ({})".format(r.status_code), "Couldn't fetch compatibility table.", exits=1, ) msg.good("Loaded compatibility table") compat = r.json()["spacy"] version = about.__version__ version = version.rsplit(".dev", 1)[0] current_compat = compat.get(version) if not current_compat: msg.fail( "Can't find spaCy v{} in compatibility table".format(version), about.__compatibility__, exits=1, ) all_models = set() for spacy_v, models in dict(compat).items(): all_models.update(models.keys()) for model, model_vs in models.items(): compat[spacy_v][model] = [reformat_version(v) for v in model_vs] model_links = get_model_links(current_compat) model_pkgs = get_model_pkgs(current_compat, all_models) incompat_links = {l for l, d in model_links.items() if not d["compat"]} incompat_models = {d["name"] for _, d in model_pkgs.items() if not d["compat"]} incompat_models.update( [d["name"] for _, d in model_links.items() if not d["compat"]] ) na_models = [m for m in incompat_models if m not in current_compat] update_models = [m for m in incompat_models if m in current_compat] spacy_dir = Path(__file__).parent.parent msg.divider("Installed models (spaCy v{})".format(about.__version__)) msg.info("spaCy installation: {}".format(path2str(spacy_dir))) if model_links or model_pkgs: header = ("TYPE", "NAME", "MODEL", "VERSION", "") rows = [] for name, data in model_pkgs.items(): rows.append(get_model_row(current_compat, name, data, msg)) for name, data in model_links.items(): rows.append(get_model_row(current_compat, name, data, msg, "link")) msg.table(rows, header=header) else: msg.text("No models found in your current environment.", exits=0) if update_models: msg.divider("Install updates") msg.text("Use the following commands to update the model packages:") cmd = "python -m spacy download {}" print("\n".join([cmd.format(pkg) for pkg in update_models]) + "\n") if na_models: msg.text( "The following models are not available for spaCy " "v{}: {}".format(about.__version__, ", ".join(na_models)) ) if incompat_links: msg.text( "You may also want to overwrite the incompatible links using the " "`python -m spacy link` command with `--force`, or remove them " "from the data directory. " "Data path: {path}".format(path=path2str(get_data_path())) ) if incompat_models or incompat_links: sys.exit(1)
def validate(): """ Validate that the currently installed version of spaCy is compatible with the installed models. Should be run after `pip install -U spacy`. """ msg = Printer() with msg.loading("Loading compatibility table..."): r = requests.get(about.__compatibility__) if r.status_code != 200: msg.fail( "Server error ({})".format(r.status_code), "Couldn't fetch compatibility table.", exits=1, ) msg.good("Loaded compatibility table") compat = r.json()["spacy"] version = about.__version__ version = version.rsplit(".dev", 1)[0] current_compat = compat.get(version) if not current_compat: msg.fail( "Can't find spaCy v{} in compatibility table".format(version), about.__compatibility__, exits=1, ) all_models = set() for spacy_v, models in dict(compat).items(): all_models.update(models.keys()) for model, model_vs in models.items(): compat[spacy_v][model] = [reformat_version(v) for v in model_vs] model_links = get_model_links(current_compat) model_pkgs = get_model_pkgs(current_compat, all_models) incompat_links = {l for l, d in model_links.items() if not d["compat"]} incompat_models = {d["name"] for _, d in model_pkgs.items() if not d["compat"]} incompat_models.update( [d["name"] for _, d in model_links.items() if not d["compat"]] ) na_models = [m for m in incompat_models if m not in current_compat] update_models = [m for m in incompat_models if m in current_compat] spacy_dir = Path(__file__).parent.parent msg.divider("Installed models (spaCy v{})".format(about.__version__)) msg.info("spaCy installation: {}".format(path2str(spacy_dir))) if model_links or model_pkgs: header = ("TYPE", "NAME", "MODEL", "VERSION", "") rows = [] for name, data in model_pkgs.items(): rows.append(get_model_row(current_compat, name, data, msg)) for name, data in model_links.items(): rows.append(get_model_row(current_compat, name, data, msg, "link")) msg.table(rows, header=header) else: msg.text("No models found in your current environment.", exits=0) if update_models: msg.divider("Install updates") msg.text("Use the following commands to update the model packages:") cmd = "python -m spacy download {}" print("\n".join([cmd.format(pkg) for pkg in update_models]) + "\n") if na_models: msg.text( "The following models are not available for spaCy " "v{}: {}".format(about.__version__, ", ".join(na_models)) ) if incompat_links: msg.text( "You may also want to overwrite the incompatible links using the " "`python -m spacy link` command with `--force`, or remove them " "from the data directory. " "Data path: {path}".format(path=path2str(get_data_path())) ) if incompat_models or incompat_links: sys.exit(1)
[ "Validate", "that", "the", "currently", "installed", "version", "of", "spaCy", "is", "compatible", "with", "the", "installed", "models", ".", "Should", "be", "run", "after", "pip", "install", "-", "U", "spacy", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/validate.py#L16-L88
[ "def", "validate", "(", ")", ":", "msg", "=", "Printer", "(", ")", "with", "msg", ".", "loading", "(", "\"Loading compatibility table...\"", ")", ":", "r", "=", "requests", ".", "get", "(", "about", ".", "__compatibility__", ")", "if", "r", ".", "status_code", "!=", "200", ":", "msg", ".", "fail", "(", "\"Server error ({})\"", ".", "format", "(", "r", ".", "status_code", ")", ",", "\"Couldn't fetch compatibility table.\"", ",", "exits", "=", "1", ",", ")", "msg", ".", "good", "(", "\"Loaded compatibility table\"", ")", "compat", "=", "r", ".", "json", "(", ")", "[", "\"spacy\"", "]", "version", "=", "about", ".", "__version__", "version", "=", "version", ".", "rsplit", "(", "\".dev\"", ",", "1", ")", "[", "0", "]", "current_compat", "=", "compat", ".", "get", "(", "version", ")", "if", "not", "current_compat", ":", "msg", ".", "fail", "(", "\"Can't find spaCy v{} in compatibility table\"", ".", "format", "(", "version", ")", ",", "about", ".", "__compatibility__", ",", "exits", "=", "1", ",", ")", "all_models", "=", "set", "(", ")", "for", "spacy_v", ",", "models", "in", "dict", "(", "compat", ")", ".", "items", "(", ")", ":", "all_models", ".", "update", "(", "models", ".", "keys", "(", ")", ")", "for", "model", ",", "model_vs", "in", "models", ".", "items", "(", ")", ":", "compat", "[", "spacy_v", "]", "[", "model", "]", "=", "[", "reformat_version", "(", "v", ")", "for", "v", "in", "model_vs", "]", "model_links", "=", "get_model_links", "(", "current_compat", ")", "model_pkgs", "=", "get_model_pkgs", "(", "current_compat", ",", "all_models", ")", "incompat_links", "=", "{", "l", "for", "l", ",", "d", "in", "model_links", ".", "items", "(", ")", "if", "not", "d", "[", "\"compat\"", "]", "}", "incompat_models", "=", "{", "d", "[", "\"name\"", "]", "for", "_", ",", "d", "in", "model_pkgs", ".", "items", "(", ")", "if", "not", "d", "[", "\"compat\"", "]", "}", "incompat_models", ".", "update", "(", "[", "d", "[", "\"name\"", "]", "for", "_", ",", "d", "in", "model_links", ".", "items", "(", ")", "if", "not", "d", "[", "\"compat\"", "]", "]", ")", "na_models", "=", "[", "m", "for", "m", "in", "incompat_models", "if", "m", "not", "in", "current_compat", "]", "update_models", "=", "[", "m", "for", "m", "in", "incompat_models", "if", "m", "in", "current_compat", "]", "spacy_dir", "=", "Path", "(", "__file__", ")", ".", "parent", ".", "parent", "msg", ".", "divider", "(", "\"Installed models (spaCy v{})\"", ".", "format", "(", "about", ".", "__version__", ")", ")", "msg", ".", "info", "(", "\"spaCy installation: {}\"", ".", "format", "(", "path2str", "(", "spacy_dir", ")", ")", ")", "if", "model_links", "or", "model_pkgs", ":", "header", "=", "(", "\"TYPE\"", ",", "\"NAME\"", ",", "\"MODEL\"", ",", "\"VERSION\"", ",", "\"\"", ")", "rows", "=", "[", "]", "for", "name", ",", "data", "in", "model_pkgs", ".", "items", "(", ")", ":", "rows", ".", "append", "(", "get_model_row", "(", "current_compat", ",", "name", ",", "data", ",", "msg", ")", ")", "for", "name", ",", "data", "in", "model_links", ".", "items", "(", ")", ":", "rows", ".", "append", "(", "get_model_row", "(", "current_compat", ",", "name", ",", "data", ",", "msg", ",", "\"link\"", ")", ")", "msg", ".", "table", "(", "rows", ",", "header", "=", "header", ")", "else", ":", "msg", ".", "text", "(", "\"No models found in your current environment.\"", ",", "exits", "=", "0", ")", "if", "update_models", ":", "msg", ".", "divider", "(", "\"Install updates\"", ")", "msg", ".", "text", "(", "\"Use the following commands to update the model packages:\"", ")", "cmd", "=", "\"python -m spacy download {}\"", "print", "(", "\"\\n\"", ".", "join", "(", "[", "cmd", ".", "format", "(", "pkg", ")", "for", "pkg", "in", "update_models", "]", ")", "+", "\"\\n\"", ")", "if", "na_models", ":", "msg", ".", "text", "(", "\"The following models are not available for spaCy \"", "\"v{}: {}\"", ".", "format", "(", "about", ".", "__version__", ",", "\", \"", ".", "join", "(", "na_models", ")", ")", ")", "if", "incompat_links", ":", "msg", ".", "text", "(", "\"You may also want to overwrite the incompatible links using the \"", "\"`python -m spacy link` command with `--force`, or remove them \"", "\"from the data directory. \"", "\"Data path: {path}\"", ".", "format", "(", "path", "=", "path2str", "(", "get_data_path", "(", ")", ")", ")", ")", "if", "incompat_models", "or", "incompat_links", ":", "sys", ".", "exit", "(", "1", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
profile
Profile a spaCy pipeline, to find out which functions take the most time. Input should be formatted as one JSON object per line with a key "text". It can either be provided as a JSONL file, or be read from sys.sytdin. If no input file is specified, the IMDB dataset is loaded via Thinc.
spacy/cli/profile.py
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 JSON object per line with a key "text". It can either be provided as a JSONL file, or be read from sys.sytdin. If no input file is specified, the IMDB dataset is loaded via Thinc. """ 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("Loaded IMDB dataset and using {} examples".format(n_inputs)) inputs = inputs[:n_inputs] with msg.loading("Loading model '{}'...".format(model)): nlp = load_model(model) msg.good("Loaded model '{}'".format(model)) texts = list(itertools.islice(inputs, n_texts)) cProfile.runctx("parse_texts(nlp, texts)", globals(), locals(), "Profile.prof") s = pstats.Stats("Profile.prof") msg.divider("Profile stats") s.strip_dirs().sort_stats("time").print_stats()
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 JSON object per line with a key "text". It can either be provided as a JSONL file, or be read from sys.sytdin. If no input file is specified, the IMDB dataset is loaded via Thinc. """ 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("Loaded IMDB dataset and using {} examples".format(n_inputs)) inputs = inputs[:n_inputs] with msg.loading("Loading model '{}'...".format(model)): nlp = load_model(model) msg.good("Loaded model '{}'".format(model)) texts = list(itertools.islice(inputs, n_texts)) cProfile.runctx("parse_texts(nlp, texts)", globals(), locals(), "Profile.prof") s = pstats.Stats("Profile.prof") msg.divider("Profile stats") s.strip_dirs().sort_stats("time").print_stats()
[ "Profile", "a", "spaCy", "pipeline", "to", "find", "out", "which", "functions", "take", "the", "most", "time", ".", "Input", "should", "be", "formatted", "as", "one", "JSON", "object", "per", "line", "with", "a", "key", "text", ".", "It", "can", "either", "be", "provided", "as", "a", "JSONL", "file", "or", "be", "read", "from", "sys", ".", "sytdin", ".", "If", "no", "input", "file", "is", "specified", "the", "IMDB", "dataset", "is", "loaded", "via", "Thinc", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/cli/profile.py#L23-L47
[ "def", "profile", "(", "model", ",", "inputs", "=", "None", ",", "n_texts", "=", "10000", ")", ":", "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", "(", "\"Loaded IMDB dataset and using {} examples\"", ".", "format", "(", "n_inputs", ")", ")", "inputs", "=", "inputs", "[", ":", "n_inputs", "]", "with", "msg", ".", "loading", "(", "\"Loading model '{}'...\"", ".", "format", "(", "model", ")", ")", ":", "nlp", "=", "load_model", "(", "model", ")", "msg", ".", "good", "(", "\"Loaded model '{}'\"", ".", "format", "(", "model", ")", ")", "texts", "=", "list", "(", "itertools", ".", "islice", "(", "inputs", ",", "n_texts", ")", ")", "cProfile", ".", "runctx", "(", "\"parse_texts(nlp, texts)\"", ",", "globals", "(", ")", ",", "locals", "(", ")", ",", "\"Profile.prof\"", ")", "s", "=", "pstats", ".", "Stats", "(", "\"Profile.prof\"", ")", "msg", ".", "divider", "(", "\"Profile stats\"", ")", "s", ".", "strip_dirs", "(", ")", ".", "sort_stats", "(", "\"time\"", ")", ".", "print_stats", "(", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
resolve_pos
If necessary, add a field to the POS tag for UD mapping. Under Universal Dependencies, sometimes the same Unidic POS tag can be mapped differently depending on the literal token or its context in the sentence. This function adds information to the POS tag to resolve ambiguous mappings.
spacy/lang/ja/__init__.py
def resolve_pos(token): """If necessary, add a field to the POS tag for UD mapping. Under Universal Dependencies, sometimes the same Unidic POS tag can be mapped differently depending on the literal token or its context in the sentence. This function adds information to the POS tag to resolve ambiguous mappings. """ # TODO: This is a first take. The rules here are crude approximations. # For many of these, full dependencies are needed to properly resolve # PoS mappings. if token.pos == "連体詞,*,*,*": if re.match(r"[こそあど此其彼]の", token.surface): return token.pos + ",DET" if re.match(r"[こそあど此其彼]", token.surface): return token.pos + ",PRON" return token.pos + ",ADJ" return token.pos
def resolve_pos(token): """If necessary, add a field to the POS tag for UD mapping. Under Universal Dependencies, sometimes the same Unidic POS tag can be mapped differently depending on the literal token or its context in the sentence. This function adds information to the POS tag to resolve ambiguous mappings. """ # TODO: This is a first take. The rules here are crude approximations. # For many of these, full dependencies are needed to properly resolve # PoS mappings. if token.pos == "連体詞,*,*,*": if re.match(r"[こそあど此其彼]の", token.surface): return token.pos + ",DET" if re.match(r"[こそあど此其彼]", token.surface): return token.pos + ",PRON" return token.pos + ",ADJ" return token.pos
[ "If", "necessary", "add", "a", "field", "to", "the", "POS", "tag", "for", "UD", "mapping", ".", "Under", "Universal", "Dependencies", "sometimes", "the", "same", "Unidic", "POS", "tag", "can", "be", "mapped", "differently", "depending", "on", "the", "literal", "token", "or", "its", "context", "in", "the", "sentence", ".", "This", "function", "adds", "information", "to", "the", "POS", "tag", "to", "resolve", "ambiguous", "mappings", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/ja/__init__.py#L33-L49
[ "def", "resolve_pos", "(", "token", ")", ":", "# TODO: This is a first take. The rules here are crude approximations.", "# For many of these, full dependencies are needed to properly resolve", "# PoS mappings.", "if", "token", ".", "pos", "==", "\"連体詞,*,*,*\":", "", "if", "re", ".", "match", "(", "r\"[こそあど此其彼]の\", token.surface)", ":", "", "", "", "", "", "return", "token", ".", "pos", "+", "\",DET\"", "if", "re", ".", "match", "(", "r\"[こそあど此其彼]\", token.surfac", "e", ":", "", "", "", "", "return", "token", ".", "pos", "+", "\",PRON\"", "return", "token", ".", "pos", "+", "\",ADJ\"", "return", "token", ".", "pos" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
detailed_tokens
Format Mecab output into a nice data structure, based on Janome.
spacy/lang/ja/__init__.py
def detailed_tokens(tokenizer, text): """Format Mecab output into a nice data structure, based on Janome.""" node = tokenizer.parseToNode(text) node = node.next # first node is beginning of sentence and empty, skip it words = [] while node.posid != 0: surface = node.surface base = surface # a default value. Updated if available later. parts = node.feature.split(",") pos = ",".join(parts[0:4]) if len(parts) > 7: # this information is only available for words in the tokenizer # dictionary base = parts[7] words.append(ShortUnitWord(surface, base, pos)) node = node.next return words
def detailed_tokens(tokenizer, text): """Format Mecab output into a nice data structure, based on Janome.""" node = tokenizer.parseToNode(text) node = node.next # first node is beginning of sentence and empty, skip it words = [] while node.posid != 0: surface = node.surface base = surface # a default value. Updated if available later. parts = node.feature.split(",") pos = ",".join(parts[0:4]) if len(parts) > 7: # this information is only available for words in the tokenizer # dictionary base = parts[7] words.append(ShortUnitWord(surface, base, pos)) node = node.next return words
[ "Format", "Mecab", "output", "into", "a", "nice", "data", "structure", "based", "on", "Janome", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/lang/ja/__init__.py#L52-L68
[ "def", "detailed_tokens", "(", "tokenizer", ",", "text", ")", ":", "node", "=", "tokenizer", ".", "parseToNode", "(", "text", ")", "node", "=", "node", ".", "next", "# first node is beginning of sentence and empty, skip it", "words", "=", "[", "]", "while", "node", ".", "posid", "!=", "0", ":", "surface", "=", "node", ".", "surface", "base", "=", "surface", "# a default value. Updated if available later.", "parts", "=", "node", ".", "feature", ".", "split", "(", "\",\"", ")", "pos", "=", "\",\"", ".", "join", "(", "parts", "[", "0", ":", "4", "]", ")", "if", "len", "(", "parts", ")", ">", "7", ":", "# this information is only available for words in the tokenizer", "# dictionary", "base", "=", "parts", "[", "7", "]", "words", ".", "append", "(", "ShortUnitWord", "(", "surface", ",", "base", ",", "pos", ")", ")", "node", "=", "node", ".", "next", "return", "words" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
symlink_to
Create a symlink. Used for model shortcut links. orig (unicode / Path): The origin path. dest (unicode / Path): The destination path of the symlink.
spacy/compat.py
def symlink_to(orig, dest): """Create a symlink. Used for model shortcut links. orig (unicode / Path): The origin path. dest (unicode / Path): The destination path of the symlink. """ if is_windows: import subprocess subprocess.check_call( ["mklink", "/d", path2str(orig), path2str(dest)], shell=True ) else: orig.symlink_to(dest)
def symlink_to(orig, dest): """Create a symlink. Used for model shortcut links. orig (unicode / Path): The origin path. dest (unicode / Path): The destination path of the symlink. """ if is_windows: import subprocess subprocess.check_call( ["mklink", "/d", path2str(orig), path2str(dest)], shell=True ) else: orig.symlink_to(dest)
[ "Create", "a", "symlink", ".", "Used", "for", "model", "shortcut", "links", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L86-L99
[ "def", "symlink_to", "(", "orig", ",", "dest", ")", ":", "if", "is_windows", ":", "import", "subprocess", "subprocess", ".", "check_call", "(", "[", "\"mklink\"", ",", "\"/d\"", ",", "path2str", "(", "orig", ")", ",", "path2str", "(", "dest", ")", "]", ",", "shell", "=", "True", ")", "else", ":", "orig", ".", "symlink_to", "(", "dest", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
symlink_remove
Remove a symlink. Used for model shortcut links. link (unicode / Path): The path to the symlink.
spacy/compat.py
def symlink_remove(link): """Remove a symlink. Used for model shortcut links. link (unicode / Path): The path to the symlink. """ # https://stackoverflow.com/q/26554135/6400719 if os.path.isdir(path2str(link)) and is_windows: # this should only be on Py2.7 and windows os.rmdir(path2str(link)) else: os.unlink(path2str(link))
def symlink_remove(link): """Remove a symlink. Used for model shortcut links. link (unicode / Path): The path to the symlink. """ # https://stackoverflow.com/q/26554135/6400719 if os.path.isdir(path2str(link)) and is_windows: # this should only be on Py2.7 and windows os.rmdir(path2str(link)) else: os.unlink(path2str(link))
[ "Remove", "a", "symlink", ".", "Used", "for", "model", "shortcut", "links", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L102-L112
[ "def", "symlink_remove", "(", "link", ")", ":", "# https://stackoverflow.com/q/26554135/6400719", "if", "os", ".", "path", ".", "isdir", "(", "path2str", "(", "link", ")", ")", "and", "is_windows", ":", "# this should only be on Py2.7 and windows", "os", ".", "rmdir", "(", "path2str", "(", "link", ")", ")", "else", ":", "os", ".", "unlink", "(", "path2str", "(", "link", ")", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
is_config
Check if a specific configuration of Python version and operating system matches the user's setup. Mostly used to display targeted error messages. python2 (bool): spaCy is executed with Python 2.x. python3 (bool): spaCy is executed with Python 3.x. windows (bool): spaCy is executed on Windows. linux (bool): spaCy is executed on Linux. osx (bool): spaCy is executed on OS X or macOS. RETURNS (bool): Whether the configuration matches the user's platform. DOCS: https://spacy.io/api/top-level#compat.is_config
spacy/compat.py
def is_config(python2=None, python3=None, windows=None, linux=None, osx=None): """Check if a specific configuration of Python version and operating system matches the user's setup. Mostly used to display targeted error messages. python2 (bool): spaCy is executed with Python 2.x. python3 (bool): spaCy is executed with Python 3.x. windows (bool): spaCy is executed on Windows. linux (bool): spaCy is executed on Linux. osx (bool): spaCy is executed on OS X or macOS. RETURNS (bool): Whether the configuration matches the user's platform. DOCS: https://spacy.io/api/top-level#compat.is_config """ return ( python2 in (None, is_python2) and python3 in (None, is_python3) and windows in (None, is_windows) and linux in (None, is_linux) and osx in (None, is_osx) )
def is_config(python2=None, python3=None, windows=None, linux=None, osx=None): """Check if a specific configuration of Python version and operating system matches the user's setup. Mostly used to display targeted error messages. python2 (bool): spaCy is executed with Python 2.x. python3 (bool): spaCy is executed with Python 3.x. windows (bool): spaCy is executed on Windows. linux (bool): spaCy is executed on Linux. osx (bool): spaCy is executed on OS X or macOS. RETURNS (bool): Whether the configuration matches the user's platform. DOCS: https://spacy.io/api/top-level#compat.is_config """ return ( python2 in (None, is_python2) and python3 in (None, is_python3) and windows in (None, is_windows) and linux in (None, is_linux) and osx in (None, is_osx) )
[ "Check", "if", "a", "specific", "configuration", "of", "Python", "version", "and", "operating", "system", "matches", "the", "user", "s", "setup", ".", "Mostly", "used", "to", "display", "targeted", "error", "messages", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L115-L134
[ "def", "is_config", "(", "python2", "=", "None", ",", "python3", "=", "None", ",", "windows", "=", "None", ",", "linux", "=", "None", ",", "osx", "=", "None", ")", ":", "return", "(", "python2", "in", "(", "None", ",", "is_python2", ")", "and", "python3", "in", "(", "None", ",", "is_python3", ")", "and", "windows", "in", "(", "None", ",", "is_windows", ")", "and", "linux", "in", "(", "None", ",", "is_linux", ")", "and", "osx", "in", "(", "None", ",", "is_osx", ")", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
import_file
Import module from a file. Used to load models from a directory. name (unicode): Name of module to load. loc (unicode / Path): Path to the file. RETURNS: The loaded module.
spacy/compat.py
def import_file(name, loc): """Import module from a file. Used to load models from a directory. name (unicode): Name of module to load. loc (unicode / Path): Path to the file. RETURNS: The loaded module. """ loc = path2str(loc) if is_python_pre_3_5: import imp return imp.load_source(name, loc) else: import importlib.util spec = importlib.util.spec_from_file_location(name, str(loc)) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
def import_file(name, loc): """Import module from a file. Used to load models from a directory. name (unicode): Name of module to load. loc (unicode / Path): Path to the file. RETURNS: The loaded module. """ loc = path2str(loc) if is_python_pre_3_5: import imp return imp.load_source(name, loc) else: import importlib.util spec = importlib.util.spec_from_file_location(name, str(loc)) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
[ "Import", "module", "from", "a", "file", ".", "Used", "to", "load", "models", "from", "a", "directory", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L137-L155
[ "def", "import_file", "(", "name", ",", "loc", ")", ":", "loc", "=", "path2str", "(", "loc", ")", "if", "is_python_pre_3_5", ":", "import", "imp", "return", "imp", ".", "load_source", "(", "name", ",", "loc", ")", "else", ":", "import", "importlib", ".", "util", "spec", "=", "importlib", ".", "util", ".", "spec_from_file_location", "(", "name", ",", "str", "(", "loc", ")", ")", "module", "=", "importlib", ".", "util", ".", "module_from_spec", "(", "spec", ")", "spec", ".", "loader", ".", "exec_module", "(", "module", ")", "return", "module" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
unescape_unicode
Python2.7's re module chokes when compiling patterns that have ranges between escaped unicode codepoints if the two codepoints are unrecognised in the unicode database. For instance: re.compile('[\\uAA77-\\uAA79]').findall("hello") Ends up matching every character (on Python 2). This problem doesn't occur if we're dealing with unicode literals.
spacy/compat.py
def unescape_unicode(string): """Python2.7's re module chokes when compiling patterns that have ranges between escaped unicode codepoints if the two codepoints are unrecognised in the unicode database. For instance: re.compile('[\\uAA77-\\uAA79]').findall("hello") Ends up matching every character (on Python 2). This problem doesn't occur if we're dealing with unicode literals. """ if string is None: return string # We only want to unescape the unicode, so we first must protect the other # backslashes. string = string.replace("\\", "\\\\") # Now we remove that protection for the unicode. string = string.replace("\\\\u", "\\u") string = string.replace("\\\\U", "\\U") # Now we unescape by evaling the string with the AST. This can't execute # code -- it only does the representational level. return ast.literal_eval("u'''" + string + "'''")
def unescape_unicode(string): """Python2.7's re module chokes when compiling patterns that have ranges between escaped unicode codepoints if the two codepoints are unrecognised in the unicode database. For instance: re.compile('[\\uAA77-\\uAA79]').findall("hello") Ends up matching every character (on Python 2). This problem doesn't occur if we're dealing with unicode literals. """ if string is None: return string # We only want to unescape the unicode, so we first must protect the other # backslashes. string = string.replace("\\", "\\\\") # Now we remove that protection for the unicode. string = string.replace("\\\\u", "\\u") string = string.replace("\\\\U", "\\U") # Now we unescape by evaling the string with the AST. This can't execute # code -- it only does the representational level. return ast.literal_eval("u'''" + string + "'''")
[ "Python2", ".", "7", "s", "re", "module", "chokes", "when", "compiling", "patterns", "that", "have", "ranges", "between", "escaped", "unicode", "codepoints", "if", "the", "two", "codepoints", "are", "unrecognised", "in", "the", "unicode", "database", ".", "For", "instance", ":" ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/compat.py#L158-L178
[ "def", "unescape_unicode", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "string", "# We only want to unescape the unicode, so we first must protect the other", "# backslashes.", "string", "=", "string", ".", "replace", "(", "\"\\\\\"", ",", "\"\\\\\\\\\"", ")", "# Now we remove that protection for the unicode.", "string", "=", "string", ".", "replace", "(", "\"\\\\\\\\u\"", ",", "\"\\\\u\"", ")", "string", "=", "string", ".", "replace", "(", "\"\\\\\\\\U\"", ",", "\"\\\\U\"", ")", "# Now we unescape by evaling the string with the AST. This can't execute", "# code -- it only does the representational level.", "return", "ast", ".", "literal_eval", "(", "\"u'''\"", "+", "string", "+", "\"'''\"", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
get_lang_class
Import and load a Language class. lang (unicode): Two-letter language code, e.g. 'en'. RETURNS (Language): Language class.
spacy/util.py
def get_lang_class(lang): """Import and load a Language class. lang (unicode): Two-letter language code, e.g. 'en'. RETURNS (Language): Language class. """ global LANGUAGES # Check if an entry point is exposed for the language code entry_point = get_entry_point("spacy_languages", lang) if entry_point is not None: LANGUAGES[lang] = entry_point return entry_point if lang not in LANGUAGES: try: module = importlib.import_module(".lang.%s" % lang, "spacy") except ImportError as err: raise ImportError(Errors.E048.format(lang=lang, err=err)) LANGUAGES[lang] = getattr(module, module.__all__[0]) return LANGUAGES[lang]
def get_lang_class(lang): """Import and load a Language class. lang (unicode): Two-letter language code, e.g. 'en'. RETURNS (Language): Language class. """ global LANGUAGES # Check if an entry point is exposed for the language code entry_point = get_entry_point("spacy_languages", lang) if entry_point is not None: LANGUAGES[lang] = entry_point return entry_point if lang not in LANGUAGES: try: module = importlib.import_module(".lang.%s" % lang, "spacy") except ImportError as err: raise ImportError(Errors.E048.format(lang=lang, err=err)) LANGUAGES[lang] = getattr(module, module.__all__[0]) return LANGUAGES[lang]
[ "Import", "and", "load", "a", "Language", "class", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L53-L71
[ "def", "get_lang_class", "(", "lang", ")", ":", "global", "LANGUAGES", "# Check if an entry point is exposed for the language code", "entry_point", "=", "get_entry_point", "(", "\"spacy_languages\"", ",", "lang", ")", "if", "entry_point", "is", "not", "None", ":", "LANGUAGES", "[", "lang", "]", "=", "entry_point", "return", "entry_point", "if", "lang", "not", "in", "LANGUAGES", ":", "try", ":", "module", "=", "importlib", ".", "import_module", "(", "\".lang.%s\"", "%", "lang", ",", "\"spacy\"", ")", "except", "ImportError", "as", "err", ":", "raise", "ImportError", "(", "Errors", ".", "E048", ".", "format", "(", "lang", "=", "lang", ",", "err", "=", "err", ")", ")", "LANGUAGES", "[", "lang", "]", "=", "getattr", "(", "module", ",", "module", ".", "__all__", "[", "0", "]", ")", "return", "LANGUAGES", "[", "lang", "]" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
load_model
Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model.
spacy/util.py
def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, "exists"): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name))
def load_model(name, **overrides): """Load a model from a shortcut link, package or data path. name (unicode): Package name, shortcut link or model path. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with the loaded model. """ data_path = get_data_path() if not data_path or not data_path.exists(): raise IOError(Errors.E049.format(path=path2str(data_path))) if isinstance(name, basestring_): # in data dir / shortcut if name in set([d.name for d in data_path.iterdir()]): return load_model_from_link(name, **overrides) if is_package(name): # installed as package return load_model_from_package(name, **overrides) if Path(name).exists(): # path to model data directory return load_model_from_path(Path(name), **overrides) elif hasattr(name, "exists"): # Path or Path-like to model data return load_model_from_path(name, **overrides) raise IOError(Errors.E050.format(name=name))
[ "Load", "a", "model", "from", "a", "shortcut", "link", "package", "or", "data", "path", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L117-L136
[ "def", "load_model", "(", "name", ",", "*", "*", "overrides", ")", ":", "data_path", "=", "get_data_path", "(", ")", "if", "not", "data_path", "or", "not", "data_path", ".", "exists", "(", ")", ":", "raise", "IOError", "(", "Errors", ".", "E049", ".", "format", "(", "path", "=", "path2str", "(", "data_path", ")", ")", ")", "if", "isinstance", "(", "name", ",", "basestring_", ")", ":", "# in data dir / shortcut", "if", "name", "in", "set", "(", "[", "d", ".", "name", "for", "d", "in", "data_path", ".", "iterdir", "(", ")", "]", ")", ":", "return", "load_model_from_link", "(", "name", ",", "*", "*", "overrides", ")", "if", "is_package", "(", "name", ")", ":", "# installed as package", "return", "load_model_from_package", "(", "name", ",", "*", "*", "overrides", ")", "if", "Path", "(", "name", ")", ".", "exists", "(", ")", ":", "# path to model data directory", "return", "load_model_from_path", "(", "Path", "(", "name", ")", ",", "*", "*", "overrides", ")", "elif", "hasattr", "(", "name", ",", "\"exists\"", ")", ":", "# Path or Path-like to model data", "return", "load_model_from_path", "(", "name", ",", "*", "*", "overrides", ")", "raise", "IOError", "(", "Errors", ".", "E050", ".", "format", "(", "name", "=", "name", ")", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
load_model_from_link
Load a model from a shortcut link, or directory in spaCy data path.
spacy/util.py
def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / "__init__.py" try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides)
def load_model_from_link(name, **overrides): """Load a model from a shortcut link, or directory in spaCy data path.""" path = get_data_path() / name / "__init__.py" try: cls = import_file(name, path) except AttributeError: raise IOError(Errors.E051.format(name=name)) return cls.load(**overrides)
[ "Load", "a", "model", "from", "a", "shortcut", "link", "or", "directory", "in", "spaCy", "data", "path", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L139-L146
[ "def", "load_model_from_link", "(", "name", ",", "*", "*", "overrides", ")", ":", "path", "=", "get_data_path", "(", ")", "/", "name", "/", "\"__init__.py\"", "try", ":", "cls", "=", "import_file", "(", "name", ",", "path", ")", "except", "AttributeError", ":", "raise", "IOError", "(", "Errors", ".", "E051", ".", "format", "(", "name", "=", "name", ")", ")", "return", "cls", ".", "load", "(", "*", "*", "overrides", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
load_model_from_package
Load a model from an installed package.
spacy/util.py
def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides)
def load_model_from_package(name, **overrides): """Load a model from an installed package.""" cls = importlib.import_module(name) return cls.load(**overrides)
[ "Load", "a", "model", "from", "an", "installed", "package", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L149-L152
[ "def", "load_model_from_package", "(", "name", ",", "*", "*", "overrides", ")", ":", "cls", "=", "importlib", ".", "import_module", "(", "name", ")", "return", "cls", ".", "load", "(", "*", "*", "overrides", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
load_model_from_path
Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.
spacy/util.py
def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" if not meta: meta = get_model_meta(model_path) cls = get_lang_class(meta["lang"]) nlp = cls(meta=meta, **overrides) pipeline = meta.get("pipeline", []) disable = overrides.get("disable", []) if pipeline is True: pipeline = nlp.Defaults.pipe_names elif pipeline in (False, None): pipeline = [] for name in pipeline: if name not in disable: config = meta.get("pipeline_args", {}).get(name, {}) component = nlp.create_pipe(name, config=config) nlp.add_pipe(component, name=name) return nlp.from_disk(model_path)
def load_model_from_path(model_path, meta=False, **overrides): """Load a model from a data directory path. Creates Language class with pipeline from meta.json and then calls from_disk() with path.""" if not meta: meta = get_model_meta(model_path) cls = get_lang_class(meta["lang"]) nlp = cls(meta=meta, **overrides) pipeline = meta.get("pipeline", []) disable = overrides.get("disable", []) if pipeline is True: pipeline = nlp.Defaults.pipe_names elif pipeline in (False, None): pipeline = [] for name in pipeline: if name not in disable: config = meta.get("pipeline_args", {}).get(name, {}) component = nlp.create_pipe(name, config=config) nlp.add_pipe(component, name=name) return nlp.from_disk(model_path)
[ "Load", "a", "model", "from", "a", "data", "directory", "path", ".", "Creates", "Language", "class", "with", "pipeline", "from", "meta", ".", "json", "and", "then", "calls", "from_disk", "()", "with", "path", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L155-L173
[ "def", "load_model_from_path", "(", "model_path", ",", "meta", "=", "False", ",", "*", "*", "overrides", ")", ":", "if", "not", "meta", ":", "meta", "=", "get_model_meta", "(", "model_path", ")", "cls", "=", "get_lang_class", "(", "meta", "[", "\"lang\"", "]", ")", "nlp", "=", "cls", "(", "meta", "=", "meta", ",", "*", "*", "overrides", ")", "pipeline", "=", "meta", ".", "get", "(", "\"pipeline\"", ",", "[", "]", ")", "disable", "=", "overrides", ".", "get", "(", "\"disable\"", ",", "[", "]", ")", "if", "pipeline", "is", "True", ":", "pipeline", "=", "nlp", ".", "Defaults", ".", "pipe_names", "elif", "pipeline", "in", "(", "False", ",", "None", ")", ":", "pipeline", "=", "[", "]", "for", "name", "in", "pipeline", ":", "if", "name", "not", "in", "disable", ":", "config", "=", "meta", ".", "get", "(", "\"pipeline_args\"", ",", "{", "}", ")", ".", "get", "(", "name", ",", "{", "}", ")", "component", "=", "nlp", ".", "create_pipe", "(", "name", ",", "config", "=", "config", ")", "nlp", ".", "add_pipe", "(", "component", ",", "name", "=", "name", ")", "return", "nlp", ".", "from_disk", "(", "model_path", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709
train
load_model_from_init_py
Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model.
spacy/util.py
def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = "%s_%s-%s" % (meta["lang"], meta["name"], meta["version"]) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides)
def load_model_from_init_py(init_file, **overrides): """Helper function to use in the `load()` method of a model package's __init__.py. init_file (unicode): Path to model's __init__.py, i.e. `__file__`. **overrides: Specific overrides, like pipeline components to disable. RETURNS (Language): `Language` class with loaded model. """ model_path = Path(init_file).parent meta = get_model_meta(model_path) data_dir = "%s_%s-%s" % (meta["lang"], meta["name"], meta["version"]) data_path = model_path / data_dir if not model_path.exists(): raise IOError(Errors.E052.format(path=path2str(data_path))) return load_model_from_path(data_path, meta, **overrides)
[ "Helper", "function", "to", "use", "in", "the", "load", "()", "method", "of", "a", "model", "package", "s", "__init__", ".", "py", "." ]
explosion/spaCy
python
https://github.com/explosion/spaCy/blob/8ee4100f8ffb336886208a1ea827bf4c745e2709/spacy/util.py#L176-L190
[ "def", "load_model_from_init_py", "(", "init_file", ",", "*", "*", "overrides", ")", ":", "model_path", "=", "Path", "(", "init_file", ")", ".", "parent", "meta", "=", "get_model_meta", "(", "model_path", ")", "data_dir", "=", "\"%s_%s-%s\"", "%", "(", "meta", "[", "\"lang\"", "]", ",", "meta", "[", "\"name\"", "]", ",", "meta", "[", "\"version\"", "]", ")", "data_path", "=", "model_path", "/", "data_dir", "if", "not", "model_path", ".", "exists", "(", ")", ":", "raise", "IOError", "(", "Errors", ".", "E052", ".", "format", "(", "path", "=", "path2str", "(", "data_path", ")", ")", ")", "return", "load_model_from_path", "(", "data_path", ",", "meta", ",", "*", "*", "overrides", ")" ]
8ee4100f8ffb336886208a1ea827bf4c745e2709