repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
wiredrive/wtframework
wtframework/wtf/assets.py
AssetManager.get_asset_path
def get_asset_path(self, filename): """ Get the full system path of a given asset if it exists. Otherwise it throws an error. Args: filename (str) - File name of a file in /assets folder to fetch the path for. Returns: str - path to the target file. Raises: AssetNotFoundError - if asset does not exist in the asset folder. Usage:: path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png") # path = /your/workspace/location/WTFProjectName/assets/my_asset.png """ if os.path.exists(os.path.join(self._asset_path, filename)): return os.path.join(self._asset_path, filename) else: raise AssetNotFoundError( u("Cannot find asset: {0}").format(filename))
python
def get_asset_path(self, filename): """ Get the full system path of a given asset if it exists. Otherwise it throws an error. Args: filename (str) - File name of a file in /assets folder to fetch the path for. Returns: str - path to the target file. Raises: AssetNotFoundError - if asset does not exist in the asset folder. Usage:: path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png") # path = /your/workspace/location/WTFProjectName/assets/my_asset.png """ if os.path.exists(os.path.join(self._asset_path, filename)): return os.path.join(self._asset_path, filename) else: raise AssetNotFoundError( u("Cannot find asset: {0}").format(filename))
[ "def", "get_asset_path", "(", "self", ",", "filename", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_asset_path", ",", "filename", ")", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_asset_path", ",", "filename", ")", "else", ":", "raise", "AssetNotFoundError", "(", "u", "(", "\"Cannot find asset: {0}\"", ")", ".", "format", "(", "filename", ")", ")" ]
Get the full system path of a given asset if it exists. Otherwise it throws an error. Args: filename (str) - File name of a file in /assets folder to fetch the path for. Returns: str - path to the target file. Raises: AssetNotFoundError - if asset does not exist in the asset folder. Usage:: path = WTF_ASSET_MANAGER.get_asset_path("my_asset.png") # path = /your/workspace/location/WTFProjectName/assets/my_asset.png
[ "Get", "the", "full", "system", "path", "of", "a", "given", "asset", "if", "it", "exists", ".", "Otherwise", "it", "throws", "an", "error", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/assets.py#L47-L70
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.create_webdriver
def create_webdriver(self, testname=None): ''' Creates an instance of Selenium webdriver based on config settings. This should only be called by a shutdown hook. Do not call directly within a test. Kwargs: testname: Optional test name to pass, this gets appended to the test name sent to selenium grid. Returns: WebDriver - Selenium Webdriver instance. ''' try: driver_type = self._config_reader.get( self.DRIVER_TYPE_CONFIG) except: driver_type = self.DRIVER_TYPE_LOCAL _wtflog.warn("%s setting is missing from config. Using default setting, %s", self.DRIVER_TYPE_CONFIG, driver_type) if driver_type == self.DRIVER_TYPE_REMOTE: # Create desired capabilities. self.webdriver = self.__create_remote_webdriver_from_config( testname=testname) else: # handle as local webdriver self.webdriver = self.__create_driver_from_browser_config() try: self.webdriver.maximize_window() except: # wait a short period and try again. time.sleep(self._timeout_mgr.BRIEF) try: self.webdriver.maximize_window() except Exception as e: if (isinstance(e, WebDriverException) and "implemented" in e.msg.lower()): pass # Maximizing window not supported by this webdriver. else: _wtflog.warn("Unable to maxmize browser window. " + "It may be possible the browser did not instantiate correctly. % s", e) return self.webdriver
python
def create_webdriver(self, testname=None): ''' Creates an instance of Selenium webdriver based on config settings. This should only be called by a shutdown hook. Do not call directly within a test. Kwargs: testname: Optional test name to pass, this gets appended to the test name sent to selenium grid. Returns: WebDriver - Selenium Webdriver instance. ''' try: driver_type = self._config_reader.get( self.DRIVER_TYPE_CONFIG) except: driver_type = self.DRIVER_TYPE_LOCAL _wtflog.warn("%s setting is missing from config. Using default setting, %s", self.DRIVER_TYPE_CONFIG, driver_type) if driver_type == self.DRIVER_TYPE_REMOTE: # Create desired capabilities. self.webdriver = self.__create_remote_webdriver_from_config( testname=testname) else: # handle as local webdriver self.webdriver = self.__create_driver_from_browser_config() try: self.webdriver.maximize_window() except: # wait a short period and try again. time.sleep(self._timeout_mgr.BRIEF) try: self.webdriver.maximize_window() except Exception as e: if (isinstance(e, WebDriverException) and "implemented" in e.msg.lower()): pass # Maximizing window not supported by this webdriver. else: _wtflog.warn("Unable to maxmize browser window. " + "It may be possible the browser did not instantiate correctly. % s", e) return self.webdriver
[ "def", "create_webdriver", "(", "self", ",", "testname", "=", "None", ")", ":", "try", ":", "driver_type", "=", "self", ".", "_config_reader", ".", "get", "(", "self", ".", "DRIVER_TYPE_CONFIG", ")", "except", ":", "driver_type", "=", "self", ".", "DRIVER_TYPE_LOCAL", "_wtflog", ".", "warn", "(", "\"%s setting is missing from config. Using default setting, %s\"", ",", "self", ".", "DRIVER_TYPE_CONFIG", ",", "driver_type", ")", "if", "driver_type", "==", "self", ".", "DRIVER_TYPE_REMOTE", ":", "# Create desired capabilities.", "self", ".", "webdriver", "=", "self", ".", "__create_remote_webdriver_from_config", "(", "testname", "=", "testname", ")", "else", ":", "# handle as local webdriver", "self", ".", "webdriver", "=", "self", ".", "__create_driver_from_browser_config", "(", ")", "try", ":", "self", ".", "webdriver", ".", "maximize_window", "(", ")", "except", ":", "# wait a short period and try again.", "time", ".", "sleep", "(", "self", ".", "_timeout_mgr", ".", "BRIEF", ")", "try", ":", "self", ".", "webdriver", ".", "maximize_window", "(", ")", "except", "Exception", "as", "e", ":", "if", "(", "isinstance", "(", "e", ",", "WebDriverException", ")", "and", "\"implemented\"", "in", "e", ".", "msg", ".", "lower", "(", ")", ")", ":", "pass", "# Maximizing window not supported by this webdriver.", "else", ":", "_wtflog", ".", "warn", "(", "\"Unable to maxmize browser window. \"", "+", "\"It may be possible the browser did not instantiate correctly. % s\"", ",", "e", ")", "return", "self", ".", "webdriver" ]
Creates an instance of Selenium webdriver based on config settings. This should only be called by a shutdown hook. Do not call directly within a test. Kwargs: testname: Optional test name to pass, this gets appended to the test name sent to selenium grid. Returns: WebDriver - Selenium Webdriver instance.
[ "Creates", "an", "instance", "of", "Selenium", "webdriver", "based", "on", "config", "settings", ".", "This", "should", "only", "be", "called", "by", "a", "shutdown", "hook", ".", "Do", "not", "call", "directly", "within", "a", "test", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L116-L161
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.__create_driver_from_browser_config
def __create_driver_from_browser_config(self): ''' Reads the config value for browser type. ''' try: browser_type = self._config_reader.get( WebDriverFactory.BROWSER_TYPE_CONFIG) except KeyError: _wtflog("%s missing is missing from config file. Using defaults", WebDriverFactory.BROWSER_TYPE_CONFIG) browser_type = WebDriverFactory.FIREFOX # Special Chrome Sauce options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) options.add_argument("always-authorize-plugins") browser_type_dict = { self.CHROME: lambda: webdriver.Chrome( self._config_reader.get(WebDriverFactory.CHROME_DRIVER_PATH), chrome_options=options), self.FIREFOX: lambda: webdriver.Firefox(), self.INTERNETEXPLORER: lambda: webdriver.Ie(), self.OPERA: lambda: webdriver.Opera(), self.PHANTOMJS: lambda: self.__create_phantom_js_driver(), self.SAFARI: lambda: self.__create_safari_driver() } try: return browser_type_dict[browser_type]() except KeyError: raise TypeError( u("Unsupported Browser Type {0}").format(browser_type))
python
def __create_driver_from_browser_config(self): ''' Reads the config value for browser type. ''' try: browser_type = self._config_reader.get( WebDriverFactory.BROWSER_TYPE_CONFIG) except KeyError: _wtflog("%s missing is missing from config file. Using defaults", WebDriverFactory.BROWSER_TYPE_CONFIG) browser_type = WebDriverFactory.FIREFOX # Special Chrome Sauce options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ["ignore-certificate-errors"]) options.add_argument("always-authorize-plugins") browser_type_dict = { self.CHROME: lambda: webdriver.Chrome( self._config_reader.get(WebDriverFactory.CHROME_DRIVER_PATH), chrome_options=options), self.FIREFOX: lambda: webdriver.Firefox(), self.INTERNETEXPLORER: lambda: webdriver.Ie(), self.OPERA: lambda: webdriver.Opera(), self.PHANTOMJS: lambda: self.__create_phantom_js_driver(), self.SAFARI: lambda: self.__create_safari_driver() } try: return browser_type_dict[browser_type]() except KeyError: raise TypeError( u("Unsupported Browser Type {0}").format(browser_type))
[ "def", "__create_driver_from_browser_config", "(", "self", ")", ":", "try", ":", "browser_type", "=", "self", ".", "_config_reader", ".", "get", "(", "WebDriverFactory", ".", "BROWSER_TYPE_CONFIG", ")", "except", "KeyError", ":", "_wtflog", "(", "\"%s missing is missing from config file. Using defaults\"", ",", "WebDriverFactory", ".", "BROWSER_TYPE_CONFIG", ")", "browser_type", "=", "WebDriverFactory", ".", "FIREFOX", "# Special Chrome Sauce", "options", "=", "webdriver", ".", "ChromeOptions", "(", ")", "options", ".", "add_experimental_option", "(", "\"excludeSwitches\"", ",", "[", "\"ignore-certificate-errors\"", "]", ")", "options", ".", "add_argument", "(", "\"always-authorize-plugins\"", ")", "browser_type_dict", "=", "{", "self", ".", "CHROME", ":", "lambda", ":", "webdriver", ".", "Chrome", "(", "self", ".", "_config_reader", ".", "get", "(", "WebDriverFactory", ".", "CHROME_DRIVER_PATH", ")", ",", "chrome_options", "=", "options", ")", ",", "self", ".", "FIREFOX", ":", "lambda", ":", "webdriver", ".", "Firefox", "(", ")", ",", "self", ".", "INTERNETEXPLORER", ":", "lambda", ":", "webdriver", ".", "Ie", "(", ")", ",", "self", ".", "OPERA", ":", "lambda", ":", "webdriver", ".", "Opera", "(", ")", ",", "self", ".", "PHANTOMJS", ":", "lambda", ":", "self", ".", "__create_phantom_js_driver", "(", ")", ",", "self", ".", "SAFARI", ":", "lambda", ":", "self", ".", "__create_safari_driver", "(", ")", "}", "try", ":", "return", "browser_type_dict", "[", "browser_type", "]", "(", ")", "except", "KeyError", ":", "raise", "TypeError", "(", "u", "(", "\"Unsupported Browser Type {0}\"", ")", ".", "format", "(", "browser_type", ")", ")" ]
Reads the config value for browser type.
[ "Reads", "the", "config", "value", "for", "browser", "type", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L163-L195
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.__create_safari_driver
def __create_safari_driver(self): ''' Creates an instance of Safari webdriver. ''' # Check for selenium jar env file needed for safari driver. if not os.getenv(self.__SELENIUM_SERVER_JAR_ENV): # If not set, check if we have a config setting for it. try: selenium_server_path = self._config_reader.get( self.SELENIUM_SERVER_LOCATION) self._env_vars[ self.__SELENIUM_SERVER_JAR_ENV] = selenium_server_path except KeyError: raise RuntimeError(u("Missing selenium server path config {0}.").format( self.SELENIUM_SERVER_LOCATION)) return webdriver.Safari()
python
def __create_safari_driver(self): ''' Creates an instance of Safari webdriver. ''' # Check for selenium jar env file needed for safari driver. if not os.getenv(self.__SELENIUM_SERVER_JAR_ENV): # If not set, check if we have a config setting for it. try: selenium_server_path = self._config_reader.get( self.SELENIUM_SERVER_LOCATION) self._env_vars[ self.__SELENIUM_SERVER_JAR_ENV] = selenium_server_path except KeyError: raise RuntimeError(u("Missing selenium server path config {0}.").format( self.SELENIUM_SERVER_LOCATION)) return webdriver.Safari()
[ "def", "__create_safari_driver", "(", "self", ")", ":", "# Check for selenium jar env file needed for safari driver.", "if", "not", "os", ".", "getenv", "(", "self", ".", "__SELENIUM_SERVER_JAR_ENV", ")", ":", "# If not set, check if we have a config setting for it.", "try", ":", "selenium_server_path", "=", "self", ".", "_config_reader", ".", "get", "(", "self", ".", "SELENIUM_SERVER_LOCATION", ")", "self", ".", "_env_vars", "[", "self", ".", "__SELENIUM_SERVER_JAR_ENV", "]", "=", "selenium_server_path", "except", "KeyError", ":", "raise", "RuntimeError", "(", "u", "(", "\"Missing selenium server path config {0}.\"", ")", ".", "format", "(", "self", ".", "SELENIUM_SERVER_LOCATION", ")", ")", "return", "webdriver", ".", "Safari", "(", ")" ]
Creates an instance of Safari webdriver.
[ "Creates", "an", "instance", "of", "Safari", "webdriver", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L198-L214
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.__create_phantom_js_driver
def __create_phantom_js_driver(self): ''' Creates an instance of PhantomJS driver. ''' try: return webdriver.PhantomJS(executable_path=self._config_reader.get(self.PHANTOMEJS_EXEC_PATH), service_args=['--ignore-ssl-errors=true']) except KeyError: return webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
python
def __create_phantom_js_driver(self): ''' Creates an instance of PhantomJS driver. ''' try: return webdriver.PhantomJS(executable_path=self._config_reader.get(self.PHANTOMEJS_EXEC_PATH), service_args=['--ignore-ssl-errors=true']) except KeyError: return webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'])
[ "def", "__create_phantom_js_driver", "(", "self", ")", ":", "try", ":", "return", "webdriver", ".", "PhantomJS", "(", "executable_path", "=", "self", ".", "_config_reader", ".", "get", "(", "self", ".", "PHANTOMEJS_EXEC_PATH", ")", ",", "service_args", "=", "[", "'--ignore-ssl-errors=true'", "]", ")", "except", "KeyError", ":", "return", "webdriver", ".", "PhantomJS", "(", "service_args", "=", "[", "'--ignore-ssl-errors=true'", "]", ")" ]
Creates an instance of PhantomJS driver.
[ "Creates", "an", "instance", "of", "PhantomJS", "driver", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L216-L224
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverFactory.__create_remote_webdriver_from_config
def __create_remote_webdriver_from_config(self, testname=None): ''' Reads the config value for browser type. ''' desired_capabilities = self._generate_desired_capabilities(testname) remote_url = self._config_reader.get( WebDriverFactory.REMOTE_URL_CONFIG) # Instantiate remote webdriver. driver = webdriver.Remote( desired_capabilities=desired_capabilities, command_executor=remote_url ) # Log IP Address of node if configured, so it can be used to # troubleshoot issues if they occur. log_driver_props = \ self._config_reader.get( WebDriverFactory.LOG_REMOTEDRIVER_PROPS, default_value=False ) in [True, "true", "TRUE", "True"] if "wd/hub" in remote_url and log_driver_props: try: grid_addr = remote_url[:remote_url.index("wd/hub")] info_request_response = urllib2.urlopen( grid_addr + "grid/api/testsession?session=" + driver.session_id, "", 5000) node_info = info_request_response.read() _wtflog.info( u("RemoteWebdriver using node: ") + u(node_info).strip()) except: # Unable to get IP Address of remote webdriver. # This happens with many 3rd party grid providers as they don't want you accessing info on nodes on # their internal network. pass return driver
python
def __create_remote_webdriver_from_config(self, testname=None): ''' Reads the config value for browser type. ''' desired_capabilities = self._generate_desired_capabilities(testname) remote_url = self._config_reader.get( WebDriverFactory.REMOTE_URL_CONFIG) # Instantiate remote webdriver. driver = webdriver.Remote( desired_capabilities=desired_capabilities, command_executor=remote_url ) # Log IP Address of node if configured, so it can be used to # troubleshoot issues if they occur. log_driver_props = \ self._config_reader.get( WebDriverFactory.LOG_REMOTEDRIVER_PROPS, default_value=False ) in [True, "true", "TRUE", "True"] if "wd/hub" in remote_url and log_driver_props: try: grid_addr = remote_url[:remote_url.index("wd/hub")] info_request_response = urllib2.urlopen( grid_addr + "grid/api/testsession?session=" + driver.session_id, "", 5000) node_info = info_request_response.read() _wtflog.info( u("RemoteWebdriver using node: ") + u(node_info).strip()) except: # Unable to get IP Address of remote webdriver. # This happens with many 3rd party grid providers as they don't want you accessing info on nodes on # their internal network. pass return driver
[ "def", "__create_remote_webdriver_from_config", "(", "self", ",", "testname", "=", "None", ")", ":", "desired_capabilities", "=", "self", ".", "_generate_desired_capabilities", "(", "testname", ")", "remote_url", "=", "self", ".", "_config_reader", ".", "get", "(", "WebDriverFactory", ".", "REMOTE_URL_CONFIG", ")", "# Instantiate remote webdriver.", "driver", "=", "webdriver", ".", "Remote", "(", "desired_capabilities", "=", "desired_capabilities", ",", "command_executor", "=", "remote_url", ")", "# Log IP Address of node if configured, so it can be used to", "# troubleshoot issues if they occur.", "log_driver_props", "=", "self", ".", "_config_reader", ".", "get", "(", "WebDriverFactory", ".", "LOG_REMOTEDRIVER_PROPS", ",", "default_value", "=", "False", ")", "in", "[", "True", ",", "\"true\"", ",", "\"TRUE\"", ",", "\"True\"", "]", "if", "\"wd/hub\"", "in", "remote_url", "and", "log_driver_props", ":", "try", ":", "grid_addr", "=", "remote_url", "[", ":", "remote_url", ".", "index", "(", "\"wd/hub\"", ")", "]", "info_request_response", "=", "urllib2", ".", "urlopen", "(", "grid_addr", "+", "\"grid/api/testsession?session=\"", "+", "driver", ".", "session_id", ",", "\"\"", ",", "5000", ")", "node_info", "=", "info_request_response", ".", "read", "(", ")", "_wtflog", ".", "info", "(", "u", "(", "\"RemoteWebdriver using node: \"", ")", "+", "u", "(", "node_info", ")", ".", "strip", "(", ")", ")", "except", ":", "# Unable to get IP Address of remote webdriver.", "# This happens with many 3rd party grid providers as they don't want you accessing info on nodes on", "# their internal network.", "pass", "return", "driver" ]
Reads the config value for browser type.
[ "Reads", "the", "config", "value", "for", "browser", "type", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L226-L261
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.clean_up_webdrivers
def clean_up_webdrivers(self): ''' Clean up webdrivers created during execution. ''' # Quit webdrivers. _wtflog.info("WebdriverManager: Cleaning up webdrivers") try: if self.__use_shutdown_hook: for key in self.__registered_drivers.keys(): for driver in self.__registered_drivers[key]: try: _wtflog.debug( "Shutdown hook closing Webdriver for thread: %s", key) driver.quit() except: pass except: pass
python
def clean_up_webdrivers(self): ''' Clean up webdrivers created during execution. ''' # Quit webdrivers. _wtflog.info("WebdriverManager: Cleaning up webdrivers") try: if self.__use_shutdown_hook: for key in self.__registered_drivers.keys(): for driver in self.__registered_drivers[key]: try: _wtflog.debug( "Shutdown hook closing Webdriver for thread: %s", key) driver.quit() except: pass except: pass
[ "def", "clean_up_webdrivers", "(", "self", ")", ":", "# Quit webdrivers.", "_wtflog", ".", "info", "(", "\"WebdriverManager: Cleaning up webdrivers\"", ")", "try", ":", "if", "self", ".", "__use_shutdown_hook", ":", "for", "key", "in", "self", ".", "__registered_drivers", ".", "keys", "(", ")", ":", "for", "driver", "in", "self", ".", "__registered_drivers", "[", "key", "]", ":", "try", ":", "_wtflog", ".", "debug", "(", "\"Shutdown hook closing Webdriver for thread: %s\"", ",", "key", ")", "driver", ".", "quit", "(", ")", "except", ":", "pass", "except", ":", "pass" ]
Clean up webdrivers created during execution.
[ "Clean", "up", "webdrivers", "created", "during", "execution", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L402-L419
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.close_driver
def close_driver(self): """ Close current running instance of Webdriver. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") WTF_WEBDRIVER_MANAGER.close_driver() """ channel = self.__get_channel() driver = self.__get_driver_for_channel(channel) if self.__config.get(self.REUSE_BROWSER, True): # If reuse browser is set, we'll avoid closing it and just clear out the cookies, # and reset the location. try: driver.delete_all_cookies() # check to see if webdriver is still responding driver.get("about:blank") except: pass if driver is not None: try: driver.quit() except: pass self.__unregister_driver(channel) if driver in self.__registered_drivers[channel]: self.__registered_drivers[channel].remove(driver) self.webdriver = None
python
def close_driver(self): """ Close current running instance of Webdriver. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") WTF_WEBDRIVER_MANAGER.close_driver() """ channel = self.__get_channel() driver = self.__get_driver_for_channel(channel) if self.__config.get(self.REUSE_BROWSER, True): # If reuse browser is set, we'll avoid closing it and just clear out the cookies, # and reset the location. try: driver.delete_all_cookies() # check to see if webdriver is still responding driver.get("about:blank") except: pass if driver is not None: try: driver.quit() except: pass self.__unregister_driver(channel) if driver in self.__registered_drivers[channel]: self.__registered_drivers[channel].remove(driver) self.webdriver = None
[ "def", "close_driver", "(", "self", ")", ":", "channel", "=", "self", ".", "__get_channel", "(", ")", "driver", "=", "self", ".", "__get_driver_for_channel", "(", "channel", ")", "if", "self", ".", "__config", ".", "get", "(", "self", ".", "REUSE_BROWSER", ",", "True", ")", ":", "# If reuse browser is set, we'll avoid closing it and just clear out the cookies,", "# and reset the location.", "try", ":", "driver", ".", "delete_all_cookies", "(", ")", "# check to see if webdriver is still responding", "driver", ".", "get", "(", "\"about:blank\"", ")", "except", ":", "pass", "if", "driver", "is", "not", "None", ":", "try", ":", "driver", ".", "quit", "(", ")", "except", ":", "pass", "self", ".", "__unregister_driver", "(", "channel", ")", "if", "driver", "in", "self", ".", "__registered_drivers", "[", "channel", "]", ":", "self", ".", "__registered_drivers", "[", "channel", "]", ".", "remove", "(", "driver", ")", "self", ".", "webdriver", "=", "None" ]
Close current running instance of Webdriver. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") WTF_WEBDRIVER_MANAGER.close_driver()
[ "Close", "current", "running", "instance", "of", "Webdriver", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L421-L453
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.get_driver
def get_driver(self): ''' Get an already running instance of Webdriver. If there is none, it will create one. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") same_driver = WTF_WEBDRIVER_MANAGER.get_driver() print(driver is same_driver) # True ''' driver = self.__get_driver_for_channel(self.__get_channel()) if driver is None: driver = self.new_driver() return driver
python
def get_driver(self): ''' Get an already running instance of Webdriver. If there is none, it will create one. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") same_driver = WTF_WEBDRIVER_MANAGER.get_driver() print(driver is same_driver) # True ''' driver = self.__get_driver_for_channel(self.__get_channel()) if driver is None: driver = self.new_driver() return driver
[ "def", "get_driver", "(", "self", ")", ":", "driver", "=", "self", ".", "__get_driver_for_channel", "(", "self", ".", "__get_channel", "(", ")", ")", "if", "driver", "is", "None", ":", "driver", "=", "self", ".", "new_driver", "(", ")", "return", "driver" ]
Get an already running instance of Webdriver. If there is none, it will create one. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") same_driver = WTF_WEBDRIVER_MANAGER.get_driver() print(driver is same_driver) # True
[ "Get", "an", "already", "running", "instance", "of", "Webdriver", ".", "If", "there", "is", "none", "it", "will", "create", "one", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L455-L473
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.new_driver
def new_driver(self, testname=None): ''' Used at a start of a test to get a new instance of WebDriver. If the 'resuebrowser' setting is true, it will use a recycled WebDriver instance with delete_all_cookies() called. Kwargs: testname (str) - Optional test name to pass to Selenium Grid. Helpful for labeling tests on 3rd party WebDriver cloud providers. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") ''' channel = self.__get_channel() # Get reference for the current driver. driver = self.__get_driver_for_channel(channel) if self.__config.get(WebDriverManager.REUSE_BROWSER, True): if driver is None: driver = self._webdriver_factory.create_webdriver( testname=testname) # Register webdriver so it can be retrieved by the manager and # cleaned up after exit. self.__register_driver(channel, driver) else: try: # Attempt to get the browser to a pristine state as possible when we are # reusing this for another test. driver.delete_all_cookies() # check to see if webdriver is still responding driver.get("about:blank") except: # In the case the browser is unhealthy, we should kill it # and serve a new one. try: if driver.is_online(): driver.quit() except: pass driver = self._webdriver_factory.create_webdriver( testname=testname) self.__register_driver(channel, driver) else: # Attempt to tear down any existing webdriver. if driver is not None: try: driver.quit() except: pass self.__unregister_driver(channel) driver = self._webdriver_factory.create_webdriver( testname=testname) self.__register_driver(channel, driver) return driver
python
def new_driver(self, testname=None): ''' Used at a start of a test to get a new instance of WebDriver. If the 'resuebrowser' setting is true, it will use a recycled WebDriver instance with delete_all_cookies() called. Kwargs: testname (str) - Optional test name to pass to Selenium Grid. Helpful for labeling tests on 3rd party WebDriver cloud providers. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com") ''' channel = self.__get_channel() # Get reference for the current driver. driver = self.__get_driver_for_channel(channel) if self.__config.get(WebDriverManager.REUSE_BROWSER, True): if driver is None: driver = self._webdriver_factory.create_webdriver( testname=testname) # Register webdriver so it can be retrieved by the manager and # cleaned up after exit. self.__register_driver(channel, driver) else: try: # Attempt to get the browser to a pristine state as possible when we are # reusing this for another test. driver.delete_all_cookies() # check to see if webdriver is still responding driver.get("about:blank") except: # In the case the browser is unhealthy, we should kill it # and serve a new one. try: if driver.is_online(): driver.quit() except: pass driver = self._webdriver_factory.create_webdriver( testname=testname) self.__register_driver(channel, driver) else: # Attempt to tear down any existing webdriver. if driver is not None: try: driver.quit() except: pass self.__unregister_driver(channel) driver = self._webdriver_factory.create_webdriver( testname=testname) self.__register_driver(channel, driver) return driver
[ "def", "new_driver", "(", "self", ",", "testname", "=", "None", ")", ":", "channel", "=", "self", ".", "__get_channel", "(", ")", "# Get reference for the current driver.", "driver", "=", "self", ".", "__get_driver_for_channel", "(", "channel", ")", "if", "self", ".", "__config", ".", "get", "(", "WebDriverManager", ".", "REUSE_BROWSER", ",", "True", ")", ":", "if", "driver", "is", "None", ":", "driver", "=", "self", ".", "_webdriver_factory", ".", "create_webdriver", "(", "testname", "=", "testname", ")", "# Register webdriver so it can be retrieved by the manager and", "# cleaned up after exit.", "self", ".", "__register_driver", "(", "channel", ",", "driver", ")", "else", ":", "try", ":", "# Attempt to get the browser to a pristine state as possible when we are", "# reusing this for another test.", "driver", ".", "delete_all_cookies", "(", ")", "# check to see if webdriver is still responding", "driver", ".", "get", "(", "\"about:blank\"", ")", "except", ":", "# In the case the browser is unhealthy, we should kill it", "# and serve a new one.", "try", ":", "if", "driver", ".", "is_online", "(", ")", ":", "driver", ".", "quit", "(", ")", "except", ":", "pass", "driver", "=", "self", ".", "_webdriver_factory", ".", "create_webdriver", "(", "testname", "=", "testname", ")", "self", ".", "__register_driver", "(", "channel", ",", "driver", ")", "else", ":", "# Attempt to tear down any existing webdriver.", "if", "driver", "is", "not", "None", ":", "try", ":", "driver", ".", "quit", "(", ")", "except", ":", "pass", "self", ".", "__unregister_driver", "(", "channel", ")", "driver", "=", "self", ".", "_webdriver_factory", ".", "create_webdriver", "(", "testname", "=", "testname", ")", "self", ".", "__register_driver", "(", "channel", ",", "driver", ")", "return", "driver" ]
Used at a start of a test to get a new instance of WebDriver. If the 'resuebrowser' setting is true, it will use a recycled WebDriver instance with delete_all_cookies() called. Kwargs: testname (str) - Optional test name to pass to Selenium Grid. Helpful for labeling tests on 3rd party WebDriver cloud providers. Returns: Webdriver - Selenium Webdriver instance. Usage:: driver = WTF_WEBDRIVER_MANAGER.new_driver() driver.get("http://the-internet.herokuapp.com")
[ "Used", "at", "a", "start", "of", "a", "test", "to", "get", "a", "new", "instance", "of", "WebDriver", ".", "If", "the", "resuebrowser", "setting", "is", "true", "it", "will", "use", "a", "recycled", "WebDriver", "instance", "with", "delete_all_cookies", "()", "called", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L488-L552
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.__register_driver
def __register_driver(self, channel, webdriver): "Register webdriver to a channel." # Add to list of webdrivers to cleanup. if not self.__registered_drivers.has_key(channel): self.__registered_drivers[channel] = [] # set to new empty array self.__registered_drivers[channel].append(webdriver) # Set singleton instance for the channel self.__webdriver[channel] = webdriver
python
def __register_driver(self, channel, webdriver): "Register webdriver to a channel." # Add to list of webdrivers to cleanup. if not self.__registered_drivers.has_key(channel): self.__registered_drivers[channel] = [] # set to new empty array self.__registered_drivers[channel].append(webdriver) # Set singleton instance for the channel self.__webdriver[channel] = webdriver
[ "def", "__register_driver", "(", "self", ",", "channel", ",", "webdriver", ")", ":", "# Add to list of webdrivers to cleanup.", "if", "not", "self", ".", "__registered_drivers", ".", "has_key", "(", "channel", ")", ":", "self", ".", "__registered_drivers", "[", "channel", "]", "=", "[", "]", "# set to new empty array", "self", ".", "__registered_drivers", "[", "channel", "]", ".", "append", "(", "webdriver", ")", "# Set singleton instance for the channel", "self", ".", "__webdriver", "[", "channel", "]", "=", "webdriver" ]
Register webdriver to a channel.
[ "Register", "webdriver", "to", "a", "channel", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L555-L565
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.__unregister_driver
def __unregister_driver(self, channel): "Unregister webdriver" driver = self.__get_driver_for_channel(channel) if self.__registered_drivers.has_key(channel) \ and driver in self.__registered_drivers[channel]: self.__registered_drivers[channel].remove(driver) self.__webdriver[channel] = None
python
def __unregister_driver(self, channel): "Unregister webdriver" driver = self.__get_driver_for_channel(channel) if self.__registered_drivers.has_key(channel) \ and driver in self.__registered_drivers[channel]: self.__registered_drivers[channel].remove(driver) self.__webdriver[channel] = None
[ "def", "__unregister_driver", "(", "self", ",", "channel", ")", ":", "driver", "=", "self", ".", "__get_driver_for_channel", "(", "channel", ")", "if", "self", ".", "__registered_drivers", ".", "has_key", "(", "channel", ")", "and", "driver", "in", "self", ".", "__registered_drivers", "[", "channel", "]", ":", "self", ".", "__registered_drivers", "[", "channel", "]", ".", "remove", "(", "driver", ")", "self", ".", "__webdriver", "[", "channel", "]", "=", "None" ]
Unregister webdriver
[ "Unregister", "webdriver" ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L567-L576
wiredrive/wtframework
wtframework/wtf/web/webdriver.py
WebDriverManager.__get_channel
def __get_channel(self): "Get the channel to register webdriver to." if self.__config.get(WebDriverManager.ENABLE_THREADING_SUPPORT, False): channel = current_thread().ident else: channel = 0 return channel
python
def __get_channel(self): "Get the channel to register webdriver to." if self.__config.get(WebDriverManager.ENABLE_THREADING_SUPPORT, False): channel = current_thread().ident else: channel = 0 return channel
[ "def", "__get_channel", "(", "self", ")", ":", "if", "self", ".", "__config", ".", "get", "(", "WebDriverManager", ".", "ENABLE_THREADING_SUPPORT", ",", "False", ")", ":", "channel", "=", "current_thread", "(", ")", ".", "ident", "else", ":", "channel", "=", "0", "return", "channel" ]
Get the channel to register webdriver to.
[ "Get", "the", "channel", "to", "register", "webdriver", "to", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webdriver.py#L585-L592
wiredrive/wtframework
wtframework/wtf/web/capture.py
WebScreenShotUtil.take_screenshot
def take_screenshot(webdriver, file_name): """ Captures a screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as. """ folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
python
def take_screenshot(webdriver, file_name): """ Captures a screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as. """ folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
[ "def", "take_screenshot", "(", "webdriver", ",", "file_name", ")", ":", "folder_location", "=", "os", ".", "path", ".", "join", "(", "ProjectUtils", ".", "get_project_root", "(", ")", ",", "WebScreenShotUtil", ".", "SCREEN_SHOT_LOCATION", ")", "WebScreenShotUtil", ".", "__capture_screenshot", "(", "webdriver", ",", "folder_location", ",", "file_name", "+", "\".png\"", ")" ]
Captures a screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as.
[ "Captures", "a", "screenshot", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/capture.py#L34-L47
wiredrive/wtframework
wtframework/wtf/web/capture.py
WebScreenShotUtil.take_reference_screenshot
def take_reference_screenshot(webdriver, file_name): """ Captures a screenshot as a reference screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as. """ folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
python
def take_reference_screenshot(webdriver, file_name): """ Captures a screenshot as a reference screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as. """ folder_location = os.path.join(ProjectUtils.get_project_root(), WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION) WebScreenShotUtil.__capture_screenshot( webdriver, folder_location, file_name + ".png")
[ "def", "take_reference_screenshot", "(", "webdriver", ",", "file_name", ")", ":", "folder_location", "=", "os", ".", "path", ".", "join", "(", "ProjectUtils", ".", "get_project_root", "(", ")", ",", "WebScreenShotUtil", ".", "REFERENCE_SCREEN_SHOT_LOCATION", ")", "WebScreenShotUtil", ".", "__capture_screenshot", "(", "webdriver", ",", "folder_location", ",", "file_name", "+", "\".png\"", ")" ]
Captures a screenshot as a reference screenshot. Args: webdriver (WebDriver) - Selenium webdriver. file_name (str) - File name to save screenshot as.
[ "Captures", "a", "screenshot", "as", "a", "reference", "screenshot", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/capture.py#L50-L62
wiredrive/wtframework
wtframework/wtf/web/capture.py
WebScreenShotUtil.__capture_screenshot
def __capture_screenshot(webdriver, folder_location, file_name): "Capture a screenshot" # Check folder location exists. if not os.path.exists(folder_location): os.makedirs(folder_location) file_location = os.path.join(folder_location, file_name) if isinstance(webdriver, remote.webdriver.WebDriver): # If this is a remote webdriver. We need to transmit the image data # back across system boundries as a base 64 encoded string so it can # be decoded back on the local system and written to disk. base64_data = webdriver.get_screenshot_as_base64() screenshot_data = base64.decodestring(base64_data) screenshot_file = open(file_location, "wb") screenshot_file.write(screenshot_data) screenshot_file.close() else: webdriver.save_screenshot(file_location)
python
def __capture_screenshot(webdriver, folder_location, file_name): "Capture a screenshot" # Check folder location exists. if not os.path.exists(folder_location): os.makedirs(folder_location) file_location = os.path.join(folder_location, file_name) if isinstance(webdriver, remote.webdriver.WebDriver): # If this is a remote webdriver. We need to transmit the image data # back across system boundries as a base 64 encoded string so it can # be decoded back on the local system and written to disk. base64_data = webdriver.get_screenshot_as_base64() screenshot_data = base64.decodestring(base64_data) screenshot_file = open(file_location, "wb") screenshot_file.write(screenshot_data) screenshot_file.close() else: webdriver.save_screenshot(file_location)
[ "def", "__capture_screenshot", "(", "webdriver", ",", "folder_location", ",", "file_name", ")", ":", "# Check folder location exists.", "if", "not", "os", ".", "path", ".", "exists", "(", "folder_location", ")", ":", "os", ".", "makedirs", "(", "folder_location", ")", "file_location", "=", "os", ".", "path", ".", "join", "(", "folder_location", ",", "file_name", ")", "if", "isinstance", "(", "webdriver", ",", "remote", ".", "webdriver", ".", "WebDriver", ")", ":", "# If this is a remote webdriver. We need to transmit the image data", "# back across system boundries as a base 64 encoded string so it can", "# be decoded back on the local system and written to disk.", "base64_data", "=", "webdriver", ".", "get_screenshot_as_base64", "(", ")", "screenshot_data", "=", "base64", ".", "decodestring", "(", "base64_data", ")", "screenshot_file", "=", "open", "(", "file_location", ",", "\"wb\"", ")", "screenshot_file", ".", "write", "(", "screenshot_data", ")", "screenshot_file", ".", "close", "(", ")", "else", ":", "webdriver", ".", "save_screenshot", "(", "file_location", ")" ]
Capture a screenshot
[ "Capture", "a", "screenshot" ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/capture.py#L65-L83
wiredrive/wtframework
wtframework/wtf/utils/project_utils.py
ProjectUtils.get_project_root
def get_project_root(cls): ''' Return path of the project directory. Use this method for getting paths relative to the project. However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended to use WTF_ASSET_MANAGER, which are already singleton instances that manger the /data, and /assets folder for you. Returns: str - path of project root directory. ''' if(cls.__root_folder__ != None): return cls.__root_folder__ # Check for enviornment variable override. try: cls.__root_folder__ = os.environ[cls.WTF_HOME_CONFIG_ENV_VAR] except KeyError: # Means WTF_HOME override isn't specified. pass # Search starting from the current working directory and traverse up parent directories for the # hidden file denoting the project root folder. path = os.getcwd() seperator_matches = re.finditer("/|\\\\", path) paths_to_search = [path] for match in seperator_matches: p = path[:match.start()] paths_to_search.insert(0, p) for path in paths_to_search: target_path = os.path.join(path, cls.__WTF_ROOT_FOLDER_FILE) if os.path.isfile(target_path): cls.__root_folder__ = path return cls.__root_folder__ raise RuntimeError(u("Missing root project folder locator file '.wtf_root_folder'.") + u("Check to make sure this file is located in your project directory."))
python
def get_project_root(cls): ''' Return path of the project directory. Use this method for getting paths relative to the project. However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended to use WTF_ASSET_MANAGER, which are already singleton instances that manger the /data, and /assets folder for you. Returns: str - path of project root directory. ''' if(cls.__root_folder__ != None): return cls.__root_folder__ # Check for enviornment variable override. try: cls.__root_folder__ = os.environ[cls.WTF_HOME_CONFIG_ENV_VAR] except KeyError: # Means WTF_HOME override isn't specified. pass # Search starting from the current working directory and traverse up parent directories for the # hidden file denoting the project root folder. path = os.getcwd() seperator_matches = re.finditer("/|\\\\", path) paths_to_search = [path] for match in seperator_matches: p = path[:match.start()] paths_to_search.insert(0, p) for path in paths_to_search: target_path = os.path.join(path, cls.__WTF_ROOT_FOLDER_FILE) if os.path.isfile(target_path): cls.__root_folder__ = path return cls.__root_folder__ raise RuntimeError(u("Missing root project folder locator file '.wtf_root_folder'.") + u("Check to make sure this file is located in your project directory."))
[ "def", "get_project_root", "(", "cls", ")", ":", "if", "(", "cls", ".", "__root_folder__", "!=", "None", ")", ":", "return", "cls", ".", "__root_folder__", "# Check for enviornment variable override.", "try", ":", "cls", ".", "__root_folder__", "=", "os", ".", "environ", "[", "cls", ".", "WTF_HOME_CONFIG_ENV_VAR", "]", "except", "KeyError", ":", "# Means WTF_HOME override isn't specified.", "pass", "# Search starting from the current working directory and traverse up parent directories for the", "# hidden file denoting the project root folder.", "path", "=", "os", ".", "getcwd", "(", ")", "seperator_matches", "=", "re", ".", "finditer", "(", "\"/|\\\\\\\\\"", ",", "path", ")", "paths_to_search", "=", "[", "path", "]", "for", "match", "in", "seperator_matches", ":", "p", "=", "path", "[", ":", "match", ".", "start", "(", ")", "]", "paths_to_search", ".", "insert", "(", "0", ",", "p", ")", "for", "path", "in", "paths_to_search", ":", "target_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "cls", ".", "__WTF_ROOT_FOLDER_FILE", ")", "if", "os", ".", "path", ".", "isfile", "(", "target_path", ")", ":", "cls", ".", "__root_folder__", "=", "path", "return", "cls", ".", "__root_folder__", "raise", "RuntimeError", "(", "u", "(", "\"Missing root project folder locator file '.wtf_root_folder'.\"", ")", "+", "u", "(", "\"Check to make sure this file is located in your project directory.\"", ")", ")" ]
Return path of the project directory. Use this method for getting paths relative to the project. However, for data, it's recommended you use WTF_DATA_MANAGER and for assets it's recommended to use WTF_ASSET_MANAGER, which are already singleton instances that manger the /data, and /assets folder for you. Returns: str - path of project root directory.
[ "Return", "path", "of", "the", "project", "directory", ".", "Use", "this", "method", "for", "getting", "paths", "relative", "to", "the", "project", ".", "However", "for", "data", "it", "s", "recommended", "you", "use", "WTF_DATA_MANAGER", "and", "for", "assets", "it", "s", "recommended", "to", "use", "WTF_ASSET_MANAGER", "which", "are", "already", "singleton", "instances", "that", "manger", "the", "/", "data", "and", "/", "assets", "folder", "for", "you", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/project_utils.py#L38-L75
wiredrive/wtframework
wtframework/wtf/utils/wait_utils.py
do_until
def do_until(lambda_expr, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, message=None): ''' A retry wrapper that'll keep performing the action until it succeeds. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: lambda_expr (lambda) : Expression to evaluate. Kwargs: timeout (number): Timeout period in seconds. sleep (number) : Sleep time to wait between iterations message (str) : Provide a message for TimeoutError raised. Returns: The value of the evaluated lambda expression. Usage:: do_until(lambda: driver.find_element_by_id("save").click(), timeout=30, sleep=0.5) Is equivalent to: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: return driver.find_element_by_id("save").click() except: pass time.sleep(0.5) raise OperationTimeoutError() ''' __check_condition_parameter_is_function(lambda_expr) end_time = datetime.now() + timedelta(seconds=timeout) last_exception = None while datetime.now() < end_time: try: return lambda_expr() except Exception as e: last_exception = e time.sleep(sleep) if message: raise OperationTimeoutError(message, last_exception) else: raise OperationTimeoutError("Operation timed out.", last_exception)
python
def do_until(lambda_expr, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, message=None): ''' A retry wrapper that'll keep performing the action until it succeeds. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: lambda_expr (lambda) : Expression to evaluate. Kwargs: timeout (number): Timeout period in seconds. sleep (number) : Sleep time to wait between iterations message (str) : Provide a message for TimeoutError raised. Returns: The value of the evaluated lambda expression. Usage:: do_until(lambda: driver.find_element_by_id("save").click(), timeout=30, sleep=0.5) Is equivalent to: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: return driver.find_element_by_id("save").click() except: pass time.sleep(0.5) raise OperationTimeoutError() ''' __check_condition_parameter_is_function(lambda_expr) end_time = datetime.now() + timedelta(seconds=timeout) last_exception = None while datetime.now() < end_time: try: return lambda_expr() except Exception as e: last_exception = e time.sleep(sleep) if message: raise OperationTimeoutError(message, last_exception) else: raise OperationTimeoutError("Operation timed out.", last_exception)
[ "def", "do_until", "(", "lambda_expr", ",", "timeout", "=", "WTF_TIMEOUT_MANAGER", ".", "NORMAL", ",", "sleep", "=", "0.5", ",", "message", "=", "None", ")", ":", "__check_condition_parameter_is_function", "(", "lambda_expr", ")", "end_time", "=", "datetime", ".", "now", "(", ")", "+", "timedelta", "(", "seconds", "=", "timeout", ")", "last_exception", "=", "None", "while", "datetime", ".", "now", "(", ")", "<", "end_time", ":", "try", ":", "return", "lambda_expr", "(", ")", "except", "Exception", "as", "e", ":", "last_exception", "=", "e", "time", ".", "sleep", "(", "sleep", ")", "if", "message", ":", "raise", "OperationTimeoutError", "(", "message", ",", "last_exception", ")", "else", ":", "raise", "OperationTimeoutError", "(", "\"Operation timed out.\"", ",", "last_exception", ")" ]
A retry wrapper that'll keep performing the action until it succeeds. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: lambda_expr (lambda) : Expression to evaluate. Kwargs: timeout (number): Timeout period in seconds. sleep (number) : Sleep time to wait between iterations message (str) : Provide a message for TimeoutError raised. Returns: The value of the evaluated lambda expression. Usage:: do_until(lambda: driver.find_element_by_id("save").click(), timeout=30, sleep=0.5) Is equivalent to: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: return driver.find_element_by_id("save").click() except: pass time.sleep(0.5) raise OperationTimeoutError()
[ "A", "retry", "wrapper", "that", "ll", "keep", "performing", "the", "action", "until", "it", "succeeds", ".", "(", "main", "differnce", "between", "do_until", "and", "wait_until", "is", "do_until", "will", "keep", "trying", "until", "a", "value", "is", "returned", "while", "wait", "until", "will", "wait", "until", "the", "function", "evaluates", "True", ".", ")" ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/wait_utils.py#L39-L88
wiredrive/wtframework
wtframework/wtf/utils/wait_utils.py
wait_and_ignore
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): ''' Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. Example:: wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): break; except: pass time.sleep(0.5) ''' try: return wait_until(condition, timeout, sleep) except: pass
python
def wait_and_ignore(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): ''' Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. Example:: wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): break; except: pass time.sleep(0.5) ''' try: return wait_until(condition, timeout, sleep) except: pass
[ "def", "wait_and_ignore", "(", "condition", ",", "timeout", "=", "WTF_TIMEOUT_MANAGER", ".", "NORMAL", ",", "sleep", "=", "0.5", ")", ":", "try", ":", "return", "wait_until", "(", "condition", ",", "timeout", ",", "sleep", ")", "except", ":", "pass" ]
Waits wrapper that'll wait for the condition to become true, but will not error if the condition isn't met. Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. Example:: wait_and_ignore(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): break; except: pass time.sleep(0.5)
[ "Waits", "wrapper", "that", "ll", "wait", "for", "the", "condition", "to", "become", "true", "but", "will", "not", "error", "if", "the", "condition", "isn", "t", "met", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/wait_utils.py#L91-L123
wiredrive/wtframework
wtframework/wtf/utils/wait_utils.py
wait_until
def wait_until(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, pass_exceptions=False, message=None): ''' Waits wrapper that'll wait for the condition to become true. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. pass_exceptions (bool) : If set true, any exceptions raised will be re-raised up the chain. Normally exceptions are ignored. message (str) : Optional message to pass into OperationTimeoutError if the wait times out. Example:: wait_until(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) did_succeed = False while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): did_succeed = True break; except: pass time.sleep(0.5) if not did_succeed: raise OperationTimeoutError() ''' __check_condition_parameter_is_function(condition) last_exception = None end_time = datetime.now() + timedelta(seconds=timeout) while datetime.now() < end_time: try: if condition(): return except Exception as e: if pass_exceptions: raise e else: last_exception = e time.sleep(sleep) if message: if last_exception: raise OperationTimeoutError(message, e) else: raise OperationTimeoutError(message) else: if last_exception: raise OperationTimeoutError("Operation timed out.", e) else: raise OperationTimeoutError("Operation timed out.")
python
def wait_until(condition, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5, pass_exceptions=False, message=None): ''' Waits wrapper that'll wait for the condition to become true. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. pass_exceptions (bool) : If set true, any exceptions raised will be re-raised up the chain. Normally exceptions are ignored. message (str) : Optional message to pass into OperationTimeoutError if the wait times out. Example:: wait_until(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) did_succeed = False while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): did_succeed = True break; except: pass time.sleep(0.5) if not did_succeed: raise OperationTimeoutError() ''' __check_condition_parameter_is_function(condition) last_exception = None end_time = datetime.now() + timedelta(seconds=timeout) while datetime.now() < end_time: try: if condition(): return except Exception as e: if pass_exceptions: raise e else: last_exception = e time.sleep(sleep) if message: if last_exception: raise OperationTimeoutError(message, e) else: raise OperationTimeoutError(message) else: if last_exception: raise OperationTimeoutError("Operation timed out.", e) else: raise OperationTimeoutError("Operation timed out.")
[ "def", "wait_until", "(", "condition", ",", "timeout", "=", "WTF_TIMEOUT_MANAGER", ".", "NORMAL", ",", "sleep", "=", "0.5", ",", "pass_exceptions", "=", "False", ",", "message", "=", "None", ")", ":", "__check_condition_parameter_is_function", "(", "condition", ")", "last_exception", "=", "None", "end_time", "=", "datetime", ".", "now", "(", ")", "+", "timedelta", "(", "seconds", "=", "timeout", ")", "while", "datetime", ".", "now", "(", ")", "<", "end_time", ":", "try", ":", "if", "condition", "(", ")", ":", "return", "except", "Exception", "as", "e", ":", "if", "pass_exceptions", ":", "raise", "e", "else", ":", "last_exception", "=", "e", "time", ".", "sleep", "(", "sleep", ")", "if", "message", ":", "if", "last_exception", ":", "raise", "OperationTimeoutError", "(", "message", ",", "e", ")", "else", ":", "raise", "OperationTimeoutError", "(", "message", ")", "else", ":", "if", "last_exception", ":", "raise", "OperationTimeoutError", "(", "\"Operation timed out.\"", ",", "e", ")", "else", ":", "raise", "OperationTimeoutError", "(", "\"Operation timed out.\"", ")" ]
Waits wrapper that'll wait for the condition to become true. (main differnce between do_until and wait_until is do_until will keep trying until a value is returned, while wait until will wait until the function evaluates True.) Args: condition (lambda) - Lambda expression to wait for to evaluate to True. Kwargs: timeout (number) : Maximum number of seconds to wait. sleep (number) : Sleep time to wait between iterations. pass_exceptions (bool) : If set true, any exceptions raised will be re-raised up the chain. Normally exceptions are ignored. message (str) : Optional message to pass into OperationTimeoutError if the wait times out. Example:: wait_until(lambda: driver.find_element_by_id("success").is_displayed(), timeout=30, sleep=0.5) is equivalent to:: end_time = datetime.now() + timedelta(seconds=30) did_succeed = False while datetime.now() < end_time: try: if driver.find_element_by_id("success").is_displayed(): did_succeed = True break; except: pass time.sleep(0.5) if not did_succeed: raise OperationTimeoutError()
[ "Waits", "wrapper", "that", "ll", "wait", "for", "the", "condition", "to", "become", "true", ".", "(", "main", "differnce", "between", "do_until", "and", "wait_until", "is", "do_until", "will", "keep", "trying", "until", "a", "value", "is", "returned", "while", "wait", "until", "will", "wait", "until", "the", "function", "evaluates", "True", ".", ")" ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/wait_utils.py#L125-L187
wiredrive/wtframework
wtframework/wtf/email.py
IMapEmailAccountObject.check_email_exists_by_subject
def check_email_exists_by_subject(self, subject, match_recipient=None): """ Searches for Email by Subject. Returns True or False. Args: subject (str): Subject to search for. Kwargs: match_recipient (str) : Recipient to match exactly. (don't care if not specified) Returns: True - email found, False - email not found """ # Select inbox to fetch the latest mail on server. self._mail.select("inbox") try: matches = self.__search_email_by_subject(subject, match_recipient) if len(matches) <= 0: return False else: return True except Exception as e: raise e
python
def check_email_exists_by_subject(self, subject, match_recipient=None): """ Searches for Email by Subject. Returns True or False. Args: subject (str): Subject to search for. Kwargs: match_recipient (str) : Recipient to match exactly. (don't care if not specified) Returns: True - email found, False - email not found """ # Select inbox to fetch the latest mail on server. self._mail.select("inbox") try: matches = self.__search_email_by_subject(subject, match_recipient) if len(matches) <= 0: return False else: return True except Exception as e: raise e
[ "def", "check_email_exists_by_subject", "(", "self", ",", "subject", ",", "match_recipient", "=", "None", ")", ":", "# Select inbox to fetch the latest mail on server.", "self", ".", "_mail", ".", "select", "(", "\"inbox\"", ")", "try", ":", "matches", "=", "self", ".", "__search_email_by_subject", "(", "subject", ",", "match_recipient", ")", "if", "len", "(", "matches", ")", "<=", "0", ":", "return", "False", "else", ":", "return", "True", "except", "Exception", "as", "e", ":", "raise", "e" ]
Searches for Email by Subject. Returns True or False. Args: subject (str): Subject to search for. Kwargs: match_recipient (str) : Recipient to match exactly. (don't care if not specified) Returns: True - email found, False - email not found
[ "Searches", "for", "Email", "by", "Subject", ".", "Returns", "True", "or", "False", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L65-L89
wiredrive/wtframework
wtframework/wtf/email.py
IMapEmailAccountObject.find_emails_by_subject
def find_emails_by_subject(self, subject, limit=50, match_recipient=None): """ Searches for Email by Subject. Returns email's imap message IDs as a list if matching subjects is found. Args: subject (str) - Subject to search for. Kwargs: limit (int) - Limit search to X number of matches, default 50 match_recipient (str) - Recipient to exactly (don't care if not specified) Returns: list - List of Integers representing imap message UIDs. """ # Select inbox to fetch the latest mail on server. self._mail.select("inbox") matching_uids = self.__search_email_by_subject( subject, match_recipient) return matching_uids
python
def find_emails_by_subject(self, subject, limit=50, match_recipient=None): """ Searches for Email by Subject. Returns email's imap message IDs as a list if matching subjects is found. Args: subject (str) - Subject to search for. Kwargs: limit (int) - Limit search to X number of matches, default 50 match_recipient (str) - Recipient to exactly (don't care if not specified) Returns: list - List of Integers representing imap message UIDs. """ # Select inbox to fetch the latest mail on server. self._mail.select("inbox") matching_uids = self.__search_email_by_subject( subject, match_recipient) return matching_uids
[ "def", "find_emails_by_subject", "(", "self", ",", "subject", ",", "limit", "=", "50", ",", "match_recipient", "=", "None", ")", ":", "# Select inbox to fetch the latest mail on server.", "self", ".", "_mail", ".", "select", "(", "\"inbox\"", ")", "matching_uids", "=", "self", ".", "__search_email_by_subject", "(", "subject", ",", "match_recipient", ")", "return", "matching_uids" ]
Searches for Email by Subject. Returns email's imap message IDs as a list if matching subjects is found. Args: subject (str) - Subject to search for. Kwargs: limit (int) - Limit search to X number of matches, default 50 match_recipient (str) - Recipient to exactly (don't care if not specified) Returns: list - List of Integers representing imap message UIDs.
[ "Searches", "for", "Email", "by", "Subject", ".", "Returns", "email", "s", "imap", "message", "IDs", "as", "a", "list", "if", "matching", "subjects", "is", "found", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L91-L113
wiredrive/wtframework
wtframework/wtf/email.py
IMapEmailAccountObject.get_email_message
def get_email_message(self, message_uid, message_type="text/plain"): """ Fetch contents of email. Args: message_uid (int): IMAP Message UID number. Kwargs: message_type: Can be 'text' or 'html' """ self._mail.select("inbox") result = self._mail.uid('fetch', message_uid, "(RFC822)") msg = email.message_from_string(result[1][0][1]) try: # Try to handle as multipart message first. for part in msg.walk(): if part.get_content_type() == message_type: return part.get_payload(decode=True) except: # handle as plain text email return msg.get_payload(decode=True)
python
def get_email_message(self, message_uid, message_type="text/plain"): """ Fetch contents of email. Args: message_uid (int): IMAP Message UID number. Kwargs: message_type: Can be 'text' or 'html' """ self._mail.select("inbox") result = self._mail.uid('fetch', message_uid, "(RFC822)") msg = email.message_from_string(result[1][0][1]) try: # Try to handle as multipart message first. for part in msg.walk(): if part.get_content_type() == message_type: return part.get_payload(decode=True) except: # handle as plain text email return msg.get_payload(decode=True)
[ "def", "get_email_message", "(", "self", ",", "message_uid", ",", "message_type", "=", "\"text/plain\"", ")", ":", "self", ".", "_mail", ".", "select", "(", "\"inbox\"", ")", "result", "=", "self", ".", "_mail", ".", "uid", "(", "'fetch'", ",", "message_uid", ",", "\"(RFC822)\"", ")", "msg", "=", "email", ".", "message_from_string", "(", "result", "[", "1", "]", "[", "0", "]", "[", "1", "]", ")", "try", ":", "# Try to handle as multipart message first.", "for", "part", "in", "msg", ".", "walk", "(", ")", ":", "if", "part", ".", "get_content_type", "(", ")", "==", "message_type", ":", "return", "part", ".", "get_payload", "(", "decode", "=", "True", ")", "except", ":", "# handle as plain text email", "return", "msg", ".", "get_payload", "(", "decode", "=", "True", ")" ]
Fetch contents of email. Args: message_uid (int): IMAP Message UID number. Kwargs: message_type: Can be 'text' or 'html'
[ "Fetch", "contents", "of", "email", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L115-L137
wiredrive/wtframework
wtframework/wtf/email.py
IMapEmailAccountObject.raw_search
def raw_search(self, *args, **kwargs): """ Find the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search through. date (datetime) - If specified, it will filter avoid checking messages older than this date. """ limit = 50 try: limit = kwargs['limit'] except KeyError: pass # Get first X messages. self._mail.select("inbox") # apply date filter. try: date = kwargs['date'] date_str = date.strftime("%d-%b-%Y") _, email_ids = self._mail.search(None, '(SINCE "%s")' % date_str) except KeyError: _, email_ids = self._mail.search(None, 'ALL') # Above call returns email IDs as an array containing 1 str email_ids = email_ids[0].split() matching_uids = [] for _ in range(1, min(limit, len(email_ids))): email_id = email_ids.pop() rfc_body = self._mail.fetch(email_id, "(RFC822)")[1][0][1] match = True for expr in args: if re.search(expr, rfc_body) is None: match = False break if match: uid = re.search( "UID\\D*(\\d+)\\D*", self._mail.fetch(email_id, 'UID')[1][0]).group(1) matching_uids.append(uid) return matching_uids
python
def raw_search(self, *args, **kwargs): """ Find the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search through. date (datetime) - If specified, it will filter avoid checking messages older than this date. """ limit = 50 try: limit = kwargs['limit'] except KeyError: pass # Get first X messages. self._mail.select("inbox") # apply date filter. try: date = kwargs['date'] date_str = date.strftime("%d-%b-%Y") _, email_ids = self._mail.search(None, '(SINCE "%s")' % date_str) except KeyError: _, email_ids = self._mail.search(None, 'ALL') # Above call returns email IDs as an array containing 1 str email_ids = email_ids[0].split() matching_uids = [] for _ in range(1, min(limit, len(email_ids))): email_id = email_ids.pop() rfc_body = self._mail.fetch(email_id, "(RFC822)")[1][0][1] match = True for expr in args: if re.search(expr, rfc_body) is None: match = False break if match: uid = re.search( "UID\\D*(\\d+)\\D*", self._mail.fetch(email_id, 'UID')[1][0]).group(1) matching_uids.append(uid) return matching_uids
[ "def", "raw_search", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "limit", "=", "50", "try", ":", "limit", "=", "kwargs", "[", "'limit'", "]", "except", "KeyError", ":", "pass", "# Get first X messages.", "self", ".", "_mail", ".", "select", "(", "\"inbox\"", ")", "# apply date filter.", "try", ":", "date", "=", "kwargs", "[", "'date'", "]", "date_str", "=", "date", ".", "strftime", "(", "\"%d-%b-%Y\"", ")", "_", ",", "email_ids", "=", "self", ".", "_mail", ".", "search", "(", "None", ",", "'(SINCE \"%s\")'", "%", "date_str", ")", "except", "KeyError", ":", "_", ",", "email_ids", "=", "self", ".", "_mail", ".", "search", "(", "None", ",", "'ALL'", ")", "# Above call returns email IDs as an array containing 1 str", "email_ids", "=", "email_ids", "[", "0", "]", ".", "split", "(", ")", "matching_uids", "=", "[", "]", "for", "_", "in", "range", "(", "1", ",", "min", "(", "limit", ",", "len", "(", "email_ids", ")", ")", ")", ":", "email_id", "=", "email_ids", ".", "pop", "(", ")", "rfc_body", "=", "self", ".", "_mail", ".", "fetch", "(", "email_id", ",", "\"(RFC822)\"", ")", "[", "1", "]", "[", "0", "]", "[", "1", "]", "match", "=", "True", "for", "expr", "in", "args", ":", "if", "re", ".", "search", "(", "expr", ",", "rfc_body", ")", "is", "None", ":", "match", "=", "False", "break", "if", "match", ":", "uid", "=", "re", ".", "search", "(", "\"UID\\\\D*(\\\\d+)\\\\D*\"", ",", "self", ".", "_mail", ".", "fetch", "(", "email_id", ",", "'UID'", ")", "[", "1", "]", "[", "0", "]", ")", ".", "group", "(", "1", ")", "matching_uids", ".", "append", "(", "uid", ")", "return", "matching_uids" ]
Find the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search through. date (datetime) - If specified, it will filter avoid checking messages older than this date.
[ "Find", "the", "a", "set", "of", "emails", "matching", "each", "regular", "expression", "passed", "in", "against", "the", "(", "RFC822", ")", "content", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L139-L188
wiredrive/wtframework
wtframework/wtf/email.py
IMapEmailAccountObject.__search_email_by_subject
def __search_email_by_subject(self, subject, match_recipient): "Get a list of message numbers" if match_recipient is None: _, data = self._mail.uid('search', None, '(HEADER SUBJECT "{subject}")' .format(subject=subject)) uid_list = data[0].split() return uid_list else: _, data = self._mail.uid('search', None, '(HEADER SUBJECT "{subject}" TO "{recipient}")' .format(subject=subject, recipient=match_recipient)) filtered_list = [] uid_list = data[0].split() for uid in uid_list: # Those hard coded indexes [1][0][1] is a hard reference to the message email message headers # that's burried in all those wrapper objects that's associated # with fetching a message. to_addr = re.search( "[^-]To: (.*)", self._mail.uid('fetch', uid, "(RFC822)")[1][0][1]).group(1).strip() if (to_addr == match_recipient or to_addr == "<{0}>".format(match_recipient)): # Add matching entry to the list. filtered_list.append(uid) return filtered_list
python
def __search_email_by_subject(self, subject, match_recipient): "Get a list of message numbers" if match_recipient is None: _, data = self._mail.uid('search', None, '(HEADER SUBJECT "{subject}")' .format(subject=subject)) uid_list = data[0].split() return uid_list else: _, data = self._mail.uid('search', None, '(HEADER SUBJECT "{subject}" TO "{recipient}")' .format(subject=subject, recipient=match_recipient)) filtered_list = [] uid_list = data[0].split() for uid in uid_list: # Those hard coded indexes [1][0][1] is a hard reference to the message email message headers # that's burried in all those wrapper objects that's associated # with fetching a message. to_addr = re.search( "[^-]To: (.*)", self._mail.uid('fetch', uid, "(RFC822)")[1][0][1]).group(1).strip() if (to_addr == match_recipient or to_addr == "<{0}>".format(match_recipient)): # Add matching entry to the list. filtered_list.append(uid) return filtered_list
[ "def", "__search_email_by_subject", "(", "self", ",", "subject", ",", "match_recipient", ")", ":", "if", "match_recipient", "is", "None", ":", "_", ",", "data", "=", "self", ".", "_mail", ".", "uid", "(", "'search'", ",", "None", ",", "'(HEADER SUBJECT \"{subject}\")'", ".", "format", "(", "subject", "=", "subject", ")", ")", "uid_list", "=", "data", "[", "0", "]", ".", "split", "(", ")", "return", "uid_list", "else", ":", "_", ",", "data", "=", "self", ".", "_mail", ".", "uid", "(", "'search'", ",", "None", ",", "'(HEADER SUBJECT \"{subject}\" TO \"{recipient}\")'", ".", "format", "(", "subject", "=", "subject", ",", "recipient", "=", "match_recipient", ")", ")", "filtered_list", "=", "[", "]", "uid_list", "=", "data", "[", "0", "]", ".", "split", "(", ")", "for", "uid", "in", "uid_list", ":", "# Those hard coded indexes [1][0][1] is a hard reference to the message email message headers", "# that's burried in all those wrapper objects that's associated", "# with fetching a message.", "to_addr", "=", "re", ".", "search", "(", "\"[^-]To: (.*)\"", ",", "self", ".", "_mail", ".", "uid", "(", "'fetch'", ",", "uid", ",", "\"(RFC822)\"", ")", "[", "1", "]", "[", "0", "]", "[", "1", "]", ")", ".", "group", "(", "1", ")", ".", "strip", "(", ")", "if", "(", "to_addr", "==", "match_recipient", "or", "to_addr", "==", "\"<{0}>\"", ".", "format", "(", "match_recipient", ")", ")", ":", "# Add matching entry to the list.", "filtered_list", ".", "append", "(", "uid", ")", "return", "filtered_list" ]
Get a list of message numbers
[ "Get", "a", "list", "of", "message", "numbers" ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L190-L219
wiredrive/wtframework
wtframework/wtf/config.py
ConfigReader.get
def get(self, key, default_value=__NoDefaultSpecified__): ''' Gets the value from the yaml config based on the key. No type casting is performed, any type casting should be performed by the caller. Args: key (str) - Config setting key. Kwargs: default_value - Default value to return if config is not specified. Returns: Returns value stored in config file. ''' # First attempt to get the var from OS enviornment. os_env_string = ConfigReader.ENV_PREFIX + key os_env_string = os_env_string.replace(".", "_") if type(os.getenv(os_env_string)) != NoneType: return os.getenv(os_env_string) # Otherwise search through config files. for data_map in self._dataMaps: try: if "." in key: # this is a multi levl string namespaces = key.split(".") temp_var = data_map for name in namespaces: temp_var = temp_var[name] return temp_var else: value = data_map[key] return value except (AttributeError, TypeError, KeyError): pass if default_value == self.__NoDefaultSpecified__: raise KeyError(u("Key '{0}' does not exist").format(key)) else: return default_value
python
def get(self, key, default_value=__NoDefaultSpecified__): ''' Gets the value from the yaml config based on the key. No type casting is performed, any type casting should be performed by the caller. Args: key (str) - Config setting key. Kwargs: default_value - Default value to return if config is not specified. Returns: Returns value stored in config file. ''' # First attempt to get the var from OS enviornment. os_env_string = ConfigReader.ENV_PREFIX + key os_env_string = os_env_string.replace(".", "_") if type(os.getenv(os_env_string)) != NoneType: return os.getenv(os_env_string) # Otherwise search through config files. for data_map in self._dataMaps: try: if "." in key: # this is a multi levl string namespaces = key.split(".") temp_var = data_map for name in namespaces: temp_var = temp_var[name] return temp_var else: value = data_map[key] return value except (AttributeError, TypeError, KeyError): pass if default_value == self.__NoDefaultSpecified__: raise KeyError(u("Key '{0}' does not exist").format(key)) else: return default_value
[ "def", "get", "(", "self", ",", "key", ",", "default_value", "=", "__NoDefaultSpecified__", ")", ":", "# First attempt to get the var from OS enviornment.", "os_env_string", "=", "ConfigReader", ".", "ENV_PREFIX", "+", "key", "os_env_string", "=", "os_env_string", ".", "replace", "(", "\".\"", ",", "\"_\"", ")", "if", "type", "(", "os", ".", "getenv", "(", "os_env_string", ")", ")", "!=", "NoneType", ":", "return", "os", ".", "getenv", "(", "os_env_string", ")", "# Otherwise search through config files.", "for", "data_map", "in", "self", ".", "_dataMaps", ":", "try", ":", "if", "\".\"", "in", "key", ":", "# this is a multi levl string", "namespaces", "=", "key", ".", "split", "(", "\".\"", ")", "temp_var", "=", "data_map", "for", "name", "in", "namespaces", ":", "temp_var", "=", "temp_var", "[", "name", "]", "return", "temp_var", "else", ":", "value", "=", "data_map", "[", "key", "]", "return", "value", "except", "(", "AttributeError", ",", "TypeError", ",", "KeyError", ")", ":", "pass", "if", "default_value", "==", "self", ".", "__NoDefaultSpecified__", ":", "raise", "KeyError", "(", "u", "(", "\"Key '{0}' does not exist\"", ")", ".", "format", "(", "key", ")", ")", "else", ":", "return", "default_value" ]
Gets the value from the yaml config based on the key. No type casting is performed, any type casting should be performed by the caller. Args: key (str) - Config setting key. Kwargs: default_value - Default value to return if config is not specified. Returns: Returns value stored in config file.
[ "Gets", "the", "value", "from", "the", "yaml", "config", "based", "on", "the", "key", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/config.py#L82-L124
wiredrive/wtframework
wtframework/wtf/_devtools_/page_object_tools.py
generate_page_object
def generate_page_object(page_name, url): "Generate page object from URL" # Attempt to extract partial URL for verification. url_with_path = u('^.*//[^/]+([^?]+)?|$') try: match = re.match(url_with_path, url) partial_url = match.group(1) print("Using partial URL for location verification. ", partial_url) except: # use full url since we couldn't extract a partial. partial_url = url print("Could not find usable partial url, using full url.", url) # Attempt to map input objects. print("Processing page source...") response = urllib2.urlopen(url) html = response.read() input_tags_expr = u('<\s*input[^>]*>') input_tag_iter = re.finditer(input_tags_expr, html, re.IGNORECASE) objectmap = "" print("Creating object map for <input> tags...") for input_tag_match in input_tag_iter: if not "hidden" in input_tag_match.group(0): try: print("processing", input_tag_match.group(0)) obj_map_entry = _process_input_tag(input_tag_match.group(0)) objectmap += u(" ") + obj_map_entry + "\n" except Exception as e: print(e) # we failed to process it, nothing more we can do. pass return _page_object_template_.contents.format(date=datetime.now(), url=url, pagename=page_name, partialurl=partial_url, objectmap=objectmap)
python
def generate_page_object(page_name, url): "Generate page object from URL" # Attempt to extract partial URL for verification. url_with_path = u('^.*//[^/]+([^?]+)?|$') try: match = re.match(url_with_path, url) partial_url = match.group(1) print("Using partial URL for location verification. ", partial_url) except: # use full url since we couldn't extract a partial. partial_url = url print("Could not find usable partial url, using full url.", url) # Attempt to map input objects. print("Processing page source...") response = urllib2.urlopen(url) html = response.read() input_tags_expr = u('<\s*input[^>]*>') input_tag_iter = re.finditer(input_tags_expr, html, re.IGNORECASE) objectmap = "" print("Creating object map for <input> tags...") for input_tag_match in input_tag_iter: if not "hidden" in input_tag_match.group(0): try: print("processing", input_tag_match.group(0)) obj_map_entry = _process_input_tag(input_tag_match.group(0)) objectmap += u(" ") + obj_map_entry + "\n" except Exception as e: print(e) # we failed to process it, nothing more we can do. pass return _page_object_template_.contents.format(date=datetime.now(), url=url, pagename=page_name, partialurl=partial_url, objectmap=objectmap)
[ "def", "generate_page_object", "(", "page_name", ",", "url", ")", ":", "# Attempt to extract partial URL for verification.", "url_with_path", "=", "u", "(", "'^.*//[^/]+([^?]+)?|$'", ")", "try", ":", "match", "=", "re", ".", "match", "(", "url_with_path", ",", "url", ")", "partial_url", "=", "match", ".", "group", "(", "1", ")", "print", "(", "\"Using partial URL for location verification. \"", ",", "partial_url", ")", "except", ":", "# use full url since we couldn't extract a partial.", "partial_url", "=", "url", "print", "(", "\"Could not find usable partial url, using full url.\"", ",", "url", ")", "# Attempt to map input objects.", "print", "(", "\"Processing page source...\"", ")", "response", "=", "urllib2", ".", "urlopen", "(", "url", ")", "html", "=", "response", ".", "read", "(", ")", "input_tags_expr", "=", "u", "(", "'<\\s*input[^>]*>'", ")", "input_tag_iter", "=", "re", ".", "finditer", "(", "input_tags_expr", ",", "html", ",", "re", ".", "IGNORECASE", ")", "objectmap", "=", "\"\"", "print", "(", "\"Creating object map for <input> tags...\"", ")", "for", "input_tag_match", "in", "input_tag_iter", ":", "if", "not", "\"hidden\"", "in", "input_tag_match", ".", "group", "(", "0", ")", ":", "try", ":", "print", "(", "\"processing\"", ",", "input_tag_match", ".", "group", "(", "0", ")", ")", "obj_map_entry", "=", "_process_input_tag", "(", "input_tag_match", ".", "group", "(", "0", ")", ")", "objectmap", "+=", "u", "(", "\" \"", ")", "+", "obj_map_entry", "+", "\"\\n\"", "except", "Exception", "as", "e", ":", "print", "(", "e", ")", "# we failed to process it, nothing more we can do.", "pass", "return", "_page_object_template_", ".", "contents", ".", "format", "(", "date", "=", "datetime", ".", "now", "(", ")", ",", "url", "=", "url", ",", "pagename", "=", "page_name", ",", "partialurl", "=", "partial_url", ",", "objectmap", "=", "objectmap", ")" ]
Generate page object from URL
[ "Generate", "page", "object", "from", "URL" ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/_devtools_/page_object_tools.py#L139-L177
wiredrive/wtframework
wtframework/wtf/data/data_management.py
DataManager.get_data_path
def get_data_path(self, filename, env_prefix=None): """ Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAGER.get_data_path('testdata.csv') Note: WTF_DATA_MANAGER is a provided global instance of DataManager """ if env_prefix == None: target_file = filename else: target_file = os.path.join(env_prefix, filename) if os.path.exists(os.path.join(self._data_path, target_file)): return os.path.join(self._data_path, target_file) else: raise DataNotFoundError( u("Cannot find data file: {0}").format(target_file))
python
def get_data_path(self, filename, env_prefix=None): """ Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAGER.get_data_path('testdata.csv') Note: WTF_DATA_MANAGER is a provided global instance of DataManager """ if env_prefix == None: target_file = filename else: target_file = os.path.join(env_prefix, filename) if os.path.exists(os.path.join(self._data_path, target_file)): return os.path.join(self._data_path, target_file) else: raise DataNotFoundError( u("Cannot find data file: {0}").format(target_file))
[ "def", "get_data_path", "(", "self", ",", "filename", ",", "env_prefix", "=", "None", ")", ":", "if", "env_prefix", "==", "None", ":", "target_file", "=", "filename", "else", ":", "target_file", "=", "os", ".", "path", ".", "join", "(", "env_prefix", ",", "filename", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_data_path", ",", "target_file", ")", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "_data_path", ",", "target_file", ")", "else", ":", "raise", "DataNotFoundError", "(", "u", "(", "\"Cannot find data file: {0}\"", ")", ".", "format", "(", "target_file", ")", ")" ]
Get data path. Args: filename (string) : Name of file inside of /data folder to retrieve. Kwargs: env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa Returns: String - path to file. Usage:: open(WTF_DATA_MANAGER.get_data_path('testdata.csv') Note: WTF_DATA_MANAGER is a provided global instance of DataManager
[ "Get", "data", "path", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/data/data_management.py#L65-L94
wiredrive/wtframework
wtframework/wtf/data/data_management.py
CsvReader.next
def next(self): """ Gets next entry as a dictionary. Returns: object - Object key/value pair representing a row. {key1: value1, key2: value2, ...} """ try: entry = {} row = self._csv_reader.next() for i in range(0, len(row)): entry[self._headers[i]] = row[i] return entry except Exception as e: # close our file when we're done reading. self._file.close() raise e
python
def next(self): """ Gets next entry as a dictionary. Returns: object - Object key/value pair representing a row. {key1: value1, key2: value2, ...} """ try: entry = {} row = self._csv_reader.next() for i in range(0, len(row)): entry[self._headers[i]] = row[i] return entry except Exception as e: # close our file when we're done reading. self._file.close() raise e
[ "def", "next", "(", "self", ")", ":", "try", ":", "entry", "=", "{", "}", "row", "=", "self", ".", "_csv_reader", ".", "next", "(", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "row", ")", ")", ":", "entry", "[", "self", ".", "_headers", "[", "i", "]", "]", "=", "row", "[", "i", "]", "return", "entry", "except", "Exception", "as", "e", ":", "# close our file when we're done reading.", "self", ".", "_file", ".", "close", "(", ")", "raise", "e" ]
Gets next entry as a dictionary. Returns: object - Object key/value pair representing a row. {key1: value1, key2: value2, ...}
[ "Gets", "next", "entry", "as", "a", "dictionary", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/data/data_management.py#L133-L152
wiredrive/wtframework
wtframework/wtf/web/webelement.py
WebElementSelector.find_element_by_selectors
def find_element_by_selectors(webdriver, *selectors): """ Utility method makes it easier to find an element using multiple selectors. This is useful for problematic elements what might works with one browser, but fail in another. (Like different page elements being served up for different browsers) Args: selectors - var arg if N number of selectors to match against. Each selector should be a Selenium 'By' object. Usage:: my_element = WebElementSelector.find_element_by_selectors(webdriver, (By.ID, "MyElementID"), (By.CSS, "MyClassSelector") ) """ # perform initial check to verify selectors are valid by statements. for selector in selectors: (by_method, value) = selector if not WebElementSelector.__is_valid_by_type(by_method): raise BadSelectorError( u("Selectors should be of type selenium.webdriver.common.by.By")) if type(value) != str: raise BadSelectorError( u("Selectors should be of type selenium.webdriver.common.by.By")) selectors_used = [] for selector in selectors: (by_method, value) = selector selectors_used.append( u("{by}:{value}").format(by=by_method, value=value)) try: return webdriver.find_element(by=by_method, value=value) except: pass raise ElementNotSelectableException( u("Unable to find elements using:") + u(",").join(selectors_used))
python
def find_element_by_selectors(webdriver, *selectors): """ Utility method makes it easier to find an element using multiple selectors. This is useful for problematic elements what might works with one browser, but fail in another. (Like different page elements being served up for different browsers) Args: selectors - var arg if N number of selectors to match against. Each selector should be a Selenium 'By' object. Usage:: my_element = WebElementSelector.find_element_by_selectors(webdriver, (By.ID, "MyElementID"), (By.CSS, "MyClassSelector") ) """ # perform initial check to verify selectors are valid by statements. for selector in selectors: (by_method, value) = selector if not WebElementSelector.__is_valid_by_type(by_method): raise BadSelectorError( u("Selectors should be of type selenium.webdriver.common.by.By")) if type(value) != str: raise BadSelectorError( u("Selectors should be of type selenium.webdriver.common.by.By")) selectors_used = [] for selector in selectors: (by_method, value) = selector selectors_used.append( u("{by}:{value}").format(by=by_method, value=value)) try: return webdriver.find_element(by=by_method, value=value) except: pass raise ElementNotSelectableException( u("Unable to find elements using:") + u(",").join(selectors_used))
[ "def", "find_element_by_selectors", "(", "webdriver", ",", "*", "selectors", ")", ":", "# perform initial check to verify selectors are valid by statements.", "for", "selector", "in", "selectors", ":", "(", "by_method", ",", "value", ")", "=", "selector", "if", "not", "WebElementSelector", ".", "__is_valid_by_type", "(", "by_method", ")", ":", "raise", "BadSelectorError", "(", "u", "(", "\"Selectors should be of type selenium.webdriver.common.by.By\"", ")", ")", "if", "type", "(", "value", ")", "!=", "str", ":", "raise", "BadSelectorError", "(", "u", "(", "\"Selectors should be of type selenium.webdriver.common.by.By\"", ")", ")", "selectors_used", "=", "[", "]", "for", "selector", "in", "selectors", ":", "(", "by_method", ",", "value", ")", "=", "selector", "selectors_used", ".", "append", "(", "u", "(", "\"{by}:{value}\"", ")", ".", "format", "(", "by", "=", "by_method", ",", "value", "=", "value", ")", ")", "try", ":", "return", "webdriver", ".", "find_element", "(", "by", "=", "by_method", ",", "value", "=", "value", ")", "except", ":", "pass", "raise", "ElementNotSelectableException", "(", "u", "(", "\"Unable to find elements using:\"", ")", "+", "u", "(", "\",\"", ")", ".", "join", "(", "selectors_used", ")", ")" ]
Utility method makes it easier to find an element using multiple selectors. This is useful for problematic elements what might works with one browser, but fail in another. (Like different page elements being served up for different browsers) Args: selectors - var arg if N number of selectors to match against. Each selector should be a Selenium 'By' object. Usage:: my_element = WebElementSelector.find_element_by_selectors(webdriver, (By.ID, "MyElementID"), (By.CSS, "MyClassSelector") )
[ "Utility", "method", "makes", "it", "easier", "to", "find", "an", "element", "using", "multiple", "selectors", ".", "This", "is", "useful", "for", "problematic", "elements", "what", "might", "works", "with", "one", "browser", "but", "fail", "in", "another", ".", "(", "Like", "different", "page", "elements", "being", "served", "up", "for", "different", "browsers", ")" ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webelement.py#L33-L70
wiredrive/wtframework
wtframework/wtf/web/webelement.py
WebElementUtils.wait_until_element_not_visible
def wait_until_element_not_visible(webdriver, locator_lambda_expression, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): """ Wait for a WebElement to disappear. Args: webdriver (Webdriver) - Selenium Webdriver locator (lambda) - Locator lambda expression. Kwargs: timeout (number) - timeout period sleep (number) - sleep period between intervals. """ # Wait for loading progress indicator to go away. try: stoptime = datetime.now() + timedelta(seconds=timeout) while datetime.now() < stoptime: element = WebDriverWait(webdriver, WTF_TIMEOUT_MANAGER.BRIEF).until( locator_lambda_expression) if element.is_displayed(): time.sleep(sleep) else: break except TimeoutException: pass
python
def wait_until_element_not_visible(webdriver, locator_lambda_expression, timeout=WTF_TIMEOUT_MANAGER.NORMAL, sleep=0.5): """ Wait for a WebElement to disappear. Args: webdriver (Webdriver) - Selenium Webdriver locator (lambda) - Locator lambda expression. Kwargs: timeout (number) - timeout period sleep (number) - sleep period between intervals. """ # Wait for loading progress indicator to go away. try: stoptime = datetime.now() + timedelta(seconds=timeout) while datetime.now() < stoptime: element = WebDriverWait(webdriver, WTF_TIMEOUT_MANAGER.BRIEF).until( locator_lambda_expression) if element.is_displayed(): time.sleep(sleep) else: break except TimeoutException: pass
[ "def", "wait_until_element_not_visible", "(", "webdriver", ",", "locator_lambda_expression", ",", "timeout", "=", "WTF_TIMEOUT_MANAGER", ".", "NORMAL", ",", "sleep", "=", "0.5", ")", ":", "# Wait for loading progress indicator to go away.", "try", ":", "stoptime", "=", "datetime", ".", "now", "(", ")", "+", "timedelta", "(", "seconds", "=", "timeout", ")", "while", "datetime", ".", "now", "(", ")", "<", "stoptime", ":", "element", "=", "WebDriverWait", "(", "webdriver", ",", "WTF_TIMEOUT_MANAGER", ".", "BRIEF", ")", ".", "until", "(", "locator_lambda_expression", ")", "if", "element", ".", "is_displayed", "(", ")", ":", "time", ".", "sleep", "(", "sleep", ")", "else", ":", "break", "except", "TimeoutException", ":", "pass" ]
Wait for a WebElement to disappear. Args: webdriver (Webdriver) - Selenium Webdriver locator (lambda) - Locator lambda expression. Kwargs: timeout (number) - timeout period sleep (number) - sleep period between intervals.
[ "Wait", "for", "a", "WebElement", "to", "disappear", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webelement.py#L89-L114
wiredrive/wtframework
wtframework/wtf/web/webelement.py
WebElementUtils.is_image_loaded
def is_image_loaded(webdriver, webelement): ''' Check if an image (in an image tag) is loaded. Note: This call will not work against background images. Only Images in <img> tags. Args: webelement (WebElement) - WebDriver web element to validate. ''' script = (u("return arguments[0].complete && type of arguments[0].naturalWidth != \"undefined\" ") + u("&& arguments[0].naturalWidth > 0")) try: return webdriver.execute_script(script, webelement) except: return False
python
def is_image_loaded(webdriver, webelement): ''' Check if an image (in an image tag) is loaded. Note: This call will not work against background images. Only Images in <img> tags. Args: webelement (WebElement) - WebDriver web element to validate. ''' script = (u("return arguments[0].complete && type of arguments[0].naturalWidth != \"undefined\" ") + u("&& arguments[0].naturalWidth > 0")) try: return webdriver.execute_script(script, webelement) except: return False
[ "def", "is_image_loaded", "(", "webdriver", ",", "webelement", ")", ":", "script", "=", "(", "u", "(", "\"return arguments[0].complete && type of arguments[0].naturalWidth != \\\"undefined\\\" \"", ")", "+", "u", "(", "\"&& arguments[0].naturalWidth > 0\"", ")", ")", "try", ":", "return", "webdriver", ".", "execute_script", "(", "script", ",", "webelement", ")", "except", ":", "return", "False" ]
Check if an image (in an image tag) is loaded. Note: This call will not work against background images. Only Images in <img> tags. Args: webelement (WebElement) - WebDriver web element to validate.
[ "Check", "if", "an", "image", "(", "in", "an", "image", "tag", ")", "is", "loaded", ".", "Note", ":", "This", "call", "will", "not", "work", "against", "background", "images", ".", "Only", "Images", "in", "<img", ">", "tags", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webelement.py#L117-L131
wiredrive/wtframework
wtframework/wtf/utils/data_utils.py
generate_timestamped_string
def generate_timestamped_string(subject="test", number_of_random_chars=4): """ Generate time-stamped string. Format as follows... `2013-01-31_14:12:23_SubjectString_a3Zg` Kwargs: subject (str): String to use as subject. number_of_random_chars (int) : Number of random characters to append. This method is helpful for creating unique names with timestamps in them so when you have to troubleshoot an issue, the name is easier to find.:: self.project_name = generate_timestamped_string("project") new_project_page.create_project(project_name) """ random_str = generate_random_string(number_of_random_chars) timestamp = generate_timestamp() return u"{timestamp}_{subject}_{random_str}".format(timestamp=timestamp, subject=subject, random_str=random_str)
python
def generate_timestamped_string(subject="test", number_of_random_chars=4): """ Generate time-stamped string. Format as follows... `2013-01-31_14:12:23_SubjectString_a3Zg` Kwargs: subject (str): String to use as subject. number_of_random_chars (int) : Number of random characters to append. This method is helpful for creating unique names with timestamps in them so when you have to troubleshoot an issue, the name is easier to find.:: self.project_name = generate_timestamped_string("project") new_project_page.create_project(project_name) """ random_str = generate_random_string(number_of_random_chars) timestamp = generate_timestamp() return u"{timestamp}_{subject}_{random_str}".format(timestamp=timestamp, subject=subject, random_str=random_str)
[ "def", "generate_timestamped_string", "(", "subject", "=", "\"test\"", ",", "number_of_random_chars", "=", "4", ")", ":", "random_str", "=", "generate_random_string", "(", "number_of_random_chars", ")", "timestamp", "=", "generate_timestamp", "(", ")", "return", "u\"{timestamp}_{subject}_{random_str}\"", ".", "format", "(", "timestamp", "=", "timestamp", ",", "subject", "=", "subject", ",", "random_str", "=", "random_str", ")" ]
Generate time-stamped string. Format as follows... `2013-01-31_14:12:23_SubjectString_a3Zg` Kwargs: subject (str): String to use as subject. number_of_random_chars (int) : Number of random characters to append. This method is helpful for creating unique names with timestamps in them so when you have to troubleshoot an issue, the name is easier to find.:: self.project_name = generate_timestamped_string("project") new_project_page.create_project(project_name)
[ "Generate", "time", "-", "stamped", "string", ".", "Format", "as", "follows", "..." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/data_utils.py#L28-L51
wiredrive/wtframework
wtframework/wtf/utils/data_utils.py
generate_random_string
def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters): """ Generate a series of random characters. Kwargs: number_of_random_chars (int) : Number of characters long character_set (str): Specify a character set. Default is ASCII """ return u('').join(random.choice(character_set) for _ in range(number_of_random_chars))
python
def generate_random_string(number_of_random_chars=8, character_set=string.ascii_letters): """ Generate a series of random characters. Kwargs: number_of_random_chars (int) : Number of characters long character_set (str): Specify a character set. Default is ASCII """ return u('').join(random.choice(character_set) for _ in range(number_of_random_chars))
[ "def", "generate_random_string", "(", "number_of_random_chars", "=", "8", ",", "character_set", "=", "string", ".", "ascii_letters", ")", ":", "return", "u", "(", "''", ")", ".", "join", "(", "random", ".", "choice", "(", "character_set", ")", "for", "_", "in", "range", "(", "number_of_random_chars", ")", ")" ]
Generate a series of random characters. Kwargs: number_of_random_chars (int) : Number of characters long character_set (str): Specify a character set. Default is ASCII
[ "Generate", "a", "series", "of", "random", "characters", "." ]
train
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/data_utils.py#L65-L74
chrisspen/weka
weka/arff.py
convert_weka_to_py_date_pattern
def convert_weka_to_py_date_pattern(p): """ Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime(). """ # https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior # https://www.cs.waikato.ac.nz/ml/weka/arff.html p = p.replace('yyyy', r'%Y') p = p.replace('MM', r'%m') p = p.replace('dd', r'%d') p = p.replace('HH', r'%H') p = p.replace('mm', r'%M') p = p.replace('ss', r'%S') return p
python
def convert_weka_to_py_date_pattern(p): """ Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime(). """ # https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior # https://www.cs.waikato.ac.nz/ml/weka/arff.html p = p.replace('yyyy', r'%Y') p = p.replace('MM', r'%m') p = p.replace('dd', r'%d') p = p.replace('HH', r'%H') p = p.replace('mm', r'%M') p = p.replace('ss', r'%S') return p
[ "def", "convert_weka_to_py_date_pattern", "(", "p", ")", ":", "# https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior", "# https://www.cs.waikato.ac.nz/ml/weka/arff.html", "p", "=", "p", ".", "replace", "(", "'yyyy'", ",", "r'%Y'", ")", "p", "=", "p", ".", "replace", "(", "'MM'", ",", "r'%m'", ")", "p", "=", "p", ".", "replace", "(", "'dd'", ",", "r'%d'", ")", "p", "=", "p", ".", "replace", "(", "'HH'", ",", "r'%H'", ")", "p", "=", "p", ".", "replace", "(", "'mm'", ",", "r'%M'", ")", "p", "=", "p", ".", "replace", "(", "'ss'", ",", "r'%S'", ")", "return", "p" ]
Converts the date format pattern used by Weka to the date format pattern used by Python's datetime.strftime().
[ "Converts", "the", "date", "format", "pattern", "used", "by", "Weka", "to", "the", "date", "format", "pattern", "used", "by", "Python", "s", "datetime", ".", "strftime", "()", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L87-L99
chrisspen/weka
weka/arff.py
ArffFile.get_attribute_value
def get_attribute_value(self, name, index): """ Returns the value associated with the given value index of the attribute with the given name. This is only applicable for nominal and string types. """ if index == MISSING: return elif self.attribute_types[name] in NUMERIC_TYPES: at = self.attribute_types[name] if at == TYPE_INTEGER: return int(index) return Decimal(str(index)) else: assert self.attribute_types[name] == TYPE_NOMINAL cls_index, cls_value = index.split(':') #return self.attribute_data[name][index-1] if cls_value != MISSING: assert cls_value in self.attribute_data[name], \ 'Predicted value "%s" but only values %s are allowed.' \ % (cls_value, ', '.join(self.attribute_data[name])) return cls_value
python
def get_attribute_value(self, name, index): """ Returns the value associated with the given value index of the attribute with the given name. This is only applicable for nominal and string types. """ if index == MISSING: return elif self.attribute_types[name] in NUMERIC_TYPES: at = self.attribute_types[name] if at == TYPE_INTEGER: return int(index) return Decimal(str(index)) else: assert self.attribute_types[name] == TYPE_NOMINAL cls_index, cls_value = index.split(':') #return self.attribute_data[name][index-1] if cls_value != MISSING: assert cls_value in self.attribute_data[name], \ 'Predicted value "%s" but only values %s are allowed.' \ % (cls_value, ', '.join(self.attribute_data[name])) return cls_value
[ "def", "get_attribute_value", "(", "self", ",", "name", ",", "index", ")", ":", "if", "index", "==", "MISSING", ":", "return", "elif", "self", ".", "attribute_types", "[", "name", "]", "in", "NUMERIC_TYPES", ":", "at", "=", "self", ".", "attribute_types", "[", "name", "]", "if", "at", "==", "TYPE_INTEGER", ":", "return", "int", "(", "index", ")", "return", "Decimal", "(", "str", "(", "index", ")", ")", "else", ":", "assert", "self", ".", "attribute_types", "[", "name", "]", "==", "TYPE_NOMINAL", "cls_index", ",", "cls_value", "=", "index", ".", "split", "(", "':'", ")", "#return self.attribute_data[name][index-1]", "if", "cls_value", "!=", "MISSING", ":", "assert", "cls_value", "in", "self", ".", "attribute_data", "[", "name", "]", ",", "'Predicted value \"%s\" but only values %s are allowed.'", "%", "(", "cls_value", ",", "', '", ".", "join", "(", "self", ".", "attribute_data", "[", "name", "]", ")", ")", "return", "cls_value" ]
Returns the value associated with the given value index of the attribute with the given name. This is only applicable for nominal and string types.
[ "Returns", "the", "value", "associated", "with", "the", "given", "value", "index", "of", "the", "attribute", "with", "the", "given", "name", ".", "This", "is", "only", "applicable", "for", "nominal", "and", "string", "types", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L320-L342
chrisspen/weka
weka/arff.py
ArffFile.load
def load(cls, filename, schema_only=False): """ Load an ARFF File from a file. """ o = open(filename) s = o.read() a = cls.parse(s, schema_only=schema_only) if not schema_only: a._filename = filename o.close() return a
python
def load(cls, filename, schema_only=False): """ Load an ARFF File from a file. """ o = open(filename) s = o.read() a = cls.parse(s, schema_only=schema_only) if not schema_only: a._filename = filename o.close() return a
[ "def", "load", "(", "cls", ",", "filename", ",", "schema_only", "=", "False", ")", ":", "o", "=", "open", "(", "filename", ")", "s", "=", "o", ".", "read", "(", ")", "a", "=", "cls", ".", "parse", "(", "s", ",", "schema_only", "=", "schema_only", ")", "if", "not", "schema_only", ":", "a", ".", "_filename", "=", "filename", "o", ".", "close", "(", ")", "return", "a" ]
Load an ARFF File from a file.
[ "Load", "an", "ARFF", "File", "from", "a", "file", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L357-L367
chrisspen/weka
weka/arff.py
ArffFile.parse
def parse(cls, s, schema_only=False): """ Parse an ARFF File already loaded into a string. """ a = cls() a.state = 'comment' a.lineno = 1 for l in s.splitlines(): a.parseline(l) a.lineno += 1 if schema_only and a.state == 'data': # Don't parse data if we're only loading the schema. break return a
python
def parse(cls, s, schema_only=False): """ Parse an ARFF File already loaded into a string. """ a = cls() a.state = 'comment' a.lineno = 1 for l in s.splitlines(): a.parseline(l) a.lineno += 1 if schema_only and a.state == 'data': # Don't parse data if we're only loading the schema. break return a
[ "def", "parse", "(", "cls", ",", "s", ",", "schema_only", "=", "False", ")", ":", "a", "=", "cls", "(", ")", "a", ".", "state", "=", "'comment'", "a", ".", "lineno", "=", "1", "for", "l", "in", "s", ".", "splitlines", "(", ")", ":", "a", ".", "parseline", "(", "l", ")", "a", ".", "lineno", "+=", "1", "if", "schema_only", "and", "a", ".", "state", "==", "'data'", ":", "# Don't parse data if we're only loading the schema.", "break", "return", "a" ]
Parse an ARFF File already loaded into a string.
[ "Parse", "an", "ARFF", "File", "already", "loaded", "into", "a", "string", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L370-L383
chrisspen/weka
weka/arff.py
ArffFile.copy
def copy(self, schema_only=False): """ Creates a deepcopy of the instance. If schema_only is True, the data will be excluded from the copy. """ o = type(self)() o.relation = self.relation o.attributes = list(self.attributes) o.attribute_types = self.attribute_types.copy() o.attribute_data = self.attribute_data.copy() if not schema_only: o.comment = list(self.comment) o.data = copy.deepcopy(self.data) return o
python
def copy(self, schema_only=False): """ Creates a deepcopy of the instance. If schema_only is True, the data will be excluded from the copy. """ o = type(self)() o.relation = self.relation o.attributes = list(self.attributes) o.attribute_types = self.attribute_types.copy() o.attribute_data = self.attribute_data.copy() if not schema_only: o.comment = list(self.comment) o.data = copy.deepcopy(self.data) return o
[ "def", "copy", "(", "self", ",", "schema_only", "=", "False", ")", ":", "o", "=", "type", "(", "self", ")", "(", ")", "o", ".", "relation", "=", "self", ".", "relation", "o", ".", "attributes", "=", "list", "(", "self", ".", "attributes", ")", "o", ".", "attribute_types", "=", "self", ".", "attribute_types", ".", "copy", "(", ")", "o", ".", "attribute_data", "=", "self", ".", "attribute_data", ".", "copy", "(", ")", "if", "not", "schema_only", ":", "o", ".", "comment", "=", "list", "(", "self", ".", "comment", ")", "o", ".", "data", "=", "copy", ".", "deepcopy", "(", "self", ".", "data", ")", "return", "o" ]
Creates a deepcopy of the instance. If schema_only is True, the data will be excluded from the copy.
[ "Creates", "a", "deepcopy", "of", "the", "instance", ".", "If", "schema_only", "is", "True", "the", "data", "will", "be", "excluded", "from", "the", "copy", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L385-L398
chrisspen/weka
weka/arff.py
ArffFile.open_stream
def open_stream(self, class_attr_name=None, fn=None): """ Save an arff structure to a file, leaving the file object open for writing of new data samples. This prevents you from directly accessing the data via Python, but when generating a huge file, this prevents all your data from being stored in memory. """ if fn: self.fout_fn = fn else: fd, self.fout_fn = tempfile.mkstemp() os.close(fd) self.fout = open(self.fout_fn, 'w') if class_attr_name: self.class_attr_name = class_attr_name self.write(fout=self.fout, schema_only=True) self.write(fout=self.fout, data_only=True) self.fout.flush()
python
def open_stream(self, class_attr_name=None, fn=None): """ Save an arff structure to a file, leaving the file object open for writing of new data samples. This prevents you from directly accessing the data via Python, but when generating a huge file, this prevents all your data from being stored in memory. """ if fn: self.fout_fn = fn else: fd, self.fout_fn = tempfile.mkstemp() os.close(fd) self.fout = open(self.fout_fn, 'w') if class_attr_name: self.class_attr_name = class_attr_name self.write(fout=self.fout, schema_only=True) self.write(fout=self.fout, data_only=True) self.fout.flush()
[ "def", "open_stream", "(", "self", ",", "class_attr_name", "=", "None", ",", "fn", "=", "None", ")", ":", "if", "fn", ":", "self", ".", "fout_fn", "=", "fn", "else", ":", "fd", ",", "self", ".", "fout_fn", "=", "tempfile", ".", "mkstemp", "(", ")", "os", ".", "close", "(", "fd", ")", "self", ".", "fout", "=", "open", "(", "self", ".", "fout_fn", ",", "'w'", ")", "if", "class_attr_name", ":", "self", ".", "class_attr_name", "=", "class_attr_name", "self", ".", "write", "(", "fout", "=", "self", ".", "fout", ",", "schema_only", "=", "True", ")", "self", ".", "write", "(", "fout", "=", "self", ".", "fout", ",", "data_only", "=", "True", ")", "self", ".", "fout", ".", "flush", "(", ")" ]
Save an arff structure to a file, leaving the file object open for writing of new data samples. This prevents you from directly accessing the data via Python, but when generating a huge file, this prevents all your data from being stored in memory.
[ "Save", "an", "arff", "structure", "to", "a", "file", "leaving", "the", "file", "object", "open", "for", "writing", "of", "new", "data", "samples", ".", "This", "prevents", "you", "from", "directly", "accessing", "the", "data", "via", "Python", "but", "when", "generating", "a", "huge", "file", "this", "prevents", "all", "your", "data", "from", "being", "stored", "in", "memory", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L404-L422
chrisspen/weka
weka/arff.py
ArffFile.close_stream
def close_stream(self): """ Terminates an open stream and returns the filename of the file containing the streamed data. """ if self.fout: fout = self.fout fout_fn = self.fout_fn self.fout.flush() self.fout.close() self.fout = None self.fout_fn = None return fout_fn
python
def close_stream(self): """ Terminates an open stream and returns the filename of the file containing the streamed data. """ if self.fout: fout = self.fout fout_fn = self.fout_fn self.fout.flush() self.fout.close() self.fout = None self.fout_fn = None return fout_fn
[ "def", "close_stream", "(", "self", ")", ":", "if", "self", ".", "fout", ":", "fout", "=", "self", ".", "fout", "fout_fn", "=", "self", ".", "fout_fn", "self", ".", "fout", ".", "flush", "(", ")", "self", ".", "fout", ".", "close", "(", ")", "self", ".", "fout", "=", "None", "self", ".", "fout_fn", "=", "None", "return", "fout_fn" ]
Terminates an open stream and returns the filename of the file containing the streamed data.
[ "Terminates", "an", "open", "stream", "and", "returns", "the", "filename", "of", "the", "file", "containing", "the", "streamed", "data", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L424-L436
chrisspen/weka
weka/arff.py
ArffFile.save
def save(self, filename=None): """ Save an arff structure to a file. """ filename = filename or self._filename o = open(filename, 'w') o.write(self.write()) o.close()
python
def save(self, filename=None): """ Save an arff structure to a file. """ filename = filename or self._filename o = open(filename, 'w') o.write(self.write()) o.close()
[ "def", "save", "(", "self", ",", "filename", "=", "None", ")", ":", "filename", "=", "filename", "or", "self", ".", "_filename", "o", "=", "open", "(", "filename", ",", "'w'", ")", "o", ".", "write", "(", "self", ".", "write", "(", ")", ")", "o", ".", "close", "(", ")" ]
Save an arff structure to a file.
[ "Save", "an", "arff", "structure", "to", "a", "file", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L438-L445
chrisspen/weka
weka/arff.py
ArffFile.write_line
def write_line(self, d, fmt=SPARSE): """ Converts a single data line to a string. """ def smart_quote(s): if isinstance(s, basestring) and ' ' in s and s[0] != '"': s = '"%s"' % s return s if fmt == DENSE: #TODO:fix assert not isinstance(d, dict), NotImplemented line = [] for e, a in zip(d, self.attributes): at = self.attribute_types[a] if at in NUMERIC_TYPES: line.append(str(e)) elif at == TYPE_STRING: line.append(self.esc(e)) elif at == TYPE_NOMINAL: line.append(e) else: raise Exception("Type " + at + " not supported for writing!") s = ','.join(map(str, line)) return s elif fmt == SPARSE: line = [] # Convert flat row into dictionary. if isinstance(d, (list, tuple)): d = dict(zip(self.attributes, d)) for k in d: at = self.attribute_types.get(k) if isinstance(d[k], Value): continue elif d[k] == MISSING: d[k] = Str(d[k]) elif at in (TYPE_NUMERIC, TYPE_REAL): d[k] = Num(d[k]) elif at == TYPE_STRING: d[k] = Str(d[k]) elif at == TYPE_INTEGER: d[k] = Int(d[k]) elif at == TYPE_NOMINAL: d[k] = Nom(d[k]) elif at == TYPE_DATE: d[k] = Date(d[k]) else: raise Exception('Unknown type: %s' % at) for i, name in enumerate(self.attributes): v = d.get(name) if v is None: # print 'Skipping attribute with None value:', name continue elif v == MISSING or (isinstance(v, Value) and v.value == MISSING): v = MISSING elif isinstance(v, String): v = '"%s"' % v.value elif isinstance(v, Date): date_format = self.attribute_data.get(name, DEFAULT_DATE_FORMAT) date_format = convert_weka_to_py_date_pattern(date_format) if isinstance(v.value, basestring): _value = dateutil.parser.parse(v.value) else: assert isinstance(v.value, (date, datetime)) _value = v.value v.value = v = _value.strftime(date_format) elif isinstance(v, Value): v = v.value if v != MISSING and self.attribute_types[name] == TYPE_NOMINAL and str(v) not in map(str, self.attribute_data[name]): pass else: line.append('%i %s' % (i, smart_quote(v))) if len(line) == 1 and MISSING in line[-1]: # Skip lines with nothing other than a missing class. return elif not line: # Don't write blank lines. return return '{' + (', '.join(line)) + '}' else: raise Exception('Uknown format: %s' % (fmt,))
python
def write_line(self, d, fmt=SPARSE): """ Converts a single data line to a string. """ def smart_quote(s): if isinstance(s, basestring) and ' ' in s and s[0] != '"': s = '"%s"' % s return s if fmt == DENSE: #TODO:fix assert not isinstance(d, dict), NotImplemented line = [] for e, a in zip(d, self.attributes): at = self.attribute_types[a] if at in NUMERIC_TYPES: line.append(str(e)) elif at == TYPE_STRING: line.append(self.esc(e)) elif at == TYPE_NOMINAL: line.append(e) else: raise Exception("Type " + at + " not supported for writing!") s = ','.join(map(str, line)) return s elif fmt == SPARSE: line = [] # Convert flat row into dictionary. if isinstance(d, (list, tuple)): d = dict(zip(self.attributes, d)) for k in d: at = self.attribute_types.get(k) if isinstance(d[k], Value): continue elif d[k] == MISSING: d[k] = Str(d[k]) elif at in (TYPE_NUMERIC, TYPE_REAL): d[k] = Num(d[k]) elif at == TYPE_STRING: d[k] = Str(d[k]) elif at == TYPE_INTEGER: d[k] = Int(d[k]) elif at == TYPE_NOMINAL: d[k] = Nom(d[k]) elif at == TYPE_DATE: d[k] = Date(d[k]) else: raise Exception('Unknown type: %s' % at) for i, name in enumerate(self.attributes): v = d.get(name) if v is None: # print 'Skipping attribute with None value:', name continue elif v == MISSING or (isinstance(v, Value) and v.value == MISSING): v = MISSING elif isinstance(v, String): v = '"%s"' % v.value elif isinstance(v, Date): date_format = self.attribute_data.get(name, DEFAULT_DATE_FORMAT) date_format = convert_weka_to_py_date_pattern(date_format) if isinstance(v.value, basestring): _value = dateutil.parser.parse(v.value) else: assert isinstance(v.value, (date, datetime)) _value = v.value v.value = v = _value.strftime(date_format) elif isinstance(v, Value): v = v.value if v != MISSING and self.attribute_types[name] == TYPE_NOMINAL and str(v) not in map(str, self.attribute_data[name]): pass else: line.append('%i %s' % (i, smart_quote(v))) if len(line) == 1 and MISSING in line[-1]: # Skip lines with nothing other than a missing class. return elif not line: # Don't write blank lines. return return '{' + (', '.join(line)) + '}' else: raise Exception('Uknown format: %s' % (fmt,))
[ "def", "write_line", "(", "self", ",", "d", ",", "fmt", "=", "SPARSE", ")", ":", "def", "smart_quote", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "basestring", ")", "and", "' '", "in", "s", "and", "s", "[", "0", "]", "!=", "'\"'", ":", "s", "=", "'\"%s\"'", "%", "s", "return", "s", "if", "fmt", "==", "DENSE", ":", "#TODO:fix", "assert", "not", "isinstance", "(", "d", ",", "dict", ")", ",", "NotImplemented", "line", "=", "[", "]", "for", "e", ",", "a", "in", "zip", "(", "d", ",", "self", ".", "attributes", ")", ":", "at", "=", "self", ".", "attribute_types", "[", "a", "]", "if", "at", "in", "NUMERIC_TYPES", ":", "line", ".", "append", "(", "str", "(", "e", ")", ")", "elif", "at", "==", "TYPE_STRING", ":", "line", ".", "append", "(", "self", ".", "esc", "(", "e", ")", ")", "elif", "at", "==", "TYPE_NOMINAL", ":", "line", ".", "append", "(", "e", ")", "else", ":", "raise", "Exception", "(", "\"Type \"", "+", "at", "+", "\" not supported for writing!\"", ")", "s", "=", "','", ".", "join", "(", "map", "(", "str", ",", "line", ")", ")", "return", "s", "elif", "fmt", "==", "SPARSE", ":", "line", "=", "[", "]", "# Convert flat row into dictionary.", "if", "isinstance", "(", "d", ",", "(", "list", ",", "tuple", ")", ")", ":", "d", "=", "dict", "(", "zip", "(", "self", ".", "attributes", ",", "d", ")", ")", "for", "k", "in", "d", ":", "at", "=", "self", ".", "attribute_types", ".", "get", "(", "k", ")", "if", "isinstance", "(", "d", "[", "k", "]", ",", "Value", ")", ":", "continue", "elif", "d", "[", "k", "]", "==", "MISSING", ":", "d", "[", "k", "]", "=", "Str", "(", "d", "[", "k", "]", ")", "elif", "at", "in", "(", "TYPE_NUMERIC", ",", "TYPE_REAL", ")", ":", "d", "[", "k", "]", "=", "Num", "(", "d", "[", "k", "]", ")", "elif", "at", "==", "TYPE_STRING", ":", "d", "[", "k", "]", "=", "Str", "(", "d", "[", "k", "]", ")", "elif", "at", "==", "TYPE_INTEGER", ":", "d", "[", "k", "]", "=", "Int", "(", "d", "[", "k", "]", ")", "elif", "at", "==", "TYPE_NOMINAL", ":", "d", "[", "k", "]", "=", "Nom", "(", "d", "[", "k", "]", ")", "elif", "at", "==", "TYPE_DATE", ":", "d", "[", "k", "]", "=", "Date", "(", "d", "[", "k", "]", ")", "else", ":", "raise", "Exception", "(", "'Unknown type: %s'", "%", "at", ")", "for", "i", ",", "name", "in", "enumerate", "(", "self", ".", "attributes", ")", ":", "v", "=", "d", ".", "get", "(", "name", ")", "if", "v", "is", "None", ":", "# print 'Skipping attribute with None value:', name", "continue", "elif", "v", "==", "MISSING", "or", "(", "isinstance", "(", "v", ",", "Value", ")", "and", "v", ".", "value", "==", "MISSING", ")", ":", "v", "=", "MISSING", "elif", "isinstance", "(", "v", ",", "String", ")", ":", "v", "=", "'\"%s\"'", "%", "v", ".", "value", "elif", "isinstance", "(", "v", ",", "Date", ")", ":", "date_format", "=", "self", ".", "attribute_data", ".", "get", "(", "name", ",", "DEFAULT_DATE_FORMAT", ")", "date_format", "=", "convert_weka_to_py_date_pattern", "(", "date_format", ")", "if", "isinstance", "(", "v", ".", "value", ",", "basestring", ")", ":", "_value", "=", "dateutil", ".", "parser", ".", "parse", "(", "v", ".", "value", ")", "else", ":", "assert", "isinstance", "(", "v", ".", "value", ",", "(", "date", ",", "datetime", ")", ")", "_value", "=", "v", ".", "value", "v", ".", "value", "=", "v", "=", "_value", ".", "strftime", "(", "date_format", ")", "elif", "isinstance", "(", "v", ",", "Value", ")", ":", "v", "=", "v", ".", "value", "if", "v", "!=", "MISSING", "and", "self", ".", "attribute_types", "[", "name", "]", "==", "TYPE_NOMINAL", "and", "str", "(", "v", ")", "not", "in", "map", "(", "str", ",", "self", ".", "attribute_data", "[", "name", "]", ")", ":", "pass", "else", ":", "line", ".", "append", "(", "'%i %s'", "%", "(", "i", ",", "smart_quote", "(", "v", ")", ")", ")", "if", "len", "(", "line", ")", "==", "1", "and", "MISSING", "in", "line", "[", "-", "1", "]", ":", "# Skip lines with nothing other than a missing class.", "return", "elif", "not", "line", ":", "# Don't write blank lines.", "return", "return", "'{'", "+", "(", "', '", ".", "join", "(", "line", ")", ")", "+", "'}'", "else", ":", "raise", "Exception", "(", "'Uknown format: %s'", "%", "(", "fmt", ",", ")", ")" ]
Converts a single data line to a string.
[ "Converts", "a", "single", "data", "line", "to", "a", "string", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L447-L532
chrisspen/weka
weka/arff.py
ArffFile.write
def write(self, fout=None, fmt=SPARSE, schema_only=False, data_only=False): """ Write an arff structure to a string. """ assert not (schema_only and data_only), 'Make up your mind.' assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s' % (fmt, ', '.join(FORMATS)) close = False if fout is None: close = True fout = StringIO() if not data_only: print('% ' + re.sub("\n", "\n% ", '\n'.join(self.comment)), file=fout) print("@relation " + self.relation, file=fout) self.write_attributes(fout=fout) if not schema_only: print("@data", file=fout) for d in self.data: line_str = self.write_line(d, fmt=fmt) if line_str: print(line_str, file=fout) if isinstance(fout, StringIO) and close: return fout.getvalue()
python
def write(self, fout=None, fmt=SPARSE, schema_only=False, data_only=False): """ Write an arff structure to a string. """ assert not (schema_only and data_only), 'Make up your mind.' assert fmt in FORMATS, 'Invalid format "%s". Should be one of: %s' % (fmt, ', '.join(FORMATS)) close = False if fout is None: close = True fout = StringIO() if not data_only: print('% ' + re.sub("\n", "\n% ", '\n'.join(self.comment)), file=fout) print("@relation " + self.relation, file=fout) self.write_attributes(fout=fout) if not schema_only: print("@data", file=fout) for d in self.data: line_str = self.write_line(d, fmt=fmt) if line_str: print(line_str, file=fout) if isinstance(fout, StringIO) and close: return fout.getvalue()
[ "def", "write", "(", "self", ",", "fout", "=", "None", ",", "fmt", "=", "SPARSE", ",", "schema_only", "=", "False", ",", "data_only", "=", "False", ")", ":", "assert", "not", "(", "schema_only", "and", "data_only", ")", ",", "'Make up your mind.'", "assert", "fmt", "in", "FORMATS", ",", "'Invalid format \"%s\". Should be one of: %s'", "%", "(", "fmt", ",", "', '", ".", "join", "(", "FORMATS", ")", ")", "close", "=", "False", "if", "fout", "is", "None", ":", "close", "=", "True", "fout", "=", "StringIO", "(", ")", "if", "not", "data_only", ":", "print", "(", "'% '", "+", "re", ".", "sub", "(", "\"\\n\"", ",", "\"\\n% \"", ",", "'\\n'", ".", "join", "(", "self", ".", "comment", ")", ")", ",", "file", "=", "fout", ")", "print", "(", "\"@relation \"", "+", "self", ".", "relation", ",", "file", "=", "fout", ")", "self", ".", "write_attributes", "(", "fout", "=", "fout", ")", "if", "not", "schema_only", ":", "print", "(", "\"@data\"", ",", "file", "=", "fout", ")", "for", "d", "in", "self", ".", "data", ":", "line_str", "=", "self", ".", "write_line", "(", "d", ",", "fmt", "=", "fmt", ")", "if", "line_str", ":", "print", "(", "line_str", ",", "file", "=", "fout", ")", "if", "isinstance", "(", "fout", ",", "StringIO", ")", "and", "close", ":", "return", "fout", ".", "getvalue", "(", ")" ]
Write an arff structure to a string.
[ "Write", "an", "arff", "structure", "to", "a", "string", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L559-L584
chrisspen/weka
weka/arff.py
ArffFile.define_attribute
def define_attribute(self, name, atype, data=None): """ Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data. """ self.attributes.append(name) assert atype in TYPES, "Unknown type '%s'. Must be one of: %s" % (atype, ', '.join(TYPES),) self.attribute_types[name] = atype self.attribute_data[name] = data
python
def define_attribute(self, name, atype, data=None): """ Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data. """ self.attributes.append(name) assert atype in TYPES, "Unknown type '%s'. Must be one of: %s" % (atype, ', '.join(TYPES),) self.attribute_types[name] = atype self.attribute_data[name] = data
[ "def", "define_attribute", "(", "self", ",", "name", ",", "atype", ",", "data", "=", "None", ")", ":", "self", ".", "attributes", ".", "append", "(", "name", ")", "assert", "atype", "in", "TYPES", ",", "\"Unknown type '%s'. Must be one of: %s\"", "%", "(", "atype", ",", "', '", ".", "join", "(", "TYPES", ")", ",", ")", "self", ".", "attribute_types", "[", "name", "]", "=", "atype", "self", ".", "attribute_data", "[", "name", "]", "=", "data" ]
Define a new attribute. atype has to be one of 'integer', 'real', 'numeric', 'string', 'date' or 'nominal'. For nominal attributes, pass the possible values as data. For date attributes, pass the format as data.
[ "Define", "a", "new", "attribute", ".", "atype", "has", "to", "be", "one", "of", "integer", "real", "numeric", "string", "date", "or", "nominal", ".", "For", "nominal", "attributes", "pass", "the", "possible", "values", "as", "data", ".", "For", "date", "attributes", "pass", "the", "format", "as", "data", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L592-L601
chrisspen/weka
weka/arff.py
ArffFile.dump
def dump(self): """Print an overview of the ARFF file.""" print("Relation " + self.relation) print(" With attributes") for n in self.attributes: if self.attribute_types[n] != TYPE_NOMINAL: print(" %s of type %s" % (n, self.attribute_types[n])) else: print(" " + n + " of type nominal with values " + ', '.join(self.attribute_data[n])) for d in self.data: print(d)
python
def dump(self): """Print an overview of the ARFF file.""" print("Relation " + self.relation) print(" With attributes") for n in self.attributes: if self.attribute_types[n] != TYPE_NOMINAL: print(" %s of type %s" % (n, self.attribute_types[n])) else: print(" " + n + " of type nominal with values " + ', '.join(self.attribute_data[n])) for d in self.data: print(d)
[ "def", "dump", "(", "self", ")", ":", "print", "(", "\"Relation \"", "+", "self", ".", "relation", ")", "print", "(", "\" With attributes\"", ")", "for", "n", "in", "self", ".", "attributes", ":", "if", "self", ".", "attribute_types", "[", "n", "]", "!=", "TYPE_NOMINAL", ":", "print", "(", "\" %s of type %s\"", "%", "(", "n", ",", "self", ".", "attribute_types", "[", "n", "]", ")", ")", "else", ":", "print", "(", "\" \"", "+", "n", "+", "\" of type nominal with values \"", "+", "', '", ".", "join", "(", "self", ".", "attribute_data", "[", "n", "]", ")", ")", "for", "d", "in", "self", ".", "data", ":", "print", "(", "d", ")" ]
Print an overview of the ARFF file.
[ "Print", "an", "overview", "of", "the", "ARFF", "file", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L722-L732
chrisspen/weka
weka/arff.py
ArffFile.alphabetize_attributes
def alphabetize_attributes(self): """ Orders attributes names alphabetically, except for the class attribute, which is kept last. """ self.attributes.sort(key=lambda name: (name == self.class_attr_name, name))
python
def alphabetize_attributes(self): """ Orders attributes names alphabetically, except for the class attribute, which is kept last. """ self.attributes.sort(key=lambda name: (name == self.class_attr_name, name))
[ "def", "alphabetize_attributes", "(", "self", ")", ":", "self", ".", "attributes", ".", "sort", "(", "key", "=", "lambda", "name", ":", "(", "name", "==", "self", ".", "class_attr_name", ",", "name", ")", ")" ]
Orders attributes names alphabetically, except for the class attribute, which is kept last.
[ "Orders", "attributes", "names", "alphabetically", "except", "for", "the", "class", "attribute", "which", "is", "kept", "last", "." ]
train
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L746-L750
xav/Grapefruit
grapefruit.py
rgb_to_hsl
def rgb_to_hsl(r, g=None, b=None): """Convert the color from RGB coordinates to HSL. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, l) tuple in the range: h[0...360], s[0...1], l[0...1] >>> rgb_to_hsl(1, 0.5, 0) (30.0, 1.0, 0.5) """ if type(r) in [list,tuple]: r, g, b = r minVal = min(r, g, b) # min RGB value maxVal = max(r, g, b) # max RGB value l = (maxVal + minVal) / 2.0 if minVal==maxVal: return (0.0, 0.0, l) # achromatic (gray) d = maxVal - minVal # delta RGB value if l < 0.5: s = d / (maxVal + minVal) else: s = d / (2.0 - maxVal - minVal) dr, dg, db = [(maxVal-val) / d for val in (r, g, b)] if r==maxVal: h = db - dg elif g==maxVal: h = 2.0 + dr - db else: h = 4.0 + dg - dr h = (h*60.0) % 360.0 return (h, s, l)
python
def rgb_to_hsl(r, g=None, b=None): """Convert the color from RGB coordinates to HSL. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, l) tuple in the range: h[0...360], s[0...1], l[0...1] >>> rgb_to_hsl(1, 0.5, 0) (30.0, 1.0, 0.5) """ if type(r) in [list,tuple]: r, g, b = r minVal = min(r, g, b) # min RGB value maxVal = max(r, g, b) # max RGB value l = (maxVal + minVal) / 2.0 if minVal==maxVal: return (0.0, 0.0, l) # achromatic (gray) d = maxVal - minVal # delta RGB value if l < 0.5: s = d / (maxVal + minVal) else: s = d / (2.0 - maxVal - minVal) dr, dg, db = [(maxVal-val) / d for val in (r, g, b)] if r==maxVal: h = db - dg elif g==maxVal: h = 2.0 + dr - db else: h = 4.0 + dg - dr h = (h*60.0) % 360.0 return (h, s, l)
[ "def", "rgb_to_hsl", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "minVal", "=", "min", "(", "r", ",", "g", ",", "b", ")", "# min RGB value", "maxVal", "=", "max", "(", "r", ",", "g", ",", "b", ")", "# max RGB value", "l", "=", "(", "maxVal", "+", "minVal", ")", "/", "2.0", "if", "minVal", "==", "maxVal", ":", "return", "(", "0.0", ",", "0.0", ",", "l", ")", "# achromatic (gray)", "d", "=", "maxVal", "-", "minVal", "# delta RGB value", "if", "l", "<", "0.5", ":", "s", "=", "d", "/", "(", "maxVal", "+", "minVal", ")", "else", ":", "s", "=", "d", "/", "(", "2.0", "-", "maxVal", "-", "minVal", ")", "dr", ",", "dg", ",", "db", "=", "[", "(", "maxVal", "-", "val", ")", "/", "d", "for", "val", "in", "(", "r", ",", "g", ",", "b", ")", "]", "if", "r", "==", "maxVal", ":", "h", "=", "db", "-", "dg", "elif", "g", "==", "maxVal", ":", "h", "=", "2.0", "+", "dr", "-", "db", "else", ":", "h", "=", "4.0", "+", "dg", "-", "dr", "h", "=", "(", "h", "*", "60.0", ")", "%", "360.0", "return", "(", "h", ",", "s", ",", "l", ")" ]
Convert the color from RGB coordinates to HSL. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, l) tuple in the range: h[0...360], s[0...1], l[0...1] >>> rgb_to_hsl(1, 0.5, 0) (30.0, 1.0, 0.5)
[ "Convert", "the", "color", "from", "RGB", "coordinates", "to", "HSL", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L249-L295
xav/Grapefruit
grapefruit.py
hsl_to_rgb
def hsl_to_rgb(h, s=None, l=None): """Convert the color from HSL coordinates to RGB. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> hsl_to_rgb(30.0, 1.0, 0.5) (1.0, 0.5, 0.0) """ if type(h) in [list,tuple]: h, s, l = h if s==0: return (l, l, l) # achromatic (gray) if l<0.5: n2 = l * (1.0 + s) else: n2 = l+s - (l*s) n1 = (2.0 * l) - n2 h /= 60.0 hueToRgb = _hue_to_rgb r = hueToRgb(n1, n2, h + 2) g = hueToRgb(n1, n2, h) b = hueToRgb(n1, n2, h - 2) return (r, g, b)
python
def hsl_to_rgb(h, s=None, l=None): """Convert the color from HSL coordinates to RGB. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> hsl_to_rgb(30.0, 1.0, 0.5) (1.0, 0.5, 0.0) """ if type(h) in [list,tuple]: h, s, l = h if s==0: return (l, l, l) # achromatic (gray) if l<0.5: n2 = l * (1.0 + s) else: n2 = l+s - (l*s) n1 = (2.0 * l) - n2 h /= 60.0 hueToRgb = _hue_to_rgb r = hueToRgb(n1, n2, h + 2) g = hueToRgb(n1, n2, h) b = hueToRgb(n1, n2, h - 2) return (r, g, b)
[ "def", "hsl_to_rgb", "(", "h", ",", "s", "=", "None", ",", "l", "=", "None", ")", ":", "if", "type", "(", "h", ")", "in", "[", "list", ",", "tuple", "]", ":", "h", ",", "s", ",", "l", "=", "h", "if", "s", "==", "0", ":", "return", "(", "l", ",", "l", ",", "l", ")", "# achromatic (gray)", "if", "l", "<", "0.5", ":", "n2", "=", "l", "*", "(", "1.0", "+", "s", ")", "else", ":", "n2", "=", "l", "+", "s", "-", "(", "l", "*", "s", ")", "n1", "=", "(", "2.0", "*", "l", ")", "-", "n2", "h", "/=", "60.0", "hueToRgb", "=", "_hue_to_rgb", "r", "=", "hueToRgb", "(", "n1", ",", "n2", ",", "h", "+", "2", ")", "g", "=", "hueToRgb", "(", "n1", ",", "n2", ",", "h", ")", "b", "=", "hueToRgb", "(", "n1", ",", "n2", ",", "h", "-", "2", ")", "return", "(", "r", ",", "g", ",", "b", ")" ]
Convert the color from HSL coordinates to RGB. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> hsl_to_rgb(30.0, 1.0, 0.5) (1.0, 0.5, 0.0)
[ "Convert", "the", "color", "from", "HSL", "coordinates", "to", "RGB", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L307-L344
xav/Grapefruit
grapefruit.py
rgb_to_hsv
def rgb_to_hsv(r, g=None, b=None): """Convert the color from RGB coordinates to HSV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, v) tuple in the range: h[0...360], s[0...1], v[0...1] >>> rgb_to_hsv(1, 0.5, 0) (30.0, 1.0, 1.0) """ if type(r) in [list,tuple]: r, g, b = r v = float(max(r, g, b)) d = v - min(r, g, b) if d==0: return (0.0, 0.0, v) s = d / v dr, dg, db = [(v - val) / d for val in (r, g, b)] if r==v: h = db - dg # between yellow & magenta elif g==v: h = 2.0 + dr - db # between cyan & yellow else: # b==v h = 4.0 + dg - dr # between magenta & cyan h = (h*60.0) % 360.0 return (h, s, v)
python
def rgb_to_hsv(r, g=None, b=None): """Convert the color from RGB coordinates to HSV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, v) tuple in the range: h[0...360], s[0...1], v[0...1] >>> rgb_to_hsv(1, 0.5, 0) (30.0, 1.0, 1.0) """ if type(r) in [list,tuple]: r, g, b = r v = float(max(r, g, b)) d = v - min(r, g, b) if d==0: return (0.0, 0.0, v) s = d / v dr, dg, db = [(v - val) / d for val in (r, g, b)] if r==v: h = db - dg # between yellow & magenta elif g==v: h = 2.0 + dr - db # between cyan & yellow else: # b==v h = 4.0 + dg - dr # between magenta & cyan h = (h*60.0) % 360.0 return (h, s, v)
[ "def", "rgb_to_hsv", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "v", "=", "float", "(", "max", "(", "r", ",", "g", ",", "b", ")", ")", "d", "=", "v", "-", "min", "(", "r", ",", "g", ",", "b", ")", "if", "d", "==", "0", ":", "return", "(", "0.0", ",", "0.0", ",", "v", ")", "s", "=", "d", "/", "v", "dr", ",", "dg", ",", "db", "=", "[", "(", "v", "-", "val", ")", "/", "d", "for", "val", "in", "(", "r", ",", "g", ",", "b", ")", "]", "if", "r", "==", "v", ":", "h", "=", "db", "-", "dg", "# between yellow & magenta", "elif", "g", "==", "v", ":", "h", "=", "2.0", "+", "dr", "-", "db", "# between cyan & yellow", "else", ":", "# b==v", "h", "=", "4.0", "+", "dg", "-", "dr", "# between magenta & cyan", "h", "=", "(", "h", "*", "60.0", ")", "%", "360.0", "return", "(", "h", ",", "s", ",", "v", ")" ]
Convert the color from RGB coordinates to HSV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (h, s, v) tuple in the range: h[0...360], s[0...1], v[0...1] >>> rgb_to_hsv(1, 0.5, 0) (30.0, 1.0, 1.0)
[ "Convert", "the", "color", "from", "RGB", "coordinates", "to", "HSV", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L346-L385
xav/Grapefruit
grapefruit.py
hsv_to_rgb
def hsv_to_rgb(h, s=None, v=None): """Convert the color from RGB coordinates to HSV. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> hsv_to_rgb(30.0, 1.0, 0.5) (0.5, 0.25, 0.0) """ if type(h) in [list,tuple]: h, s, v = h if s==0: return (v, v, v) # achromatic (gray) h /= 60.0 h = h % 6.0 i = int(h) f = h - i if not(i&1): f = 1-f # if i is even m = v * (1.0 - s) n = v * (1.0 - (s * f)) if i==0: return (v, n, m) if i==1: return (n, v, m) if i==2: return (m, v, n) if i==3: return (m, n, v) if i==4: return (n, m, v) return (v, m, n)
python
def hsv_to_rgb(h, s=None, v=None): """Convert the color from RGB coordinates to HSV. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> hsv_to_rgb(30.0, 1.0, 0.5) (0.5, 0.25, 0.0) """ if type(h) in [list,tuple]: h, s, v = h if s==0: return (v, v, v) # achromatic (gray) h /= 60.0 h = h % 6.0 i = int(h) f = h - i if not(i&1): f = 1-f # if i is even m = v * (1.0 - s) n = v * (1.0 - (s * f)) if i==0: return (v, n, m) if i==1: return (n, v, m) if i==2: return (m, v, n) if i==3: return (m, n, v) if i==4: return (n, m, v) return (v, m, n)
[ "def", "hsv_to_rgb", "(", "h", ",", "s", "=", "None", ",", "v", "=", "None", ")", ":", "if", "type", "(", "h", ")", "in", "[", "list", ",", "tuple", "]", ":", "h", ",", "s", ",", "v", "=", "h", "if", "s", "==", "0", ":", "return", "(", "v", ",", "v", ",", "v", ")", "# achromatic (gray)", "h", "/=", "60.0", "h", "=", "h", "%", "6.0", "i", "=", "int", "(", "h", ")", "f", "=", "h", "-", "i", "if", "not", "(", "i", "&", "1", ")", ":", "f", "=", "1", "-", "f", "# if i is even", "m", "=", "v", "*", "(", "1.0", "-", "s", ")", "n", "=", "v", "*", "(", "1.0", "-", "(", "s", "*", "f", ")", ")", "if", "i", "==", "0", ":", "return", "(", "v", ",", "n", ",", "m", ")", "if", "i", "==", "1", ":", "return", "(", "n", ",", "v", ",", "m", ")", "if", "i", "==", "2", ":", "return", "(", "m", ",", "v", ",", "n", ")", "if", "i", "==", "3", ":", "return", "(", "m", ",", "n", ",", "v", ")", "if", "i", "==", "4", ":", "return", "(", "n", ",", "m", ",", "v", ")", "return", "(", "v", ",", "m", ",", "n", ")" ]
Convert the color from RGB coordinates to HSV. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> hsv_to_rgb(30.0, 1.0, 0.5) (0.5, 0.25, 0.0)
[ "Convert", "the", "color", "from", "RGB", "coordinates", "to", "HSV", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L387-L428
xav/Grapefruit
grapefruit.py
rgb_to_yiq
def rgb_to_yiq(r, g=None, b=None): """Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1], q[0...1] >>> '(%g, %g, %g)' % rgb_to_yiq(1, 0.5, 0) '(0.592263, 0.458874, -0.0499818)' """ if type(r) in [list,tuple]: r, g, b = r y = (r * 0.29895808) + (g * 0.58660979) + (b *0.11443213) i = (r * 0.59590296) - (g * 0.27405705) - (b *0.32184591) q = (r * 0.21133576) - (g * 0.52263517) + (b *0.31129940) return (y, i, q)
python
def rgb_to_yiq(r, g=None, b=None): """Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1], q[0...1] >>> '(%g, %g, %g)' % rgb_to_yiq(1, 0.5, 0) '(0.592263, 0.458874, -0.0499818)' """ if type(r) in [list,tuple]: r, g, b = r y = (r * 0.29895808) + (g * 0.58660979) + (b *0.11443213) i = (r * 0.59590296) - (g * 0.27405705) - (b *0.32184591) q = (r * 0.21133576) - (g * 0.52263517) + (b *0.31129940) return (y, i, q)
[ "def", "rgb_to_yiq", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "y", "=", "(", "r", "*", "0.29895808", ")", "+", "(", "g", "*", "0.58660979", ")", "+", "(", "b", "*", "0.11443213", ")", "i", "=", "(", "r", "*", "0.59590296", ")", "-", "(", "g", "*", "0.27405705", ")", "-", "(", "b", "*", "0.32184591", ")", "q", "=", "(", "r", "*", "0.21133576", ")", "-", "(", "g", "*", "0.52263517", ")", "+", "(", "b", "*", "0.31129940", ")", "return", "(", "y", ",", "i", ",", "q", ")" ]
Convert the color from RGB to YIQ. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, i, q) tuple in the range: y[0...1], i[0...1], q[0...1] >>> '(%g, %g, %g)' % rgb_to_yiq(1, 0.5, 0) '(0.592263, 0.458874, -0.0499818)'
[ "Convert", "the", "color", "from", "RGB", "to", "YIQ", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L430-L457
xav/Grapefruit
grapefruit.py
yiq_to_rgb
def yiq_to_rgb(y, i=None, q=None): """Convert the color from YIQ coordinates to RGB. Parameters: :y: Tte Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '({}, {}, {})'.format(*[round(v, 6) for v in yiq_to_rgb(0.592263, 0.458874, -0.0499818)]) '(1.0, 0.5, 1e-06)' """ if type(y) in [list,tuple]: y, i, q = y r = y + (i * 0.9562) + (q * 0.6210) g = y - (i * 0.2717) - (q * 0.6485) b = y - (i * 1.1053) + (q * 1.7020) return (r, g, b)
python
def yiq_to_rgb(y, i=None, q=None): """Convert the color from YIQ coordinates to RGB. Parameters: :y: Tte Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '({}, {}, {})'.format(*[round(v, 6) for v in yiq_to_rgb(0.592263, 0.458874, -0.0499818)]) '(1.0, 0.5, 1e-06)' """ if type(y) in [list,tuple]: y, i, q = y r = y + (i * 0.9562) + (q * 0.6210) g = y - (i * 0.2717) - (q * 0.6485) b = y - (i * 1.1053) + (q * 1.7020) return (r, g, b)
[ "def", "yiq_to_rgb", "(", "y", ",", "i", "=", "None", ",", "q", "=", "None", ")", ":", "if", "type", "(", "y", ")", "in", "[", "list", ",", "tuple", "]", ":", "y", ",", "i", ",", "q", "=", "y", "r", "=", "y", "+", "(", "i", "*", "0.9562", ")", "+", "(", "q", "*", "0.6210", ")", "g", "=", "y", "-", "(", "i", "*", "0.2717", ")", "-", "(", "q", "*", "0.6485", ")", "b", "=", "y", "-", "(", "i", "*", "1.1053", ")", "+", "(", "q", "*", "1.7020", ")", "return", "(", "r", ",", "g", ",", "b", ")" ]
Convert the color from YIQ coordinates to RGB. Parameters: :y: Tte Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '({}, {}, {})'.format(*[round(v, 6) for v in yiq_to_rgb(0.592263, 0.458874, -0.0499818)]) '(1.0, 0.5, 1e-06)'
[ "Convert", "the", "color", "from", "YIQ", "coordinates", "to", "RGB", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L459-L485
xav/Grapefruit
grapefruit.py
rgb_to_yuv
def rgb_to_yuv(r, g=None, b=None): """Convert the color from RGB coordinates to YUV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, u, v) tuple in the range: y[0...1], u[-0.436...0.436], v[-0.615...0.615] >>> '(%g, %g, %g)' % rgb_to_yuv(1, 0.5, 0) '(0.5925, -0.29156, 0.357505)' """ if type(r) in [list,tuple]: r, g, b = r y = (r * 0.29900) + (g * 0.58700) + (b * 0.11400) u = -(r * 0.14713) - (g * 0.28886) + (b * 0.43600) v = (r * 0.61500) - (g * 0.51499) - (b * 0.10001) return (y, u, v)
python
def rgb_to_yuv(r, g=None, b=None): """Convert the color from RGB coordinates to YUV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, u, v) tuple in the range: y[0...1], u[-0.436...0.436], v[-0.615...0.615] >>> '(%g, %g, %g)' % rgb_to_yuv(1, 0.5, 0) '(0.5925, -0.29156, 0.357505)' """ if type(r) in [list,tuple]: r, g, b = r y = (r * 0.29900) + (g * 0.58700) + (b * 0.11400) u = -(r * 0.14713) - (g * 0.28886) + (b * 0.43600) v = (r * 0.61500) - (g * 0.51499) - (b * 0.10001) return (y, u, v)
[ "def", "rgb_to_yuv", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "y", "=", "(", "r", "*", "0.29900", ")", "+", "(", "g", "*", "0.58700", ")", "+", "(", "b", "*", "0.11400", ")", "u", "=", "-", "(", "r", "*", "0.14713", ")", "-", "(", "g", "*", "0.28886", ")", "+", "(", "b", "*", "0.43600", ")", "v", "=", "(", "r", "*", "0.61500", ")", "-", "(", "g", "*", "0.51499", ")", "-", "(", "b", "*", "0.10001", ")", "return", "(", "y", ",", "u", ",", "v", ")" ]
Convert the color from RGB coordinates to YUV. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (y, u, v) tuple in the range: y[0...1], u[-0.436...0.436], v[-0.615...0.615] >>> '(%g, %g, %g)' % rgb_to_yuv(1, 0.5, 0) '(0.5925, -0.29156, 0.357505)'
[ "Convert", "the", "color", "from", "RGB", "coordinates", "to", "YUV", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L487-L514
xav/Grapefruit
grapefruit.py
yuv_to_rgb
def yuv_to_rgb(y, u=None, v=None): """Convert the color from YUV coordinates to RGB. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % yuv_to_rgb(0.5925, -0.2916, 0.3575) '(0.999989, 0.500015, -6.3276e-05)' """ if type(y) in [list,tuple]: y, u, v = y r = y + (v * 1.13983) g = y - (u * 0.39465) - (v * 0.58060) b = y + (u * 2.03211) return (r, g, b)
python
def yuv_to_rgb(y, u=None, v=None): """Convert the color from YUV coordinates to RGB. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % yuv_to_rgb(0.5925, -0.2916, 0.3575) '(0.999989, 0.500015, -6.3276e-05)' """ if type(y) in [list,tuple]: y, u, v = y r = y + (v * 1.13983) g = y - (u * 0.39465) - (v * 0.58060) b = y + (u * 2.03211) return (r, g, b)
[ "def", "yuv_to_rgb", "(", "y", ",", "u", "=", "None", ",", "v", "=", "None", ")", ":", "if", "type", "(", "y", ")", "in", "[", "list", ",", "tuple", "]", ":", "y", ",", "u", ",", "v", "=", "y", "r", "=", "y", "+", "(", "v", "*", "1.13983", ")", "g", "=", "y", "-", "(", "u", "*", "0.39465", ")", "-", "(", "v", "*", "0.58060", ")", "b", "=", "y", "+", "(", "u", "*", "2.03211", ")", "return", "(", "r", ",", "g", ",", "b", ")" ]
Convert the color from YUV coordinates to RGB. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % yuv_to_rgb(0.5925, -0.2916, 0.3575) '(0.999989, 0.500015, -6.3276e-05)'
[ "Convert", "the", "color", "from", "YUV", "coordinates", "to", "RGB", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L516-L542
xav/Grapefruit
grapefruit.py
rgb_to_xyz
def rgb_to_xyz(r, g=None, b=None): """Convert the color from sRGB to CIE XYZ. The methods assumes that the RGB coordinates are given in the sRGB colorspace (D65). .. note:: Compensation for the sRGB gamma correction is applied before converting. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (x, y, z) tuple in the range: x[0...1], y[0...1], z[0...1] >>> '(%g, %g, %g)' % rgb_to_xyz(1, 0.5, 0) '(0.488941, 0.365682, 0.0448137)' """ if type(r) in [list,tuple]: r, g, b = r r, g, b = [((v <= 0.03928) and [v / 12.92] or [((v+0.055) / 1.055) **2.4])[0] for v in (r, g, b)] x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805) y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722) z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505) return (x, y, z)
python
def rgb_to_xyz(r, g=None, b=None): """Convert the color from sRGB to CIE XYZ. The methods assumes that the RGB coordinates are given in the sRGB colorspace (D65). .. note:: Compensation for the sRGB gamma correction is applied before converting. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (x, y, z) tuple in the range: x[0...1], y[0...1], z[0...1] >>> '(%g, %g, %g)' % rgb_to_xyz(1, 0.5, 0) '(0.488941, 0.365682, 0.0448137)' """ if type(r) in [list,tuple]: r, g, b = r r, g, b = [((v <= 0.03928) and [v / 12.92] or [((v+0.055) / 1.055) **2.4])[0] for v in (r, g, b)] x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805) y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722) z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505) return (x, y, z)
[ "def", "rgb_to_xyz", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "r", ",", "g", ",", "b", "=", "[", "(", "(", "v", "<=", "0.03928", ")", "and", "[", "v", "/", "12.92", "]", "or", "[", "(", "(", "v", "+", "0.055", ")", "/", "1.055", ")", "**", "2.4", "]", ")", "[", "0", "]", "for", "v", "in", "(", "r", ",", "g", ",", "b", ")", "]", "x", "=", "(", "r", "*", "0.4124", ")", "+", "(", "g", "*", "0.3576", ")", "+", "(", "b", "*", "0.1805", ")", "y", "=", "(", "r", "*", "0.2126", ")", "+", "(", "g", "*", "0.7152", ")", "+", "(", "b", "*", "0.0722", ")", "z", "=", "(", "r", "*", "0.0193", ")", "+", "(", "g", "*", "0.1192", ")", "+", "(", "b", "*", "0.9505", ")", "return", "(", "x", ",", "y", ",", "z", ")" ]
Convert the color from sRGB to CIE XYZ. The methods assumes that the RGB coordinates are given in the sRGB colorspace (D65). .. note:: Compensation for the sRGB gamma correction is applied before converting. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (x, y, z) tuple in the range: x[0...1], y[0...1], z[0...1] >>> '(%g, %g, %g)' % rgb_to_xyz(1, 0.5, 0) '(0.488941, 0.365682, 0.0448137)'
[ "Convert", "the", "color", "from", "sRGB", "to", "CIE", "XYZ", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L544-L580
xav/Grapefruit
grapefruit.py
xyz_to_rgb
def xyz_to_rgb(x, y=None, z=None): """Convert the color from CIE XYZ coordinates to sRGB. .. note:: Compensation for sRGB gamma correction is applied before converting. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % xyz_to_rgb(0.488941, 0.365682, 0.0448137) '(1, 0.5, 6.81883e-08)' """ if type(x) in [list,tuple]: x, y, z = x r = (x * 3.2406255) - (y * 1.5372080) - (z * 0.4986286) g = -(x * 0.9689307) + (y * 1.8757561) + (z * 0.0415175) b = (x * 0.0557101) - (y * 0.2040211) + (z * 1.0569959) return tuple((((v <= _srgbGammaCorrInv) and [v * 12.92] or [(1.055 * (v ** (1/2.4))) - 0.055])[0] for v in (r, g, b)))
python
def xyz_to_rgb(x, y=None, z=None): """Convert the color from CIE XYZ coordinates to sRGB. .. note:: Compensation for sRGB gamma correction is applied before converting. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % xyz_to_rgb(0.488941, 0.365682, 0.0448137) '(1, 0.5, 6.81883e-08)' """ if type(x) in [list,tuple]: x, y, z = x r = (x * 3.2406255) - (y * 1.5372080) - (z * 0.4986286) g = -(x * 0.9689307) + (y * 1.8757561) + (z * 0.0415175) b = (x * 0.0557101) - (y * 0.2040211) + (z * 1.0569959) return tuple((((v <= _srgbGammaCorrInv) and [v * 12.92] or [(1.055 * (v ** (1/2.4))) - 0.055])[0] for v in (r, g, b)))
[ "def", "xyz_to_rgb", "(", "x", ",", "y", "=", "None", ",", "z", "=", "None", ")", ":", "if", "type", "(", "x", ")", "in", "[", "list", ",", "tuple", "]", ":", "x", ",", "y", ",", "z", "=", "x", "r", "=", "(", "x", "*", "3.2406255", ")", "-", "(", "y", "*", "1.5372080", ")", "-", "(", "z", "*", "0.4986286", ")", "g", "=", "-", "(", "x", "*", "0.9689307", ")", "+", "(", "y", "*", "1.8757561", ")", "+", "(", "z", "*", "0.0415175", ")", "b", "=", "(", "x", "*", "0.0557101", ")", "-", "(", "y", "*", "0.2040211", ")", "+", "(", "z", "*", "1.0569959", ")", "return", "tuple", "(", "(", "(", "(", "v", "<=", "_srgbGammaCorrInv", ")", "and", "[", "v", "*", "12.92", "]", "or", "[", "(", "1.055", "*", "(", "v", "**", "(", "1", "/", "2.4", ")", ")", ")", "-", "0.055", "]", ")", "[", "0", "]", "for", "v", "in", "(", "r", ",", "g", ",", "b", ")", ")", ")" ]
Convert the color from CIE XYZ coordinates to sRGB. .. note:: Compensation for sRGB gamma correction is applied before converting. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % xyz_to_rgb(0.488941, 0.365682, 0.0448137) '(1, 0.5, 6.81883e-08)'
[ "Convert", "the", "color", "from", "CIE", "XYZ", "coordinates", "to", "sRGB", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L582-L612
xav/Grapefruit
grapefruit.py
xyz_to_lab
def xyz_to_lab(x, y=None, z=None, wref=_DEFAULT_WREF): """Convert the color from CIE XYZ to CIE L*a*b*. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (L, a, b) tuple in the range: L[0...100], a[-1...1], b[-1...1] >>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137) '(66.9518, 0.430841, 0.739692)' >>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137, WHITE_REFERENCE['std_D50']) '(66.9518, 0.41166, 0.67282)' """ if type(x) in [list,tuple]: x, y, z = x # White point correction x /= wref[0] y /= wref[1] z /= wref[2] # Nonlinear distortion and linear transformation x, y, z = [((v > 0.008856) and [v**_oneThird] or [(7.787 * v) + _sixteenHundredsixteenth])[0] for v in (x, y, z)] # Vector scaling l = (116 * y) - 16 a = 5.0 * (x - y) b = 2.0 * (y - z) return (l, a, b)
python
def xyz_to_lab(x, y=None, z=None, wref=_DEFAULT_WREF): """Convert the color from CIE XYZ to CIE L*a*b*. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (L, a, b) tuple in the range: L[0...100], a[-1...1], b[-1...1] >>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137) '(66.9518, 0.430841, 0.739692)' >>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137, WHITE_REFERENCE['std_D50']) '(66.9518, 0.41166, 0.67282)' """ if type(x) in [list,tuple]: x, y, z = x # White point correction x /= wref[0] y /= wref[1] z /= wref[2] # Nonlinear distortion and linear transformation x, y, z = [((v > 0.008856) and [v**_oneThird] or [(7.787 * v) + _sixteenHundredsixteenth])[0] for v in (x, y, z)] # Vector scaling l = (116 * y) - 16 a = 5.0 * (x - y) b = 2.0 * (y - z) return (l, a, b)
[ "def", "xyz_to_lab", "(", "x", ",", "y", "=", "None", ",", "z", "=", "None", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "if", "type", "(", "x", ")", "in", "[", "list", ",", "tuple", "]", ":", "x", ",", "y", ",", "z", "=", "x", "# White point correction", "x", "/=", "wref", "[", "0", "]", "y", "/=", "wref", "[", "1", "]", "z", "/=", "wref", "[", "2", "]", "# Nonlinear distortion and linear transformation", "x", ",", "y", ",", "z", "=", "[", "(", "(", "v", ">", "0.008856", ")", "and", "[", "v", "**", "_oneThird", "]", "or", "[", "(", "7.787", "*", "v", ")", "+", "_sixteenHundredsixteenth", "]", ")", "[", "0", "]", "for", "v", "in", "(", "x", ",", "y", ",", "z", ")", "]", "# Vector scaling", "l", "=", "(", "116", "*", "y", ")", "-", "16", "a", "=", "5.0", "*", "(", "x", "-", "y", ")", "b", "=", "2.0", "*", "(", "y", "-", "z", ")", "return", "(", "l", ",", "a", ",", "b", ")" ]
Convert the color from CIE XYZ to CIE L*a*b*. Parameters: :x: The X component value [0...1] :y: The Y component value [0...1] :z: The Z component value [0...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (L, a, b) tuple in the range: L[0...100], a[-1...1], b[-1...1] >>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137) '(66.9518, 0.430841, 0.739692)' >>> '(%g, %g, %g)' % xyz_to_lab(0.488941, 0.365682, 0.0448137, WHITE_REFERENCE['std_D50']) '(66.9518, 0.41166, 0.67282)'
[ "Convert", "the", "color", "from", "CIE", "XYZ", "to", "CIE", "L", "*", "a", "*", "b", "*", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L614-L655
xav/Grapefruit
grapefruit.py
lab_to_xyz
def lab_to_xyz(l, a=None, b=None, wref=_DEFAULT_WREF): """Convert the color from CIE L*a*b* to CIE 1931 XYZ. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (x, y, z) tuple in the range: x[0...q], y[0...1], z[0...1] >>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.43084, 0.739692) '(0.48894, 0.365682, 0.0448137)' >>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.411663, 0.67282, WHITE_REFERENCE['std_D50']) '(0.488942, 0.365682, 0.0448137)' """ if type(l) in [list,tuple]: l, a, b = l y = (l + 16) / 116 x = (a / 5.0) + y z = y - (b / 2.0) return tuple((((v > 0.206893) and [v**3] or [(v - _sixteenHundredsixteenth) / 7.787])[0] * w for v, w in zip((x, y, z), wref)))
python
def lab_to_xyz(l, a=None, b=None, wref=_DEFAULT_WREF): """Convert the color from CIE L*a*b* to CIE 1931 XYZ. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (x, y, z) tuple in the range: x[0...q], y[0...1], z[0...1] >>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.43084, 0.739692) '(0.48894, 0.365682, 0.0448137)' >>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.411663, 0.67282, WHITE_REFERENCE['std_D50']) '(0.488942, 0.365682, 0.0448137)' """ if type(l) in [list,tuple]: l, a, b = l y = (l + 16) / 116 x = (a / 5.0) + y z = y - (b / 2.0) return tuple((((v > 0.206893) and [v**3] or [(v - _sixteenHundredsixteenth) / 7.787])[0] * w for v, w in zip((x, y, z), wref)))
[ "def", "lab_to_xyz", "(", "l", ",", "a", "=", "None", ",", "b", "=", "None", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "if", "type", "(", "l", ")", "in", "[", "list", ",", "tuple", "]", ":", "l", ",", "a", ",", "b", "=", "l", "y", "=", "(", "l", "+", "16", ")", "/", "116", "x", "=", "(", "a", "/", "5.0", ")", "+", "y", "z", "=", "y", "-", "(", "b", "/", "2.0", ")", "return", "tuple", "(", "(", "(", "(", "v", ">", "0.206893", ")", "and", "[", "v", "**", "3", "]", "or", "[", "(", "v", "-", "_sixteenHundredsixteenth", ")", "/", "7.787", "]", ")", "[", "0", "]", "*", "w", "for", "v", ",", "w", "in", "zip", "(", "(", "x", ",", "y", ",", "z", ")", ",", "wref", ")", ")", ")" ]
Convert the color from CIE L*a*b* to CIE 1931 XYZ. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :wref: The whitepoint reference, default is 2° D65. Returns: The color as an (x, y, z) tuple in the range: x[0...q], y[0...1], z[0...1] >>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.43084, 0.739692) '(0.48894, 0.365682, 0.0448137)' >>> '(%g, %g, %g)' % lab_to_xyz(66.9518, 0.411663, 0.67282, WHITE_REFERENCE['std_D50']) '(0.488942, 0.365682, 0.0448137)'
[ "Convert", "the", "color", "from", "CIE", "L", "*", "a", "*", "b", "*", "to", "CIE", "1931", "XYZ", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L657-L688
xav/Grapefruit
grapefruit.py
cmyk_to_cmy
def cmyk_to_cmy(c, m=None, y=None, k=None): """Convert the color from CMYK coordinates to CMY. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], m[0...1], y[0...1] >>> '(%g, %g, %g)' % cmyk_to_cmy(1, 0.32, 0, 0.5) '(1, 0.66, 0.5)' """ if type(c) in [list,tuple]: c, m, y, k = c mk = 1-k return ((c*mk + k), (m*mk + k), (y*mk + k))
python
def cmyk_to_cmy(c, m=None, y=None, k=None): """Convert the color from CMYK coordinates to CMY. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], m[0...1], y[0...1] >>> '(%g, %g, %g)' % cmyk_to_cmy(1, 0.32, 0, 0.5) '(1, 0.66, 0.5)' """ if type(c) in [list,tuple]: c, m, y, k = c mk = 1-k return ((c*mk + k), (m*mk + k), (y*mk + k))
[ "def", "cmyk_to_cmy", "(", "c", ",", "m", "=", "None", ",", "y", "=", "None", ",", "k", "=", "None", ")", ":", "if", "type", "(", "c", ")", "in", "[", "list", ",", "tuple", "]", ":", "c", ",", "m", ",", "y", ",", "k", "=", "c", "mk", "=", "1", "-", "k", "return", "(", "(", "c", "*", "mk", "+", "k", ")", ",", "(", "m", "*", "mk", "+", "k", ")", ",", "(", "y", "*", "mk", "+", "k", ")", ")" ]
Convert the color from CMYK coordinates to CMY. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], m[0...1], y[0...1] >>> '(%g, %g, %g)' % cmyk_to_cmy(1, 0.32, 0, 0.5) '(1, 0.66, 0.5)'
[ "Convert", "the", "color", "from", "CMYK", "coordinates", "to", "CMY", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L690-L716
xav/Grapefruit
grapefruit.py
cmy_to_cmyk
def cmy_to_cmyk(c, m=None, y=None): """Convert the color from CMY coordinates to CMYK. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (c, m, y, k) tuple in the range: c[0...1], m[0...1], y[0...1], k[0...1] >>> '(%g, %g, %g, %g)' % cmy_to_cmyk(1, 0.66, 0.5) '(1, 0.32, 0, 0.5)' """ if type(c) in [list,tuple]: c, m, y = c k = min(c, m, y) if k==1.0: return (0.0, 0.0, 0.0, 1.0) mk = 1.0-k return ((c-k) / mk, (m-k) / mk, (y-k) / mk, k)
python
def cmy_to_cmyk(c, m=None, y=None): """Convert the color from CMY coordinates to CMYK. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (c, m, y, k) tuple in the range: c[0...1], m[0...1], y[0...1], k[0...1] >>> '(%g, %g, %g, %g)' % cmy_to_cmyk(1, 0.66, 0.5) '(1, 0.32, 0, 0.5)' """ if type(c) in [list,tuple]: c, m, y = c k = min(c, m, y) if k==1.0: return (0.0, 0.0, 0.0, 1.0) mk = 1.0-k return ((c-k) / mk, (m-k) / mk, (y-k) / mk, k)
[ "def", "cmy_to_cmyk", "(", "c", ",", "m", "=", "None", ",", "y", "=", "None", ")", ":", "if", "type", "(", "c", ")", "in", "[", "list", ",", "tuple", "]", ":", "c", ",", "m", ",", "y", "=", "c", "k", "=", "min", "(", "c", ",", "m", ",", "y", ")", "if", "k", "==", "1.0", ":", "return", "(", "0.0", ",", "0.0", ",", "0.0", ",", "1.0", ")", "mk", "=", "1.0", "-", "k", "return", "(", "(", "c", "-", "k", ")", "/", "mk", ",", "(", "m", "-", "k", ")", "/", "mk", ",", "(", "y", "-", "k", ")", "/", "mk", ",", "k", ")" ]
Convert the color from CMY coordinates to CMYK. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (c, m, y, k) tuple in the range: c[0...1], m[0...1], y[0...1], k[0...1] >>> '(%g, %g, %g, %g)' % cmy_to_cmyk(1, 0.66, 0.5) '(1, 0.32, 0, 0.5)'
[ "Convert", "the", "color", "from", "CMY", "coordinates", "to", "CMYK", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L718-L745
xav/Grapefruit
grapefruit.py
rgb_to_cmy
def rgb_to_cmy(r, g=None, b=None): """Convert the color from RGB coordinates to CMY. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], m[0...1], y[0...1] >>> rgb_to_cmy(1, 0.5, 0) (0, 0.5, 1) """ if type(r) in [list,tuple]: r, g, b = r return (1-r, 1-g, 1-b)
python
def rgb_to_cmy(r, g=None, b=None): """Convert the color from RGB coordinates to CMY. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], m[0...1], y[0...1] >>> rgb_to_cmy(1, 0.5, 0) (0, 0.5, 1) """ if type(r) in [list,tuple]: r, g, b = r return (1-r, 1-g, 1-b)
[ "def", "rgb_to_cmy", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "return", "(", "1", "-", "r", ",", "1", "-", "g", ",", "1", "-", "b", ")" ]
Convert the color from RGB coordinates to CMY. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (c, m, y) tuple in the range: c[0...1], m[0...1], y[0...1] >>> rgb_to_cmy(1, 0.5, 0) (0, 0.5, 1)
[ "Convert", "the", "color", "from", "RGB", "coordinates", "to", "CMY", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L747-L770
xav/Grapefruit
grapefruit.py
cmy_to_rgb
def cmy_to_rgb(c, m=None, y=None): """Convert the color from CMY coordinates to RGB. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> cmy_to_rgb(0, 0.5, 1) (1, 0.5, 0) """ if type(c) in [list,tuple]: c, m, y = c return (1-c, 1-m, 1-y)
python
def cmy_to_rgb(c, m=None, y=None): """Convert the color from CMY coordinates to RGB. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> cmy_to_rgb(0, 0.5, 1) (1, 0.5, 0) """ if type(c) in [list,tuple]: c, m, y = c return (1-c, 1-m, 1-y)
[ "def", "cmy_to_rgb", "(", "c", ",", "m", "=", "None", ",", "y", "=", "None", ")", ":", "if", "type", "(", "c", ")", "in", "[", "list", ",", "tuple", "]", ":", "c", ",", "m", ",", "y", "=", "c", "return", "(", "1", "-", "c", ",", "1", "-", "m", ",", "1", "-", "y", ")" ]
Convert the color from CMY coordinates to RGB. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> cmy_to_rgb(0, 0.5, 1) (1, 0.5, 0)
[ "Convert", "the", "color", "from", "CMY", "coordinates", "to", "RGB", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L772-L795
xav/Grapefruit
grapefruit.py
rgb_to_ints
def rgb_to_ints(r, g=None, b=None): """Convert the color in the standard [0...1] range to ints in the [0..255] range. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...255], g[0...2551], b[0...2551] >>> rgb_to_ints(1, 0.5, 0) (255, 128, 0) """ if type(r) in [list,tuple]: r, g, b = r return tuple(int(round(v*255)) for v in (r, g, b))
python
def rgb_to_ints(r, g=None, b=None): """Convert the color in the standard [0...1] range to ints in the [0..255] range. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...255], g[0...2551], b[0...2551] >>> rgb_to_ints(1, 0.5, 0) (255, 128, 0) """ if type(r) in [list,tuple]: r, g, b = r return tuple(int(round(v*255)) for v in (r, g, b))
[ "def", "rgb_to_ints", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "return", "tuple", "(", "int", "(", "round", "(", "v", "*", "255", ")", ")", "for", "v", "in", "(", "r", ",", "g", ",", "b", ")", ")" ]
Convert the color in the standard [0...1] range to ints in the [0..255] range. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: r[0...255], g[0...2551], b[0...2551] >>> rgb_to_ints(1, 0.5, 0) (255, 128, 0)
[ "Convert", "the", "color", "in", "the", "standard", "[", "0", "...", "1", "]", "range", "to", "ints", "in", "the", "[", "0", "..", "255", "]", "range", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L797-L820
xav/Grapefruit
grapefruit.py
ints_to_rgb
def ints_to_rgb(r, g=None, b=None): """Convert ints in the [0...255] range to the standard [0...1] range. Parameters: :r: The Red component value [0...255] :g: The Green component value [0...255] :b: The Blue component value [0...255] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % ints_to_rgb((255, 128, 0)) '(1, 0.501961, 0)' """ if type(r) in [list,tuple]: r, g, b = r return tuple(float(v) / 255.0 for v in [r, g, b])
python
def ints_to_rgb(r, g=None, b=None): """Convert ints in the [0...255] range to the standard [0...1] range. Parameters: :r: The Red component value [0...255] :g: The Green component value [0...255] :b: The Blue component value [0...255] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % ints_to_rgb((255, 128, 0)) '(1, 0.501961, 0)' """ if type(r) in [list,tuple]: r, g, b = r return tuple(float(v) / 255.0 for v in [r, g, b])
[ "def", "ints_to_rgb", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "return", "tuple", "(", "float", "(", "v", ")", "/", "255.0", "for", "v", "in", "[", "r", ",", "g", ",", "b", "]", ")" ]
Convert ints in the [0...255] range to the standard [0...1] range. Parameters: :r: The Red component value [0...255] :g: The Green component value [0...255] :b: The Blue component value [0...255] Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % ints_to_rgb((255, 128, 0)) '(1, 0.501961, 0)'
[ "Convert", "ints", "in", "the", "[", "0", "...", "255", "]", "range", "to", "the", "standard", "[", "0", "...", "1", "]", "range", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L822-L845
xav/Grapefruit
grapefruit.py
rgb_to_html
def rgb_to_html(r, g=None, b=None): """Convert the color from (r, g, b) to #RRGGBB. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A CSS string representation of this color (#RRGGBB). >>> rgb_to_html(1, 0.5, 0) '#ff8000' """ if type(r) in [list,tuple]: r, g, b = r return '#%02x%02x%02x' % tuple((min(round(v*255), 255) for v in (r, g, b)))
python
def rgb_to_html(r, g=None, b=None): """Convert the color from (r, g, b) to #RRGGBB. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A CSS string representation of this color (#RRGGBB). >>> rgb_to_html(1, 0.5, 0) '#ff8000' """ if type(r) in [list,tuple]: r, g, b = r return '#%02x%02x%02x' % tuple((min(round(v*255), 255) for v in (r, g, b)))
[ "def", "rgb_to_html", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "return", "'#%02x%02x%02x'", "%", "tuple", "(", "(", "min", "(", "round", "(", "v", "*", "255", ")", ",", "255", ")", "for", "v", "in", "(", "r", ",", "g", ",", "b", ")", ")", ")" ]
Convert the color from (r, g, b) to #RRGGBB. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A CSS string representation of this color (#RRGGBB). >>> rgb_to_html(1, 0.5, 0) '#ff8000'
[ "Convert", "the", "color", "from", "(", "r", "g", "b", ")", "to", "#RRGGBB", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L847-L867
xav/Grapefruit
grapefruit.py
html_to_rgb
def html_to_rgb(html): """Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither a known color name or a hexadecimal RGB representation. >>> '(%g, %g, %g)' % html_to_rgb('#ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % html_to_rgb('ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % html_to_rgb('#f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % html_to_rgb('f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % html_to_rgb('lemonchiffon') '(1, 0.980392, 0.803922)' """ html = html.strip().lower() if html[0]=='#': html = html[1:] elif html in NAMED_COLOR: html = NAMED_COLOR[html][1:] if len(html)==6: rgb = html[:2], html[2:4], html[4:] elif len(html)==3: rgb = ['%c%c' % (v,v) for v in html] else: raise ValueError("input #%s is not in #RRGGBB format" % html) return tuple(((int(n, 16) / 255.0) for n in rgb))
python
def html_to_rgb(html): """Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither a known color name or a hexadecimal RGB representation. >>> '(%g, %g, %g)' % html_to_rgb('#ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % html_to_rgb('ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % html_to_rgb('#f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % html_to_rgb('f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % html_to_rgb('lemonchiffon') '(1, 0.980392, 0.803922)' """ html = html.strip().lower() if html[0]=='#': html = html[1:] elif html in NAMED_COLOR: html = NAMED_COLOR[html][1:] if len(html)==6: rgb = html[:2], html[2:4], html[4:] elif len(html)==3: rgb = ['%c%c' % (v,v) for v in html] else: raise ValueError("input #%s is not in #RRGGBB format" % html) return tuple(((int(n, 16) / 255.0) for n in rgb))
[ "def", "html_to_rgb", "(", "html", ")", ":", "html", "=", "html", ".", "strip", "(", ")", ".", "lower", "(", ")", "if", "html", "[", "0", "]", "==", "'#'", ":", "html", "=", "html", "[", "1", ":", "]", "elif", "html", "in", "NAMED_COLOR", ":", "html", "=", "NAMED_COLOR", "[", "html", "]", "[", "1", ":", "]", "if", "len", "(", "html", ")", "==", "6", ":", "rgb", "=", "html", "[", ":", "2", "]", ",", "html", "[", "2", ":", "4", "]", ",", "html", "[", "4", ":", "]", "elif", "len", "(", "html", ")", "==", "3", ":", "rgb", "=", "[", "'%c%c'", "%", "(", "v", ",", "v", ")", "for", "v", "in", "html", "]", "else", ":", "raise", "ValueError", "(", "\"input #%s is not in #RRGGBB format\"", "%", "html", ")", "return", "tuple", "(", "(", "(", "int", "(", "n", ",", "16", ")", "/", "255.0", ")", "for", "n", "in", "rgb", ")", ")" ]
Convert the HTML color to (r, g, b). Parameters: :html: the HTML definition of the color (#RRGGBB or #RGB or a color name). Returns: The color as an (r, g, b) tuple in the range: r[0...1], g[0...1], b[0...1] Throws: :ValueError: If html is neither a known color name or a hexadecimal RGB representation. >>> '(%g, %g, %g)' % html_to_rgb('#ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % html_to_rgb('ff8000') '(1, 0.501961, 0)' >>> '(%g, %g, %g)' % html_to_rgb('#f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % html_to_rgb('f60') '(1, 0.4, 0)' >>> '(%g, %g, %g)' % html_to_rgb('lemonchiffon') '(1, 0.980392, 0.803922)'
[ "Convert", "the", "HTML", "color", "to", "(", "r", "g", "b", ")", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L869-L912
xav/Grapefruit
grapefruit.py
rgb_to_pil
def rgb_to_pil(r, g=None, b=None): """Convert the color from RGB to a PIL-compatible integer. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A PIL compatible integer (0xBBGGRR). >>> '0x%06x' % rgb_to_pil(1, 0.5, 0) '0x0080ff' """ if type(r) in [list,tuple]: r, g, b = r r, g, b = [min(int(round(v*255)), 255) for v in (r, g, b)] return (b << 16) + (g << 8) + r
python
def rgb_to_pil(r, g=None, b=None): """Convert the color from RGB to a PIL-compatible integer. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A PIL compatible integer (0xBBGGRR). >>> '0x%06x' % rgb_to_pil(1, 0.5, 0) '0x0080ff' """ if type(r) in [list,tuple]: r, g, b = r r, g, b = [min(int(round(v*255)), 255) for v in (r, g, b)] return (b << 16) + (g << 8) + r
[ "def", "rgb_to_pil", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "r", ",", "g", ",", "b", "=", "[", "min", "(", "int", "(", "round", "(", "v", "*", "255", ")", ")", ",", "255", ")", "for", "v", "in", "(", "r", ",", "g", ",", "b", ")", "]", "return", "(", "b", "<<", "16", ")", "+", "(", "g", "<<", "8", ")", "+", "r" ]
Convert the color from RGB to a PIL-compatible integer. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: A PIL compatible integer (0xBBGGRR). >>> '0x%06x' % rgb_to_pil(1, 0.5, 0) '0x0080ff'
[ "Convert", "the", "color", "from", "RGB", "to", "a", "PIL", "-", "compatible", "integer", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L914-L935
xav/Grapefruit
grapefruit.py
pil_to_rgb
def pil_to_rgb(pil): """Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] b: [0...1] >>> '(%g, %g, %g)' % pil_to_rgb(0x0080ff) '(1, 0.501961, 0)' """ r = 0xff & pil g = 0xff & (pil >> 8) b = 0xff & (pil >> 16) return tuple((v / 255.0 for v in (r, g, b)))
python
def pil_to_rgb(pil): """Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] b: [0...1] >>> '(%g, %g, %g)' % pil_to_rgb(0x0080ff) '(1, 0.501961, 0)' """ r = 0xff & pil g = 0xff & (pil >> 8) b = 0xff & (pil >> 16) return tuple((v / 255.0 for v in (r, g, b)))
[ "def", "pil_to_rgb", "(", "pil", ")", ":", "r", "=", "0xff", "&", "pil", "g", "=", "0xff", "&", "(", "pil", ">>", "8", ")", "b", "=", "0xff", "&", "(", "pil", ">>", "16", ")", "return", "tuple", "(", "(", "v", "/", "255.0", "for", "v", "in", "(", "r", ",", "g", ",", "b", ")", ")", ")" ]
Convert the color from a PIL-compatible integer to RGB. Parameters: pil: a PIL compatible color representation (0xBBGGRR) Returns: The color as an (r, g, b) tuple in the range: the range: r: [0...1] g: [0...1] b: [0...1] >>> '(%g, %g, %g)' % pil_to_rgb(0x0080ff) '(1, 0.501961, 0)'
[ "Convert", "the", "color", "from", "a", "PIL", "-", "compatible", "integer", "to", "RGB", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L937-L956
xav/Grapefruit
grapefruit.py
_websafe_component
def _websafe_component(c, alt=False): """Convert a color component to its web safe equivalent. Parameters: :c: The component value [0...1] :alt: If True, return the alternative value instead of the nearest one. Returns: The web safe equivalent of the component value. """ # This sucks, but floating point between 0 and 1 is quite fuzzy... # So we just change the scale a while to make the equality tests # work, otherwise it gets wrong at some decimal far to the right. sc = c * 100.0 # If the color is already safe, return it straight away d = sc % 20 if d==0: return c # Get the lower and upper safe values l = sc - d u = l + 20 # Return the 'closest' value according to the alt flag if alt: if (sc-l) >= (u-sc): return l/100.0 else: return u/100.0 else: if (sc-l) >= (u-sc): return u/100.0 else: return l/100.0
python
def _websafe_component(c, alt=False): """Convert a color component to its web safe equivalent. Parameters: :c: The component value [0...1] :alt: If True, return the alternative value instead of the nearest one. Returns: The web safe equivalent of the component value. """ # This sucks, but floating point between 0 and 1 is quite fuzzy... # So we just change the scale a while to make the equality tests # work, otherwise it gets wrong at some decimal far to the right. sc = c * 100.0 # If the color is already safe, return it straight away d = sc % 20 if d==0: return c # Get the lower and upper safe values l = sc - d u = l + 20 # Return the 'closest' value according to the alt flag if alt: if (sc-l) >= (u-sc): return l/100.0 else: return u/100.0 else: if (sc-l) >= (u-sc): return u/100.0 else: return l/100.0
[ "def", "_websafe_component", "(", "c", ",", "alt", "=", "False", ")", ":", "# This sucks, but floating point between 0 and 1 is quite fuzzy...", "# So we just change the scale a while to make the equality tests", "# work, otherwise it gets wrong at some decimal far to the right.", "sc", "=", "c", "*", "100.0", "# If the color is already safe, return it straight away", "d", "=", "sc", "%", "20", "if", "d", "==", "0", ":", "return", "c", "# Get the lower and upper safe values", "l", "=", "sc", "-", "d", "u", "=", "l", "+", "20", "# Return the 'closest' value according to the alt flag", "if", "alt", ":", "if", "(", "sc", "-", "l", ")", ">=", "(", "u", "-", "sc", ")", ":", "return", "l", "/", "100.0", "else", ":", "return", "u", "/", "100.0", "else", ":", "if", "(", "sc", "-", "l", ")", ">=", "(", "u", "-", "sc", ")", ":", "return", "u", "/", "100.0", "else", ":", "return", "l", "/", "100.0" ]
Convert a color component to its web safe equivalent. Parameters: :c: The component value [0...1] :alt: If True, return the alternative value instead of the nearest one. Returns: The web safe equivalent of the component value.
[ "Convert", "a", "color", "component", "to", "its", "web", "safe", "equivalent", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L958-L990
xav/Grapefruit
grapefruit.py
rgb_to_websafe
def rgb_to_websafe(r, g=None, b=None, alt=False): """Convert the color from RGB to 'web safe' RGB Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alt: If True, use the alternative color instead of the nearest one. Can be used for dithering. Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % rgb_to_websafe(1, 0.55, 0.0) '(1, 0.6, 0)' """ if type(r) in [list,tuple]: r, g, b = r websafeComponent = _websafe_component return tuple((websafeComponent(v, alt) for v in (r, g, b)))
python
def rgb_to_websafe(r, g=None, b=None, alt=False): """Convert the color from RGB to 'web safe' RGB Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alt: If True, use the alternative color instead of the nearest one. Can be used for dithering. Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % rgb_to_websafe(1, 0.55, 0.0) '(1, 0.6, 0)' """ if type(r) in [list,tuple]: r, g, b = r websafeComponent = _websafe_component return tuple((websafeComponent(v, alt) for v in (r, g, b)))
[ "def", "rgb_to_websafe", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ",", "alt", "=", "False", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "websafeComponent", "=", "_websafe_component", "return", "tuple", "(", "(", "websafeComponent", "(", "v", ",", "alt", ")", "for", "v", "in", "(", "r", ",", "g", ",", "b", ")", ")", ")" ]
Convert the color from RGB to 'web safe' RGB Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alt: If True, use the alternative color instead of the nearest one. Can be used for dithering. Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % rgb_to_websafe(1, 0.55, 0.0) '(1, 0.6, 0)'
[ "Convert", "the", "color", "from", "RGB", "to", "web", "safe", "RGB" ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L992-L1020
xav/Grapefruit
grapefruit.py
rgb_to_greyscale
def rgb_to_greyscale(r, g=None, b=None): """Convert the color from RGB to its greyscale equivalent Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % rgb_to_greyscale(1, 0.8, 0) '(0.6, 0.6, 0.6)' """ if type(r) in [list,tuple]: r, g, b = r v = (r + g + b) / 3.0 return (v, v, v)
python
def rgb_to_greyscale(r, g=None, b=None): """Convert the color from RGB to its greyscale equivalent Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % rgb_to_greyscale(1, 0.8, 0) '(0.6, 0.6, 0.6)' """ if type(r) in [list,tuple]: r, g, b = r v = (r + g + b) / 3.0 return (v, v, v)
[ "def", "rgb_to_greyscale", "(", "r", ",", "g", "=", "None", ",", "b", "=", "None", ")", ":", "if", "type", "(", "r", ")", "in", "[", "list", ",", "tuple", "]", ":", "r", ",", "g", ",", "b", "=", "r", "v", "=", "(", "r", "+", "g", "+", "b", ")", "/", "3.0", "return", "(", "v", ",", "v", ",", "v", ")" ]
Convert the color from RGB to its greyscale equivalent Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] Returns: The color as an (r, g, b) tuple in the range: the range: r[0...1], g[0...1], b[0...1] >>> '(%g, %g, %g)' % rgb_to_greyscale(1, 0.8, 0) '(0.6, 0.6, 0.6)'
[ "Convert", "the", "color", "from", "RGB", "to", "its", "greyscale", "equivalent" ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1022-L1047
xav/Grapefruit
grapefruit.py
rgb_to_ryb
def rgb_to_ryb(hue): """Maps a hue on the RGB color wheel to Itten's RYB wheel. Parameters: :hue: The hue on the RGB color wheel [0...360] Returns: An approximation of the corresponding hue on Itten's RYB wheel. >>> rgb_to_ryb(15) 26.0 """ d = hue % 15 i = int(hue / 15) x0 = _RybWheel[i] x1 = _RybWheel[i+1] return x0 + (x1-x0) * d / 15
python
def rgb_to_ryb(hue): """Maps a hue on the RGB color wheel to Itten's RYB wheel. Parameters: :hue: The hue on the RGB color wheel [0...360] Returns: An approximation of the corresponding hue on Itten's RYB wheel. >>> rgb_to_ryb(15) 26.0 """ d = hue % 15 i = int(hue / 15) x0 = _RybWheel[i] x1 = _RybWheel[i+1] return x0 + (x1-x0) * d / 15
[ "def", "rgb_to_ryb", "(", "hue", ")", ":", "d", "=", "hue", "%", "15", "i", "=", "int", "(", "hue", "/", "15", ")", "x0", "=", "_RybWheel", "[", "i", "]", "x1", "=", "_RybWheel", "[", "i", "+", "1", "]", "return", "x0", "+", "(", "x1", "-", "x0", ")", "*", "d", "/", "15" ]
Maps a hue on the RGB color wheel to Itten's RYB wheel. Parameters: :hue: The hue on the RGB color wheel [0...360] Returns: An approximation of the corresponding hue on Itten's RYB wheel. >>> rgb_to_ryb(15) 26.0
[ "Maps", "a", "hue", "on", "the", "RGB", "color", "wheel", "to", "Itten", "s", "RYB", "wheel", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1049-L1067
xav/Grapefruit
grapefruit.py
ryb_to_rgb
def ryb_to_rgb(hue): """Maps a hue on Itten's RYB color wheel to the standard RGB wheel. Parameters: :hue: The hue on Itten's RYB color wheel [0...360] Returns: An approximation of the corresponding hue on the standard RGB wheel. >>> ryb_to_rgb(15) 8.0 """ d = hue % 15 i = int(hue / 15) x0 = _RgbWheel[i] x1 = _RgbWheel[i+1] return x0 + (x1-x0) * d / 15
python
def ryb_to_rgb(hue): """Maps a hue on Itten's RYB color wheel to the standard RGB wheel. Parameters: :hue: The hue on Itten's RYB color wheel [0...360] Returns: An approximation of the corresponding hue on the standard RGB wheel. >>> ryb_to_rgb(15) 8.0 """ d = hue % 15 i = int(hue / 15) x0 = _RgbWheel[i] x1 = _RgbWheel[i+1] return x0 + (x1-x0) * d / 15
[ "def", "ryb_to_rgb", "(", "hue", ")", ":", "d", "=", "hue", "%", "15", "i", "=", "int", "(", "hue", "/", "15", ")", "x0", "=", "_RgbWheel", "[", "i", "]", "x1", "=", "_RgbWheel", "[", "i", "+", "1", "]", "return", "x0", "+", "(", "x1", "-", "x0", ")", "*", "d", "/", "15" ]
Maps a hue on Itten's RYB color wheel to the standard RGB wheel. Parameters: :hue: The hue on Itten's RYB color wheel [0...360] Returns: An approximation of the corresponding hue on the standard RGB wheel. >>> ryb_to_rgb(15) 8.0
[ "Maps", "a", "hue", "on", "Itten", "s", "RYB", "color", "wheel", "to", "the", "standard", "RGB", "wheel", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1069-L1087
xav/Grapefruit
grapefruit.py
Color.from_rgb
def from_rgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_rgb(1.0, 0.5, 0.0) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_rgb(1.0, 0.5, 0.0, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ return Color((r, g, b), 'rgb', alpha, wref)
python
def from_rgb(r, g, b, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_rgb(1.0, 0.5, 0.0) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_rgb(1.0, 0.5, 0.0, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ return Color((r, g, b), 'rgb', alpha, wref)
[ "def", "from_rgb", "(", "r", ",", "g", ",", "b", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "(", "r", ",", "g", ",", "b", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed RGB values. Parameters: :r: The Red component value [0...1] :g: The Green component value [0...1] :b: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_rgb(1.0, 0.5, 0.0) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_rgb(1.0, 0.5, 0.0, 0.5) Color(1.0, 0.5, 0.0, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "RGB", "values", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1123-L1147
xav/Grapefruit
grapefruit.py
Color.from_hsl
def from_hsl(h, s, l, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HSL values. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 1, 0.5) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_hsl(30, 1, 0.5, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ return Color((h, s, l), 'hsl', alpha, wref)
python
def from_hsl(h, s, l, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HSL values. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 1, 0.5) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_hsl(30, 1, 0.5, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ return Color((h, s, l), 'hsl', alpha, wref)
[ "def", "from_hsl", "(", "h", ",", "s", ",", "l", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "(", "h", ",", "s", ",", "l", ")", ",", "'hsl'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed HSL values. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 1, 0.5) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_hsl(30, 1, 0.5, 0.5) Color(1.0, 0.5, 0.0, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "HSL", "values", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1150-L1174
xav/Grapefruit
grapefruit.py
Color.from_hsv
def from_hsv(h, s, v, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HSV values. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_hsv(30, 1, 1) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_hsv(30, 1, 1, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ h2, s, l = rgb_to_hsl(*hsv_to_rgb(h, s, v)) return Color((h, s, l), 'hsl', alpha, wref)
python
def from_hsv(h, s, v, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HSV values. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_hsv(30, 1, 1) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_hsv(30, 1, 1, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ h2, s, l = rgb_to_hsl(*hsv_to_rgb(h, s, v)) return Color((h, s, l), 'hsl', alpha, wref)
[ "def", "from_hsv", "(", "h", ",", "s", ",", "v", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "h2", ",", "s", ",", "l", "=", "rgb_to_hsl", "(", "*", "hsv_to_rgb", "(", "h", ",", "s", ",", "v", ")", ")", "return", "Color", "(", "(", "h", ",", "s", ",", "l", ")", ",", "'hsl'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed HSV values. Parameters: :h: The Hus component value [0...1] :s: The Saturation component value [0...1] :v: The Value component [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_hsv(30, 1, 1) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_hsv(30, 1, 1, 0.5) Color(1.0, 0.5, 0.0, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "HSV", "values", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1177-L1202
xav/Grapefruit
grapefruit.py
Color.from_yiq
def from_yiq(y, i, q, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed YIQ values. Parameters: :y: The Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_yiq(0.5922, 0.45885,-0.05) Color(0.999902, 0.499955, -6.7e-05, 1.0) >>> Color.from_yiq(0.5922, 0.45885,-0.05, 0.5) Color(0.999902, 0.499955, -6.7e-05, 0.5) """ return Color(yiq_to_rgb(y, i, q), 'rgb', alpha, wref)
python
def from_yiq(y, i, q, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed YIQ values. Parameters: :y: The Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_yiq(0.5922, 0.45885,-0.05) Color(0.999902, 0.499955, -6.7e-05, 1.0) >>> Color.from_yiq(0.5922, 0.45885,-0.05, 0.5) Color(0.999902, 0.499955, -6.7e-05, 0.5) """ return Color(yiq_to_rgb(y, i, q), 'rgb', alpha, wref)
[ "def", "from_yiq", "(", "y", ",", "i", ",", "q", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "yiq_to_rgb", "(", "y", ",", "i", ",", "q", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed YIQ values. Parameters: :y: The Y component value [0...1] :i: The I component value [0...1] :q: The Q component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_yiq(0.5922, 0.45885,-0.05) Color(0.999902, 0.499955, -6.7e-05, 1.0) >>> Color.from_yiq(0.5922, 0.45885,-0.05, 0.5) Color(0.999902, 0.499955, -6.7e-05, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "YIQ", "values", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1205-L1229
xav/Grapefruit
grapefruit.py
Color.from_yuv
def from_yuv(y, u, v, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed YUV values. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_yuv(0.5925, -0.2916, 0.3575) Color(0.999989, 0.500015, -6.3e-05, 1.0) >>> Color.from_yuv(0.5925, -0.2916, 0.3575, 0.5) Color(0.999989, 0.500015, -6.3e-05, 0.5) """ return Color(yuv_to_rgb(y, u, v), 'rgb', alpha, wref)
python
def from_yuv(y, u, v, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed YUV values. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_yuv(0.5925, -0.2916, 0.3575) Color(0.999989, 0.500015, -6.3e-05, 1.0) >>> Color.from_yuv(0.5925, -0.2916, 0.3575, 0.5) Color(0.999989, 0.500015, -6.3e-05, 0.5) """ return Color(yuv_to_rgb(y, u, v), 'rgb', alpha, wref)
[ "def", "from_yuv", "(", "y", ",", "u", ",", "v", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "yuv_to_rgb", "(", "y", ",", "u", ",", "v", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed YUV values. Parameters: :y: The Y component value [0...1] :u: The U component value [-0.436...0.436] :v: The V component value [-0.615...0.615] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_yuv(0.5925, -0.2916, 0.3575) Color(0.999989, 0.500015, -6.3e-05, 1.0) >>> Color.from_yuv(0.5925, -0.2916, 0.3575, 0.5) Color(0.999989, 0.500015, -6.3e-05, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "YUV", "values", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1232-L1256
xav/Grapefruit
grapefruit.py
Color.from_xyz
def from_xyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_xyz(0.488941, 0.365682, 0.0448137) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_xyz(0.488941, 0.365682, 0.0448137, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ return Color(xyz_to_rgb(x, y, z), 'rgb', alpha, wref)
python
def from_xyz(x, y, z, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_xyz(0.488941, 0.365682, 0.0448137) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_xyz(0.488941, 0.365682, 0.0448137, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ return Color(xyz_to_rgb(x, y, z), 'rgb', alpha, wref)
[ "def", "from_xyz", "(", "x", ",", "y", ",", "z", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "xyz_to_rgb", "(", "x", ",", "y", ",", "z", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed CIE-XYZ values. Parameters: :x: The Red component value [0...1] :y: The Green component value [0...1] :z: The Blue component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_xyz(0.488941, 0.365682, 0.0448137) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_xyz(0.488941, 0.365682, 0.0448137, 0.5) Color(1.0, 0.5, 0.0, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "CIE", "-", "XYZ", "values", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1259-L1283
xav/Grapefruit
grapefruit.py
Color.from_lab
def from_lab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_lab(66.951823, 0.43084105, 0.73969231) Color(1.0, 0.5, -0.0, 1.0) >>> Color.from_lab(66.951823, 0.41165967, 0.67282012, wref=WHITE_REFERENCE['std_D50']) Color(1.0, 0.5, -0.0, 1.0) >>> Color.from_lab(66.951823, 0.43084105, 0.73969231, 0.5) Color(1.0, 0.5, -0.0, 0.5) >>> Color.from_lab(66.951823, 0.41165967, 0.67282012, 0.5, WHITE_REFERENCE['std_D50']) Color(1.0, 0.5, -0.0, 0.5) """ return Color(xyz_to_rgb(*lab_to_xyz(l, a, b, wref)), 'rgb', alpha, wref)
python
def from_lab(l, a, b, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_lab(66.951823, 0.43084105, 0.73969231) Color(1.0, 0.5, -0.0, 1.0) >>> Color.from_lab(66.951823, 0.41165967, 0.67282012, wref=WHITE_REFERENCE['std_D50']) Color(1.0, 0.5, -0.0, 1.0) >>> Color.from_lab(66.951823, 0.43084105, 0.73969231, 0.5) Color(1.0, 0.5, -0.0, 0.5) >>> Color.from_lab(66.951823, 0.41165967, 0.67282012, 0.5, WHITE_REFERENCE['std_D50']) Color(1.0, 0.5, -0.0, 0.5) """ return Color(xyz_to_rgb(*lab_to_xyz(l, a, b, wref)), 'rgb', alpha, wref)
[ "def", "from_lab", "(", "l", ",", "a", ",", "b", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "xyz_to_rgb", "(", "*", "lab_to_xyz", "(", "l", ",", "a", ",", "b", ",", "wref", ")", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed CIE-LAB values. Parameters: :l: The L component [0...100] :a: The a component [-1...1] :b: The a component [-1...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_lab(66.951823, 0.43084105, 0.73969231) Color(1.0, 0.5, -0.0, 1.0) >>> Color.from_lab(66.951823, 0.41165967, 0.67282012, wref=WHITE_REFERENCE['std_D50']) Color(1.0, 0.5, -0.0, 1.0) >>> Color.from_lab(66.951823, 0.43084105, 0.73969231, 0.5) Color(1.0, 0.5, -0.0, 0.5) >>> Color.from_lab(66.951823, 0.41165967, 0.67282012, 0.5, WHITE_REFERENCE['std_D50']) Color(1.0, 0.5, -0.0, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "CIE", "-", "LAB", "values", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1286-L1314
xav/Grapefruit
grapefruit.py
Color.from_cmy
def from_cmy(c, m, y, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CMY values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_cmy(0, 0.5, 1) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_cmy(0, 0.5, 1, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ return Color(cmy_to_rgb(c, m, y), 'rgb', alpha, wref)
python
def from_cmy(c, m, y, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CMY values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_cmy(0, 0.5, 1) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_cmy(0, 0.5, 1, 0.5) Color(1.0, 0.5, 0.0, 0.5) """ return Color(cmy_to_rgb(c, m, y), 'rgb', alpha, wref)
[ "def", "from_cmy", "(", "c", ",", "m", ",", "y", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "cmy_to_rgb", "(", "c", ",", "m", ",", "y", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed CMY values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_cmy(0, 0.5, 1) Color(1.0, 0.5, 0.0, 1.0) >>> Color.from_cmy(0, 0.5, 1, 0.5) Color(1.0, 0.5, 0.0, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "CMY", "values", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1317-L1341
xav/Grapefruit
grapefruit.py
Color.from_cmyk
def from_cmyk(c, m, y, k, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CMYK values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_cmyk(1, 0.32, 0, 0.5) Color(0.0, 0.34, 0.5, 1.0) >>> Color.from_cmyk(1, 0.32, 0, 0.5, 0.5) Color(0.0, 0.34, 0.5, 0.5) """ return Color(cmy_to_rgb(*cmyk_to_cmy(c, m, y, k)), 'rgb', alpha, wref)
python
def from_cmyk(c, m, y, k, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed CMYK values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_cmyk(1, 0.32, 0, 0.5) Color(0.0, 0.34, 0.5, 1.0) >>> Color.from_cmyk(1, 0.32, 0, 0.5, 0.5) Color(0.0, 0.34, 0.5, 0.5) """ return Color(cmy_to_rgb(*cmyk_to_cmy(c, m, y, k)), 'rgb', alpha, wref)
[ "def", "from_cmyk", "(", "c", ",", "m", ",", "y", ",", "k", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "cmy_to_rgb", "(", "*", "cmyk_to_cmy", "(", "c", ",", "m", ",", "y", ",", "k", ")", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed CMYK values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The Black component value [0...1] :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_cmyk(1, 0.32, 0, 0.5) Color(0.0, 0.34, 0.5, 1.0) >>> Color.from_cmyk(1, 0.32, 0, 0.5, 0.5) Color(0.0, 0.34, 0.5, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "CMYK", "values", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1344-L1370
xav/Grapefruit
grapefruit.py
Color.from_html
def from_html(html, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HTML color definition. Parameters: :html: The HTML definition of the color (#RRGGBB or #RGB or a color name). :alpha: The color transparency [0...1], default is opaque. :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_html('#ff8000') Color(1.0, 0.501961, 0.0, 1.0) >>> Color.from_html('ff8000') Color(1.0, 0.501961, 0.0, 1.0) >>> Color.from_html('#f60') Color(1.0, 0.4, 0.0, 1.0) >>> Color.from_html('f60') Color(1.0, 0.4, 0.0, 1.0) >>> Color.from_html('lemonchiffon') Color(1.0, 0.980392, 0.803922, 1.0) >>> Color.from_html('#ff8000', 0.5) Color(1.0, 0.501961, 0.0, 0.5) """ return Color(html_to_rgb(html), 'rgb', alpha, wref)
python
def from_html(html, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed HTML color definition. Parameters: :html: The HTML definition of the color (#RRGGBB or #RGB or a color name). :alpha: The color transparency [0...1], default is opaque. :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_html('#ff8000') Color(1.0, 0.501961, 0.0, 1.0) >>> Color.from_html('ff8000') Color(1.0, 0.501961, 0.0, 1.0) >>> Color.from_html('#f60') Color(1.0, 0.4, 0.0, 1.0) >>> Color.from_html('f60') Color(1.0, 0.4, 0.0, 1.0) >>> Color.from_html('lemonchiffon') Color(1.0, 0.980392, 0.803922, 1.0) >>> Color.from_html('#ff8000', 0.5) Color(1.0, 0.501961, 0.0, 0.5) """ return Color(html_to_rgb(html), 'rgb', alpha, wref)
[ "def", "from_html", "(", "html", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "html_to_rgb", "(", "html", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed HTML color definition. Parameters: :html: The HTML definition of the color (#RRGGBB or #RGB or a color name). :alpha: The color transparency [0...1], default is opaque. :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_html('#ff8000') Color(1.0, 0.501961, 0.0, 1.0) >>> Color.from_html('ff8000') Color(1.0, 0.501961, 0.0, 1.0) >>> Color.from_html('#f60') Color(1.0, 0.4, 0.0, 1.0) >>> Color.from_html('f60') Color(1.0, 0.4, 0.0, 1.0) >>> Color.from_html('lemonchiffon') Color(1.0, 0.980392, 0.803922, 1.0) >>> Color.from_html('#ff8000', 0.5) Color(1.0, 0.501961, 0.0, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "HTML", "color", "definition", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1373-L1401
xav/Grapefruit
grapefruit.py
Color.from_pil
def from_pil(pil, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed PIL color. Parameters: :pil: A PIL compatible color representation (0xBBGGRR) :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_pil(0x0080ff) Color(1.0, 0.501961, 0.0, 1.0) >>> Color.from_pil(0x0080ff, 0.5) Color(1.0, 0.501961, 0.0, 0.5) """ return Color(pil_to_rgb(pil), 'rgb', alpha, wref)
python
def from_pil(pil, alpha=1.0, wref=_DEFAULT_WREF): """Create a new instance based on the specifed PIL color. Parameters: :pil: A PIL compatible color representation (0xBBGGRR) :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_pil(0x0080ff) Color(1.0, 0.501961, 0.0, 1.0) >>> Color.from_pil(0x0080ff, 0.5) Color(1.0, 0.501961, 0.0, 0.5) """ return Color(pil_to_rgb(pil), 'rgb', alpha, wref)
[ "def", "from_pil", "(", "pil", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "pil_to_rgb", "(", "pil", ")", ",", "'rgb'", ",", "alpha", ",", "wref", ")" ]
Create a new instance based on the specifed PIL color. Parameters: :pil: A PIL compatible color representation (0xBBGGRR) :alpha: The color transparency [0...1], default is opaque :wref: The whitepoint reference, default is 2° D65. Returns: A grapefruit.Color instance. >>> Color.from_pil(0x0080ff) Color(1.0, 0.501961, 0.0, 1.0) >>> Color.from_pil(0x0080ff, 0.5) Color(1.0, 0.501961, 0.0, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "the", "specifed", "PIL", "color", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1404-L1424
xav/Grapefruit
grapefruit.py
Color.with_white_ref
def with_white_ref(self, wref, labAsRef=False): """Create a new instance based on this one with a new white reference. Parameters: :wref: The whitepoint reference. :labAsRef: If True, the L*a*b* values of the current instance are used as reference for the new color; otherwise, the RGB values are used as reference. Returns: A grapefruit.Color instance. >>> c = Color.from_rgb(1.0, 0.5, 0.0, 1.0, WHITE_REFERENCE['std_D65']) >>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50']) >>> c2.rgb (1.0, 0.5, 0.0) >>> '(%g, %g, %g)' % c2.white_ref '(0.967206, 1, 0.81428)' >>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50'], labAsRef=True) >>> '(%g, %g, %g)' % c2.rgb '(1.01463, 0.490341, -0.148133)' >>> '(%g, %g, %g)' % c2.white_ref '(0.967206, 1, 0.81428)' >>> '(%g, %g, %g)' % c.lab '(66.9518, 0.430841, 0.739692)' >>> '(%g, %g, %g)' % c2.lab '(66.9518, 0.430841, 0.739693)' """ if labAsRef: l, a, b = self.lab return Color.from_lab(l, a, b, self.__a, wref) else: return Color(self.__rgb, 'rgb', self.__a, wref)
python
def with_white_ref(self, wref, labAsRef=False): """Create a new instance based on this one with a new white reference. Parameters: :wref: The whitepoint reference. :labAsRef: If True, the L*a*b* values of the current instance are used as reference for the new color; otherwise, the RGB values are used as reference. Returns: A grapefruit.Color instance. >>> c = Color.from_rgb(1.0, 0.5, 0.0, 1.0, WHITE_REFERENCE['std_D65']) >>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50']) >>> c2.rgb (1.0, 0.5, 0.0) >>> '(%g, %g, %g)' % c2.white_ref '(0.967206, 1, 0.81428)' >>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50'], labAsRef=True) >>> '(%g, %g, %g)' % c2.rgb '(1.01463, 0.490341, -0.148133)' >>> '(%g, %g, %g)' % c2.white_ref '(0.967206, 1, 0.81428)' >>> '(%g, %g, %g)' % c.lab '(66.9518, 0.430841, 0.739692)' >>> '(%g, %g, %g)' % c2.lab '(66.9518, 0.430841, 0.739693)' """ if labAsRef: l, a, b = self.lab return Color.from_lab(l, a, b, self.__a, wref) else: return Color(self.__rgb, 'rgb', self.__a, wref)
[ "def", "with_white_ref", "(", "self", ",", "wref", ",", "labAsRef", "=", "False", ")", ":", "if", "labAsRef", ":", "l", ",", "a", ",", "b", "=", "self", ".", "lab", "return", "Color", ".", "from_lab", "(", "l", ",", "a", ",", "b", ",", "self", ".", "__a", ",", "wref", ")", "else", ":", "return", "Color", "(", "self", ".", "__rgb", ",", "'rgb'", ",", "self", ".", "__a", ",", "wref", ")" ]
Create a new instance based on this one with a new white reference. Parameters: :wref: The whitepoint reference. :labAsRef: If True, the L*a*b* values of the current instance are used as reference for the new color; otherwise, the RGB values are used as reference. Returns: A grapefruit.Color instance. >>> c = Color.from_rgb(1.0, 0.5, 0.0, 1.0, WHITE_REFERENCE['std_D65']) >>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50']) >>> c2.rgb (1.0, 0.5, 0.0) >>> '(%g, %g, %g)' % c2.white_ref '(0.967206, 1, 0.81428)' >>> c2 = c.with_white_ref(WHITE_REFERENCE['sup_D50'], labAsRef=True) >>> '(%g, %g, %g)' % c2.rgb '(1.01463, 0.490341, -0.148133)' >>> '(%g, %g, %g)' % c2.white_ref '(0.967206, 1, 0.81428)' >>> '(%g, %g, %g)' % c.lab '(66.9518, 0.430841, 0.739692)' >>> '(%g, %g, %g)' % c2.lab '(66.9518, 0.430841, 0.739693)'
[ "Create", "a", "new", "instance", "based", "on", "this", "one", "with", "a", "new", "white", "reference", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1707-L1744
xav/Grapefruit
grapefruit.py
Color.desaturate
def desaturate(self, level): """Create a new instance based on this one but less saturated. Parameters: :level: The amount by which the color should be desaturated to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25) Color(0.625, 0.5, 0.375, 1.0) >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25).hsl (30.0, 0.25, 0.5) """ h, s, l = self.__hsl return Color((h, max(s - level, 0), l), 'hsl', self.__a, self.__wref)
python
def desaturate(self, level): """Create a new instance based on this one but less saturated. Parameters: :level: The amount by which the color should be desaturated to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25) Color(0.625, 0.5, 0.375, 1.0) >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25).hsl (30.0, 0.25, 0.5) """ h, s, l = self.__hsl return Color((h, max(s - level, 0), l), 'hsl', self.__a, self.__wref)
[ "def", "desaturate", "(", "self", ",", "level", ")", ":", "h", ",", "s", ",", "l", "=", "self", ".", "__hsl", "return", "Color", "(", "(", "h", ",", "max", "(", "s", "-", "level", ",", "0", ")", ",", "l", ")", ",", "'hsl'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")" ]
Create a new instance based on this one but less saturated. Parameters: :level: The amount by which the color should be desaturated to produce the new one [0...1]. Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25) Color(0.625, 0.5, 0.375, 1.0) >>> Color.from_hsl(30, 0.5, 0.5).desaturate(0.25).hsl (30.0, 0.25, 0.5)
[ "Create", "a", "new", "instance", "based", "on", "this", "one", "but", "less", "saturated", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1867-L1885
xav/Grapefruit
grapefruit.py
Color.websafe_dither
def websafe_dither(self): """Return the two websafe colors nearest to this one. Returns: A tuple of two grapefruit.Color instances which are the two web safe colors closest this one. >>> c = Color.from_rgb(1.0, 0.45, 0.0) >>> c1, c2 = c.websafe_dither() >>> c1 Color(1.0, 0.4, 0.0, 1.0) >>> c2 Color(1.0, 0.6, 0.0, 1.0) """ return ( Color(rgb_to_websafe(*self.__rgb), 'rgb', self.__a, self.__wref), Color(rgb_to_websafe(alt=True, *self.__rgb), 'rgb', self.__a, self.__wref))
python
def websafe_dither(self): """Return the two websafe colors nearest to this one. Returns: A tuple of two grapefruit.Color instances which are the two web safe colors closest this one. >>> c = Color.from_rgb(1.0, 0.45, 0.0) >>> c1, c2 = c.websafe_dither() >>> c1 Color(1.0, 0.4, 0.0, 1.0) >>> c2 Color(1.0, 0.6, 0.0, 1.0) """ return ( Color(rgb_to_websafe(*self.__rgb), 'rgb', self.__a, self.__wref), Color(rgb_to_websafe(alt=True, *self.__rgb), 'rgb', self.__a, self.__wref))
[ "def", "websafe_dither", "(", "self", ")", ":", "return", "(", "Color", "(", "rgb_to_websafe", "(", "*", "self", ".", "__rgb", ")", ",", "'rgb'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")", ",", "Color", "(", "rgb_to_websafe", "(", "alt", "=", "True", ",", "*", "self", ".", "__rgb", ")", ",", "'rgb'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")", ")" ]
Return the two websafe colors nearest to this one. Returns: A tuple of two grapefruit.Color instances which are the two web safe colors closest this one. >>> c = Color.from_rgb(1.0, 0.45, 0.0) >>> c1, c2 = c.websafe_dither() >>> c1 Color(1.0, 0.4, 0.0, 1.0) >>> c2 Color(1.0, 0.6, 0.0, 1.0)
[ "Return", "the", "two", "websafe", "colors", "nearest", "to", "this", "one", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1895-L1912
xav/Grapefruit
grapefruit.py
Color.complementary_color
def complementary_color(self, mode='ryb'): """Create a new instance which is the complementary color of this one. Parameters: :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb') Color(0.0, 0.5, 1.0, 1.0) >>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb').hsl (210.0, 1.0, 0.5) """ h, s, l = self.__hsl if mode == 'ryb': h = rgb_to_ryb(h) h = (h+180)%360 if mode == 'ryb': h = ryb_to_rgb(h) return Color((h, s, l), 'hsl', self.__a, self.__wref)
python
def complementary_color(self, mode='ryb'): """Create a new instance which is the complementary color of this one. Parameters: :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb') Color(0.0, 0.5, 1.0, 1.0) >>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb').hsl (210.0, 1.0, 0.5) """ h, s, l = self.__hsl if mode == 'ryb': h = rgb_to_ryb(h) h = (h+180)%360 if mode == 'ryb': h = ryb_to_rgb(h) return Color((h, s, l), 'hsl', self.__a, self.__wref)
[ "def", "complementary_color", "(", "self", ",", "mode", "=", "'ryb'", ")", ":", "h", ",", "s", ",", "l", "=", "self", ".", "__hsl", "if", "mode", "==", "'ryb'", ":", "h", "=", "rgb_to_ryb", "(", "h", ")", "h", "=", "(", "h", "+", "180", ")", "%", "360", "if", "mode", "==", "'ryb'", ":", "h", "=", "ryb_to_rgb", "(", "h", ")", "return", "Color", "(", "(", "h", ",", "s", ",", "l", ")", ",", "'hsl'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")" ]
Create a new instance which is the complementary color of this one. Parameters: :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A grapefruit.Color instance. >>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb') Color(0.0, 0.5, 1.0, 1.0) >>> Color.from_hsl(30, 1, 0.5).complementary_color(mode='rgb').hsl (210.0, 1.0, 0.5)
[ "Create", "a", "new", "instance", "which", "is", "the", "complementary", "color", "of", "this", "one", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1914-L1937
xav/Grapefruit
grapefruit.py
Color.make_analogous_scheme
def make_analogous_scheme(self, angle=30, mode='ryb'): """Return two colors analogous to this one. Args: :angle: The angle between the hues of the created colors and this one. :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A tuple of grapefruit.Colors analogous to this one. >>> c1 = Color.from_hsl(30, 1, 0.5) >>> c2, c3 = c1.make_analogous_scheme(angle=60, mode='rgb') >>> c2.hsl (330.0, 1.0, 0.5) >>> c3.hsl (90.0, 1.0, 0.5) >>> c2, c3 = c1.make_analogous_scheme(angle=10, mode='rgb') >>> c2.hsl (20.0, 1.0, 0.5) >>> c3.hsl (40.0, 1.0, 0.5) """ h, s, l = self.__hsl if mode == 'ryb': h = rgb_to_ryb(h) h += 360 h1 = (h - angle) % 360 h2 = (h + angle) % 360 if mode == 'ryb': h1 = ryb_to_rgb(h1) h2 = ryb_to_rgb(h2) return (Color((h1, s, l), 'hsl', self.__a, self.__wref), Color((h2, s, l), 'hsl', self.__a, self.__wref))
python
def make_analogous_scheme(self, angle=30, mode='ryb'): """Return two colors analogous to this one. Args: :angle: The angle between the hues of the created colors and this one. :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A tuple of grapefruit.Colors analogous to this one. >>> c1 = Color.from_hsl(30, 1, 0.5) >>> c2, c3 = c1.make_analogous_scheme(angle=60, mode='rgb') >>> c2.hsl (330.0, 1.0, 0.5) >>> c3.hsl (90.0, 1.0, 0.5) >>> c2, c3 = c1.make_analogous_scheme(angle=10, mode='rgb') >>> c2.hsl (20.0, 1.0, 0.5) >>> c3.hsl (40.0, 1.0, 0.5) """ h, s, l = self.__hsl if mode == 'ryb': h = rgb_to_ryb(h) h += 360 h1 = (h - angle) % 360 h2 = (h + angle) % 360 if mode == 'ryb': h1 = ryb_to_rgb(h1) h2 = ryb_to_rgb(h2) return (Color((h1, s, l), 'hsl', self.__a, self.__wref), Color((h2, s, l), 'hsl', self.__a, self.__wref))
[ "def", "make_analogous_scheme", "(", "self", ",", "angle", "=", "30", ",", "mode", "=", "'ryb'", ")", ":", "h", ",", "s", ",", "l", "=", "self", ".", "__hsl", "if", "mode", "==", "'ryb'", ":", "h", "=", "rgb_to_ryb", "(", "h", ")", "h", "+=", "360", "h1", "=", "(", "h", "-", "angle", ")", "%", "360", "h2", "=", "(", "h", "+", "angle", ")", "%", "360", "if", "mode", "==", "'ryb'", ":", "h1", "=", "ryb_to_rgb", "(", "h1", ")", "h2", "=", "ryb_to_rgb", "(", "h2", ")", "return", "(", "Color", "(", "(", "h1", ",", "s", ",", "l", ")", ",", "'hsl'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")", ",", "Color", "(", "(", "h2", ",", "s", ",", "l", ")", ",", "'hsl'", ",", "self", ".", "__a", ",", "self", ".", "__wref", ")", ")" ]
Return two colors analogous to this one. Args: :angle: The angle between the hues of the created colors and this one. :mode: Select which color wheel to use for the generation (ryb/rgb). Returns: A tuple of grapefruit.Colors analogous to this one. >>> c1 = Color.from_hsl(30, 1, 0.5) >>> c2, c3 = c1.make_analogous_scheme(angle=60, mode='rgb') >>> c2.hsl (330.0, 1.0, 0.5) >>> c3.hsl (90.0, 1.0, 0.5) >>> c2, c3 = c1.make_analogous_scheme(angle=10, mode='rgb') >>> c2.hsl (20.0, 1.0, 0.5) >>> c3.hsl (40.0, 1.0, 0.5)
[ "Return", "two", "colors", "analogous", "to", "this", "one", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L2089-L2127
xav/Grapefruit
grapefruit.py
Color.alpha_blend
def alpha_blend(self, other): """Alpha-blend this color on the other one. Args: :other: The grapefruit.Color to alpha-blend with this one. Returns: A grapefruit.Color instance which is the result of alpha-blending this color on the other one. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) >>> c2 = Color.from_rgb(1, 1, 1, 0.8) >>> c3 = c1.alpha_blend(c2) >>> c3 Color(1.0, 0.875, 0.75, 0.84) """ # get final alpha channel fa = self.__a + other.__a - (self.__a * other.__a) # get percentage of source alpha compared to final alpha if fa==0: sa = 0 else: sa = min(1.0, self.__a/other.__a) # destination percentage is just the additive inverse da = 1.0 - sa sr, sg, sb = [v * sa for v in self.__rgb] dr, dg, db = [v * da for v in other.__rgb] return Color((sr+dr, sg+dg, sb+db), 'rgb', fa, self.__wref)
python
def alpha_blend(self, other): """Alpha-blend this color on the other one. Args: :other: The grapefruit.Color to alpha-blend with this one. Returns: A grapefruit.Color instance which is the result of alpha-blending this color on the other one. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) >>> c2 = Color.from_rgb(1, 1, 1, 0.8) >>> c3 = c1.alpha_blend(c2) >>> c3 Color(1.0, 0.875, 0.75, 0.84) """ # get final alpha channel fa = self.__a + other.__a - (self.__a * other.__a) # get percentage of source alpha compared to final alpha if fa==0: sa = 0 else: sa = min(1.0, self.__a/other.__a) # destination percentage is just the additive inverse da = 1.0 - sa sr, sg, sb = [v * sa for v in self.__rgb] dr, dg, db = [v * da for v in other.__rgb] return Color((sr+dr, sg+dg, sb+db), 'rgb', fa, self.__wref)
[ "def", "alpha_blend", "(", "self", ",", "other", ")", ":", "# get final alpha channel", "fa", "=", "self", ".", "__a", "+", "other", ".", "__a", "-", "(", "self", ".", "__a", "*", "other", ".", "__a", ")", "# get percentage of source alpha compared to final alpha", "if", "fa", "==", "0", ":", "sa", "=", "0", "else", ":", "sa", "=", "min", "(", "1.0", ",", "self", ".", "__a", "/", "other", ".", "__a", ")", "# destination percentage is just the additive inverse", "da", "=", "1.0", "-", "sa", "sr", ",", "sg", ",", "sb", "=", "[", "v", "*", "sa", "for", "v", "in", "self", ".", "__rgb", "]", "dr", ",", "dg", ",", "db", "=", "[", "v", "*", "da", "for", "v", "in", "other", ".", "__rgb", "]", "return", "Color", "(", "(", "sr", "+", "dr", ",", "sg", "+", "dg", ",", "sb", "+", "db", ")", ",", "'rgb'", ",", "fa", ",", "self", ".", "__wref", ")" ]
Alpha-blend this color on the other one. Args: :other: The grapefruit.Color to alpha-blend with this one. Returns: A grapefruit.Color instance which is the result of alpha-blending this color on the other one. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) >>> c2 = Color.from_rgb(1, 1, 1, 0.8) >>> c3 = c1.alpha_blend(c2) >>> c3 Color(1.0, 0.875, 0.75, 0.84)
[ "Alpha", "-", "blend", "this", "color", "on", "the", "other", "one", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L2129-L2160
xav/Grapefruit
grapefruit.py
Color.blend
def blend(self, other, percent=0.5): """blend this color with the other one. Args: :other: the grapefruit.Color to blend with this one. Returns: A grapefruit.Color instance which is the result of blending this color on the other one. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) >>> c2 = Color.from_rgb(1, 1, 1, 0.6) >>> c3 = c1.blend(c2) >>> c3 Color(1.0, 0.75, 0.5, 0.4) """ dest = 1.0 - percent rgb = tuple(((u * percent) + (v * dest) for u, v in zip(self.__rgb, other.__rgb))) a = (self.__a * percent) + (other.__a * dest) return Color(rgb, 'rgb', a, self.__wref)
python
def blend(self, other, percent=0.5): """blend this color with the other one. Args: :other: the grapefruit.Color to blend with this one. Returns: A grapefruit.Color instance which is the result of blending this color on the other one. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) >>> c2 = Color.from_rgb(1, 1, 1, 0.6) >>> c3 = c1.blend(c2) >>> c3 Color(1.0, 0.75, 0.5, 0.4) """ dest = 1.0 - percent rgb = tuple(((u * percent) + (v * dest) for u, v in zip(self.__rgb, other.__rgb))) a = (self.__a * percent) + (other.__a * dest) return Color(rgb, 'rgb', a, self.__wref)
[ "def", "blend", "(", "self", ",", "other", ",", "percent", "=", "0.5", ")", ":", "dest", "=", "1.0", "-", "percent", "rgb", "=", "tuple", "(", "(", "(", "u", "*", "percent", ")", "+", "(", "v", "*", "dest", ")", "for", "u", ",", "v", "in", "zip", "(", "self", ".", "__rgb", ",", "other", ".", "__rgb", ")", ")", ")", "a", "=", "(", "self", ".", "__a", "*", "percent", ")", "+", "(", "other", ".", "__a", "*", "dest", ")", "return", "Color", "(", "rgb", ",", "'rgb'", ",", "a", ",", "self", ".", "__wref", ")" ]
blend this color with the other one. Args: :other: the grapefruit.Color to blend with this one. Returns: A grapefruit.Color instance which is the result of blending this color on the other one. >>> c1 = Color.from_rgb(1, 0.5, 0, 0.2) >>> c2 = Color.from_rgb(1, 1, 1, 0.6) >>> c3 = c1.blend(c2) >>> c3 Color(1.0, 0.75, 0.5, 0.4)
[ "blend", "this", "color", "with", "the", "other", "one", "." ]
train
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L2162-L2183
huntrar/scrape
scrape/scrape.py
get_parser
def get_parser(): """Parse command-line arguments.""" parser = ArgumentParser(description='a command-line web scraping tool') parser.add_argument('query', metavar='QUERY', type=str, nargs='*', help='URLs/files to scrape') parser.add_argument('-a', '--attributes', type=str, nargs='*', help='extract text using tag attributes') parser.add_argument('-all', '--crawl-all', help='crawl all pages', action='store_true') parser.add_argument('-c', '--crawl', type=str, nargs='*', help='regexp rules for following new pages') parser.add_argument('-C', '--clear-cache', help='clear requests cache', action='store_true') parser.add_argument('--csv', help='write files as csv', action='store_true') parser.add_argument('-cs', '--cache-size', type=int, nargs='?', help='size of page cache (default: 1000)', default=1000) parser.add_argument('-f', '--filter', type=str, nargs='*', help='regexp rules for filtering text') parser.add_argument('--html', help='write files as HTML', action='store_true') parser.add_argument('-i', '--images', action='store_true', help='save page images') parser.add_argument('-m', '--multiple', help='save to multiple files', action='store_true') parser.add_argument('-max', '--max-crawls', type=int, help='max number of pages to crawl') parser.add_argument('-n', '--nonstrict', action='store_true', help='allow crawler to visit any domain') parser.add_argument('-ni', '--no-images', action='store_true', help='do not save page images') parser.add_argument('-no', '--no-overwrite', action='store_true', help='do not overwrite files if they exist') parser.add_argument('-o', '--out', type=str, nargs='*', help='specify outfile names') parser.add_argument('-ow', '--overwrite', action='store_true', help='overwrite a file if it exists') parser.add_argument('-p', '--pdf', help='write files as pdf', action='store_true') parser.add_argument('-pt', '--print', help='print text output', action='store_true') parser.add_argument('-q', '--quiet', help='suppress program output', action='store_true') parser.add_argument('-s', '--single', help='save to a single file', action='store_true') parser.add_argument('-t', '--text', help='write files as text', action='store_true') parser.add_argument('-v', '--version', help='display current version', action='store_true') parser.add_argument('-x', '--xpath', type=str, nargs='?', help='filter HTML using XPath') return parser
python
def get_parser(): """Parse command-line arguments.""" parser = ArgumentParser(description='a command-line web scraping tool') parser.add_argument('query', metavar='QUERY', type=str, nargs='*', help='URLs/files to scrape') parser.add_argument('-a', '--attributes', type=str, nargs='*', help='extract text using tag attributes') parser.add_argument('-all', '--crawl-all', help='crawl all pages', action='store_true') parser.add_argument('-c', '--crawl', type=str, nargs='*', help='regexp rules for following new pages') parser.add_argument('-C', '--clear-cache', help='clear requests cache', action='store_true') parser.add_argument('--csv', help='write files as csv', action='store_true') parser.add_argument('-cs', '--cache-size', type=int, nargs='?', help='size of page cache (default: 1000)', default=1000) parser.add_argument('-f', '--filter', type=str, nargs='*', help='regexp rules for filtering text') parser.add_argument('--html', help='write files as HTML', action='store_true') parser.add_argument('-i', '--images', action='store_true', help='save page images') parser.add_argument('-m', '--multiple', help='save to multiple files', action='store_true') parser.add_argument('-max', '--max-crawls', type=int, help='max number of pages to crawl') parser.add_argument('-n', '--nonstrict', action='store_true', help='allow crawler to visit any domain') parser.add_argument('-ni', '--no-images', action='store_true', help='do not save page images') parser.add_argument('-no', '--no-overwrite', action='store_true', help='do not overwrite files if they exist') parser.add_argument('-o', '--out', type=str, nargs='*', help='specify outfile names') parser.add_argument('-ow', '--overwrite', action='store_true', help='overwrite a file if it exists') parser.add_argument('-p', '--pdf', help='write files as pdf', action='store_true') parser.add_argument('-pt', '--print', help='print text output', action='store_true') parser.add_argument('-q', '--quiet', help='suppress program output', action='store_true') parser.add_argument('-s', '--single', help='save to a single file', action='store_true') parser.add_argument('-t', '--text', help='write files as text', action='store_true') parser.add_argument('-v', '--version', help='display current version', action='store_true') parser.add_argument('-x', '--xpath', type=str, nargs='?', help='filter HTML using XPath') return parser
[ "def", "get_parser", "(", ")", ":", "parser", "=", "ArgumentParser", "(", "description", "=", "'a command-line web scraping tool'", ")", "parser", ".", "add_argument", "(", "'query'", ",", "metavar", "=", "'QUERY'", ",", "type", "=", "str", ",", "nargs", "=", "'*'", ",", "help", "=", "'URLs/files to scrape'", ")", "parser", ".", "add_argument", "(", "'-a'", ",", "'--attributes'", ",", "type", "=", "str", ",", "nargs", "=", "'*'", ",", "help", "=", "'extract text using tag attributes'", ")", "parser", ".", "add_argument", "(", "'-all'", ",", "'--crawl-all'", ",", "help", "=", "'crawl all pages'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--crawl'", ",", "type", "=", "str", ",", "nargs", "=", "'*'", ",", "help", "=", "'regexp rules for following new pages'", ")", "parser", ".", "add_argument", "(", "'-C'", ",", "'--clear-cache'", ",", "help", "=", "'clear requests cache'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'--csv'", ",", "help", "=", "'write files as csv'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-cs'", ",", "'--cache-size'", ",", "type", "=", "int", ",", "nargs", "=", "'?'", ",", "help", "=", "'size of page cache (default: 1000)'", ",", "default", "=", "1000", ")", "parser", ".", "add_argument", "(", "'-f'", ",", "'--filter'", ",", "type", "=", "str", ",", "nargs", "=", "'*'", ",", "help", "=", "'regexp rules for filtering text'", ")", "parser", ".", "add_argument", "(", "'--html'", ",", "help", "=", "'write files as HTML'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--images'", ",", "action", "=", "'store_true'", ",", "help", "=", "'save page images'", ")", "parser", ".", "add_argument", "(", "'-m'", ",", "'--multiple'", ",", "help", "=", "'save to multiple files'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-max'", ",", "'--max-crawls'", ",", "type", "=", "int", ",", "help", "=", "'max number of pages to crawl'", ")", "parser", ".", "add_argument", "(", "'-n'", ",", "'--nonstrict'", ",", "action", "=", "'store_true'", ",", "help", "=", "'allow crawler to visit any domain'", ")", "parser", ".", "add_argument", "(", "'-ni'", ",", "'--no-images'", ",", "action", "=", "'store_true'", ",", "help", "=", "'do not save page images'", ")", "parser", ".", "add_argument", "(", "'-no'", ",", "'--no-overwrite'", ",", "action", "=", "'store_true'", ",", "help", "=", "'do not overwrite files if they exist'", ")", "parser", ".", "add_argument", "(", "'-o'", ",", "'--out'", ",", "type", "=", "str", ",", "nargs", "=", "'*'", ",", "help", "=", "'specify outfile names'", ")", "parser", ".", "add_argument", "(", "'-ow'", ",", "'--overwrite'", ",", "action", "=", "'store_true'", ",", "help", "=", "'overwrite a file if it exists'", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "'--pdf'", ",", "help", "=", "'write files as pdf'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-pt'", ",", "'--print'", ",", "help", "=", "'print text output'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-q'", ",", "'--quiet'", ",", "help", "=", "'suppress program output'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--single'", ",", "help", "=", "'save to a single file'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-t'", ",", "'--text'", ",", "help", "=", "'write files as text'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--version'", ",", "help", "=", "'display current version'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-x'", ",", "'--xpath'", ",", "type", "=", "str", ",", "nargs", "=", "'?'", ",", "help", "=", "'filter HTML using XPath'", ")", "return", "parser" ]
Parse command-line arguments.
[ "Parse", "command", "-", "line", "arguments", "." ]
train
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L19-L71
huntrar/scrape
scrape/scrape.py
write_files
def write_files(args, infilenames, outfilename): """Write scraped or local file(s) in desired format. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output file (str) Remove PART(#).html files after conversion unless otherwise specified. """ write_actions = {'print': utils.print_text, 'pdf': utils.write_pdf_files, 'csv': utils.write_csv_files, 'text': utils.write_text_files} try: for action in iterkeys(write_actions): if args[action]: write_actions[action](args, infilenames, outfilename) finally: if args['urls'] and not args['html']: utils.remove_part_files()
python
def write_files(args, infilenames, outfilename): """Write scraped or local file(s) in desired format. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output file (str) Remove PART(#).html files after conversion unless otherwise specified. """ write_actions = {'print': utils.print_text, 'pdf': utils.write_pdf_files, 'csv': utils.write_csv_files, 'text': utils.write_text_files} try: for action in iterkeys(write_actions): if args[action]: write_actions[action](args, infilenames, outfilename) finally: if args['urls'] and not args['html']: utils.remove_part_files()
[ "def", "write_files", "(", "args", ",", "infilenames", ",", "outfilename", ")", ":", "write_actions", "=", "{", "'print'", ":", "utils", ".", "print_text", ",", "'pdf'", ":", "utils", ".", "write_pdf_files", ",", "'csv'", ":", "utils", ".", "write_csv_files", ",", "'text'", ":", "utils", ".", "write_text_files", "}", "try", ":", "for", "action", "in", "iterkeys", "(", "write_actions", ")", ":", "if", "args", "[", "action", "]", ":", "write_actions", "[", "action", "]", "(", "args", ",", "infilenames", ",", "outfilename", ")", "finally", ":", "if", "args", "[", "'urls'", "]", "and", "not", "args", "[", "'html'", "]", ":", "utils", ".", "remove_part_files", "(", ")" ]
Write scraped or local file(s) in desired format. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- name of output file (str) Remove PART(#).html files after conversion unless otherwise specified.
[ "Write", "scraped", "or", "local", "file", "(", "s", ")", "in", "desired", "format", "." ]
train
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L74-L94
huntrar/scrape
scrape/scrape.py
write_single_file
def write_single_file(args, base_dir, crawler): """Write to a single output file and/or subdirectory.""" if args['urls'] and args['html']: # Create a directory to save PART.html files in domain = utils.get_domain(args['urls'][0]) if not args['quiet']: print('Storing html files in {0}/'.format(domain)) utils.mkdir_and_cd(domain) infilenames = [] for query in args['query']: if query in args['files']: infilenames.append(query) elif query.strip('/') in args['urls']: if args['crawl'] or args['crawl_all']: # Crawl and save HTML files/image files to disk infilenames += crawler.crawl_links(query) else: raw_resp = utils.get_raw_resp(query) if raw_resp is None: return False prev_part_num = utils.get_num_part_files() utils.write_part_file(args, query, raw_resp) curr_part_num = prev_part_num + 1 infilenames += utils.get_part_filenames(curr_part_num, prev_part_num) # Convert output or leave as PART.html files if args['html']: # HTML files have been written already, so return to base directory os.chdir(base_dir) else: # Write files to text or pdf if infilenames: if args['out']: outfilename = args['out'][0] else: outfilename = utils.get_single_outfilename(args) if outfilename: write_files(args, infilenames, outfilename) else: utils.remove_part_files() return True
python
def write_single_file(args, base_dir, crawler): """Write to a single output file and/or subdirectory.""" if args['urls'] and args['html']: # Create a directory to save PART.html files in domain = utils.get_domain(args['urls'][0]) if not args['quiet']: print('Storing html files in {0}/'.format(domain)) utils.mkdir_and_cd(domain) infilenames = [] for query in args['query']: if query in args['files']: infilenames.append(query) elif query.strip('/') in args['urls']: if args['crawl'] or args['crawl_all']: # Crawl and save HTML files/image files to disk infilenames += crawler.crawl_links(query) else: raw_resp = utils.get_raw_resp(query) if raw_resp is None: return False prev_part_num = utils.get_num_part_files() utils.write_part_file(args, query, raw_resp) curr_part_num = prev_part_num + 1 infilenames += utils.get_part_filenames(curr_part_num, prev_part_num) # Convert output or leave as PART.html files if args['html']: # HTML files have been written already, so return to base directory os.chdir(base_dir) else: # Write files to text or pdf if infilenames: if args['out']: outfilename = args['out'][0] else: outfilename = utils.get_single_outfilename(args) if outfilename: write_files(args, infilenames, outfilename) else: utils.remove_part_files() return True
[ "def", "write_single_file", "(", "args", ",", "base_dir", ",", "crawler", ")", ":", "if", "args", "[", "'urls'", "]", "and", "args", "[", "'html'", "]", ":", "# Create a directory to save PART.html files in", "domain", "=", "utils", ".", "get_domain", "(", "args", "[", "'urls'", "]", "[", "0", "]", ")", "if", "not", "args", "[", "'quiet'", "]", ":", "print", "(", "'Storing html files in {0}/'", ".", "format", "(", "domain", ")", ")", "utils", ".", "mkdir_and_cd", "(", "domain", ")", "infilenames", "=", "[", "]", "for", "query", "in", "args", "[", "'query'", "]", ":", "if", "query", "in", "args", "[", "'files'", "]", ":", "infilenames", ".", "append", "(", "query", ")", "elif", "query", ".", "strip", "(", "'/'", ")", "in", "args", "[", "'urls'", "]", ":", "if", "args", "[", "'crawl'", "]", "or", "args", "[", "'crawl_all'", "]", ":", "# Crawl and save HTML files/image files to disk", "infilenames", "+=", "crawler", ".", "crawl_links", "(", "query", ")", "else", ":", "raw_resp", "=", "utils", ".", "get_raw_resp", "(", "query", ")", "if", "raw_resp", "is", "None", ":", "return", "False", "prev_part_num", "=", "utils", ".", "get_num_part_files", "(", ")", "utils", ".", "write_part_file", "(", "args", ",", "query", ",", "raw_resp", ")", "curr_part_num", "=", "prev_part_num", "+", "1", "infilenames", "+=", "utils", ".", "get_part_filenames", "(", "curr_part_num", ",", "prev_part_num", ")", "# Convert output or leave as PART.html files", "if", "args", "[", "'html'", "]", ":", "# HTML files have been written already, so return to base directory", "os", ".", "chdir", "(", "base_dir", ")", "else", ":", "# Write files to text or pdf", "if", "infilenames", ":", "if", "args", "[", "'out'", "]", ":", "outfilename", "=", "args", "[", "'out'", "]", "[", "0", "]", "else", ":", "outfilename", "=", "utils", ".", "get_single_outfilename", "(", "args", ")", "if", "outfilename", ":", "write_files", "(", "args", ",", "infilenames", ",", "outfilename", ")", "else", ":", "utils", ".", "remove_part_files", "(", ")", "return", "True" ]
Write to a single output file and/or subdirectory.
[ "Write", "to", "a", "single", "output", "file", "and", "/", "or", "subdirectory", "." ]
train
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L97-L139
huntrar/scrape
scrape/scrape.py
write_multiple_files
def write_multiple_files(args, base_dir, crawler): """Write to multiple output files and/or subdirectories.""" for i, query in enumerate(args['query']): if query in args['files']: # Write files if args['out'] and i < len(args['out']): outfilename = args['out'][i] else: outfilename = '.'.join(query.split('.')[:-1]) write_files(args, [query], outfilename) elif query in args['urls']: # Scrape/crawl urls domain = utils.get_domain(query) if args['html']: # Create a directory to save PART.html files in if not args['quiet']: print('Storing html files in {0}/'.format(domain)) utils.mkdir_and_cd(domain) if args['crawl'] or args['crawl_all']: # Crawl and save HTML files/image files to disk infilenames = crawler.crawl_links(query) else: raw_resp = utils.get_raw_resp(query) if raw_resp is None: return False # Saves page as PART.html file prev_part_num = utils.get_num_part_files() utils.write_part_file(args, query, raw_resp) curr_part_num = prev_part_num + 1 infilenames = utils.get_part_filenames(curr_part_num, prev_part_num) # Convert output or leave as PART.html files if args['html']: # HTML files have been written already, so return to base dir os.chdir(base_dir) else: # Write files to text or pdf if infilenames: if args['out'] and i < len(args['out']): outfilename = args['out'][i] else: outfilename = utils.get_outfilename(query, domain) write_files(args, infilenames, outfilename) else: sys.stderr.write('Failed to retrieve content from {0}.\n' .format(query)) return True
python
def write_multiple_files(args, base_dir, crawler): """Write to multiple output files and/or subdirectories.""" for i, query in enumerate(args['query']): if query in args['files']: # Write files if args['out'] and i < len(args['out']): outfilename = args['out'][i] else: outfilename = '.'.join(query.split('.')[:-1]) write_files(args, [query], outfilename) elif query in args['urls']: # Scrape/crawl urls domain = utils.get_domain(query) if args['html']: # Create a directory to save PART.html files in if not args['quiet']: print('Storing html files in {0}/'.format(domain)) utils.mkdir_and_cd(domain) if args['crawl'] or args['crawl_all']: # Crawl and save HTML files/image files to disk infilenames = crawler.crawl_links(query) else: raw_resp = utils.get_raw_resp(query) if raw_resp is None: return False # Saves page as PART.html file prev_part_num = utils.get_num_part_files() utils.write_part_file(args, query, raw_resp) curr_part_num = prev_part_num + 1 infilenames = utils.get_part_filenames(curr_part_num, prev_part_num) # Convert output or leave as PART.html files if args['html']: # HTML files have been written already, so return to base dir os.chdir(base_dir) else: # Write files to text or pdf if infilenames: if args['out'] and i < len(args['out']): outfilename = args['out'][i] else: outfilename = utils.get_outfilename(query, domain) write_files(args, infilenames, outfilename) else: sys.stderr.write('Failed to retrieve content from {0}.\n' .format(query)) return True
[ "def", "write_multiple_files", "(", "args", ",", "base_dir", ",", "crawler", ")", ":", "for", "i", ",", "query", "in", "enumerate", "(", "args", "[", "'query'", "]", ")", ":", "if", "query", "in", "args", "[", "'files'", "]", ":", "# Write files", "if", "args", "[", "'out'", "]", "and", "i", "<", "len", "(", "args", "[", "'out'", "]", ")", ":", "outfilename", "=", "args", "[", "'out'", "]", "[", "i", "]", "else", ":", "outfilename", "=", "'.'", ".", "join", "(", "query", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", ")", "write_files", "(", "args", ",", "[", "query", "]", ",", "outfilename", ")", "elif", "query", "in", "args", "[", "'urls'", "]", ":", "# Scrape/crawl urls", "domain", "=", "utils", ".", "get_domain", "(", "query", ")", "if", "args", "[", "'html'", "]", ":", "# Create a directory to save PART.html files in", "if", "not", "args", "[", "'quiet'", "]", ":", "print", "(", "'Storing html files in {0}/'", ".", "format", "(", "domain", ")", ")", "utils", ".", "mkdir_and_cd", "(", "domain", ")", "if", "args", "[", "'crawl'", "]", "or", "args", "[", "'crawl_all'", "]", ":", "# Crawl and save HTML files/image files to disk", "infilenames", "=", "crawler", ".", "crawl_links", "(", "query", ")", "else", ":", "raw_resp", "=", "utils", ".", "get_raw_resp", "(", "query", ")", "if", "raw_resp", "is", "None", ":", "return", "False", "# Saves page as PART.html file", "prev_part_num", "=", "utils", ".", "get_num_part_files", "(", ")", "utils", ".", "write_part_file", "(", "args", ",", "query", ",", "raw_resp", ")", "curr_part_num", "=", "prev_part_num", "+", "1", "infilenames", "=", "utils", ".", "get_part_filenames", "(", "curr_part_num", ",", "prev_part_num", ")", "# Convert output or leave as PART.html files", "if", "args", "[", "'html'", "]", ":", "# HTML files have been written already, so return to base dir", "os", ".", "chdir", "(", "base_dir", ")", "else", ":", "# Write files to text or pdf", "if", "infilenames", ":", "if", "args", "[", "'out'", "]", "and", "i", "<", "len", "(", "args", "[", "'out'", "]", ")", ":", "outfilename", "=", "args", "[", "'out'", "]", "[", "i", "]", "else", ":", "outfilename", "=", "utils", ".", "get_outfilename", "(", "query", ",", "domain", ")", "write_files", "(", "args", ",", "infilenames", ",", "outfilename", ")", "else", ":", "sys", ".", "stderr", ".", "write", "(", "'Failed to retrieve content from {0}.\\n'", ".", "format", "(", "query", ")", ")", "return", "True" ]
Write to multiple output files and/or subdirectories.
[ "Write", "to", "multiple", "output", "files", "and", "/", "or", "subdirectories", "." ]
train
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L142-L190
huntrar/scrape
scrape/scrape.py
split_input
def split_input(args): """Split query input into local files and URLs.""" args['files'] = [] args['urls'] = [] for arg in args['query']: if os.path.isfile(arg): args['files'].append(arg) else: args['urls'].append(arg.strip('/'))
python
def split_input(args): """Split query input into local files and URLs.""" args['files'] = [] args['urls'] = [] for arg in args['query']: if os.path.isfile(arg): args['files'].append(arg) else: args['urls'].append(arg.strip('/'))
[ "def", "split_input", "(", "args", ")", ":", "args", "[", "'files'", "]", "=", "[", "]", "args", "[", "'urls'", "]", "=", "[", "]", "for", "arg", "in", "args", "[", "'query'", "]", ":", "if", "os", ".", "path", ".", "isfile", "(", "arg", ")", ":", "args", "[", "'files'", "]", ".", "append", "(", "arg", ")", "else", ":", "args", "[", "'urls'", "]", ".", "append", "(", "arg", ".", "strip", "(", "'/'", ")", ")" ]
Split query input into local files and URLs.
[ "Split", "query", "input", "into", "local", "files", "and", "URLs", "." ]
train
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L193-L201
huntrar/scrape
scrape/scrape.py
detect_output_type
def detect_output_type(args): """Detect whether to save to a single or multiple files.""" if not args['single'] and not args['multiple']: # Save to multiple files if multiple files/URLs entered if len(args['query']) > 1 or len(args['out']) > 1: args['multiple'] = True else: args['single'] = True
python
def detect_output_type(args): """Detect whether to save to a single or multiple files.""" if not args['single'] and not args['multiple']: # Save to multiple files if multiple files/URLs entered if len(args['query']) > 1 or len(args['out']) > 1: args['multiple'] = True else: args['single'] = True
[ "def", "detect_output_type", "(", "args", ")", ":", "if", "not", "args", "[", "'single'", "]", "and", "not", "args", "[", "'multiple'", "]", ":", "# Save to multiple files if multiple files/URLs entered", "if", "len", "(", "args", "[", "'query'", "]", ")", ">", "1", "or", "len", "(", "args", "[", "'out'", "]", ")", ">", "1", ":", "args", "[", "'multiple'", "]", "=", "True", "else", ":", "args", "[", "'single'", "]", "=", "True" ]
Detect whether to save to a single or multiple files.
[ "Detect", "whether", "to", "save", "to", "a", "single", "or", "multiple", "files", "." ]
train
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L204-L211
huntrar/scrape
scrape/scrape.py
scrape
def scrape(args): """Scrape webpage content.""" try: base_dir = os.getcwd() if args['out'] is None: args['out'] = [] # Detect whether to save to a single or multiple files detect_output_type(args) # Split query input into local files and URLs split_input(args) if args['urls']: # Add URL extensions and schemes and update query and URLs urls_with_exts = [utils.add_url_suffix(x) for x in args['urls']] args['query'] = [utils.add_protocol(x) if x in args['urls'] else x for x in urls_with_exts] args['urls'] = [x for x in args['query'] if x not in args['files']] # Print error if attempting to convert local files to HTML if args['files'] and args['html']: sys.stderr.write('Cannot convert local files to HTML.\n') args['files'] = [] # Instantiate web crawler if necessary crawler = None if args['crawl'] or args['crawl_all']: crawler = Crawler(args) if args['single']: return write_single_file(args, base_dir, crawler) elif args['multiple']: return write_multiple_files(args, base_dir, crawler) except (KeyboardInterrupt, Exception): if args['html']: try: os.chdir(base_dir) except OSError: pass else: utils.remove_part_files() raise
python
def scrape(args): """Scrape webpage content.""" try: base_dir = os.getcwd() if args['out'] is None: args['out'] = [] # Detect whether to save to a single or multiple files detect_output_type(args) # Split query input into local files and URLs split_input(args) if args['urls']: # Add URL extensions and schemes and update query and URLs urls_with_exts = [utils.add_url_suffix(x) for x in args['urls']] args['query'] = [utils.add_protocol(x) if x in args['urls'] else x for x in urls_with_exts] args['urls'] = [x for x in args['query'] if x not in args['files']] # Print error if attempting to convert local files to HTML if args['files'] and args['html']: sys.stderr.write('Cannot convert local files to HTML.\n') args['files'] = [] # Instantiate web crawler if necessary crawler = None if args['crawl'] or args['crawl_all']: crawler = Crawler(args) if args['single']: return write_single_file(args, base_dir, crawler) elif args['multiple']: return write_multiple_files(args, base_dir, crawler) except (KeyboardInterrupt, Exception): if args['html']: try: os.chdir(base_dir) except OSError: pass else: utils.remove_part_files() raise
[ "def", "scrape", "(", "args", ")", ":", "try", ":", "base_dir", "=", "os", ".", "getcwd", "(", ")", "if", "args", "[", "'out'", "]", "is", "None", ":", "args", "[", "'out'", "]", "=", "[", "]", "# Detect whether to save to a single or multiple files", "detect_output_type", "(", "args", ")", "# Split query input into local files and URLs", "split_input", "(", "args", ")", "if", "args", "[", "'urls'", "]", ":", "# Add URL extensions and schemes and update query and URLs", "urls_with_exts", "=", "[", "utils", ".", "add_url_suffix", "(", "x", ")", "for", "x", "in", "args", "[", "'urls'", "]", "]", "args", "[", "'query'", "]", "=", "[", "utils", ".", "add_protocol", "(", "x", ")", "if", "x", "in", "args", "[", "'urls'", "]", "else", "x", "for", "x", "in", "urls_with_exts", "]", "args", "[", "'urls'", "]", "=", "[", "x", "for", "x", "in", "args", "[", "'query'", "]", "if", "x", "not", "in", "args", "[", "'files'", "]", "]", "# Print error if attempting to convert local files to HTML", "if", "args", "[", "'files'", "]", "and", "args", "[", "'html'", "]", ":", "sys", ".", "stderr", ".", "write", "(", "'Cannot convert local files to HTML.\\n'", ")", "args", "[", "'files'", "]", "=", "[", "]", "# Instantiate web crawler if necessary", "crawler", "=", "None", "if", "args", "[", "'crawl'", "]", "or", "args", "[", "'crawl_all'", "]", ":", "crawler", "=", "Crawler", "(", "args", ")", "if", "args", "[", "'single'", "]", ":", "return", "write_single_file", "(", "args", ",", "base_dir", ",", "crawler", ")", "elif", "args", "[", "'multiple'", "]", ":", "return", "write_multiple_files", "(", "args", ",", "base_dir", ",", "crawler", ")", "except", "(", "KeyboardInterrupt", ",", "Exception", ")", ":", "if", "args", "[", "'html'", "]", ":", "try", ":", "os", ".", "chdir", "(", "base_dir", ")", "except", "OSError", ":", "pass", "else", ":", "utils", ".", "remove_part_files", "(", ")", "raise" ]
Scrape webpage content.
[ "Scrape", "webpage", "content", "." ]
train
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L214-L257
huntrar/scrape
scrape/scrape.py
prompt_filetype
def prompt_filetype(args): """Prompt user for filetype if none specified.""" valid_types = ('print', 'text', 'csv', 'pdf', 'html') if not any(args[x] for x in valid_types): try: filetype = input('Print or save output as ({0}): ' .format(', '.join(valid_types))).lower() while filetype not in valid_types: filetype = input('Invalid entry. Choose from ({0}): ' .format(', '.join(valid_types))).lower() except (KeyboardInterrupt, EOFError): return args[filetype] = True
python
def prompt_filetype(args): """Prompt user for filetype if none specified.""" valid_types = ('print', 'text', 'csv', 'pdf', 'html') if not any(args[x] for x in valid_types): try: filetype = input('Print or save output as ({0}): ' .format(', '.join(valid_types))).lower() while filetype not in valid_types: filetype = input('Invalid entry. Choose from ({0}): ' .format(', '.join(valid_types))).lower() except (KeyboardInterrupt, EOFError): return args[filetype] = True
[ "def", "prompt_filetype", "(", "args", ")", ":", "valid_types", "=", "(", "'print'", ",", "'text'", ",", "'csv'", ",", "'pdf'", ",", "'html'", ")", "if", "not", "any", "(", "args", "[", "x", "]", "for", "x", "in", "valid_types", ")", ":", "try", ":", "filetype", "=", "input", "(", "'Print or save output as ({0}): '", ".", "format", "(", "', '", ".", "join", "(", "valid_types", ")", ")", ")", ".", "lower", "(", ")", "while", "filetype", "not", "in", "valid_types", ":", "filetype", "=", "input", "(", "'Invalid entry. Choose from ({0}): '", ".", "format", "(", "', '", ".", "join", "(", "valid_types", ")", ")", ")", ".", "lower", "(", ")", "except", "(", "KeyboardInterrupt", ",", "EOFError", ")", ":", "return", "args", "[", "filetype", "]", "=", "True" ]
Prompt user for filetype if none specified.
[ "Prompt", "user", "for", "filetype", "if", "none", "specified", "." ]
train
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L260-L272