repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
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_ui...
Fetch contents of email. Args: message_uid (int): IMAP Message UID number. Kwargs: message_type: Can be 'text' or 'html'
[ "Fetch", "contents", "of", "email", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L115-L137
train
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", ".",...
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", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L139-L188
train
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 \"{su...
Get a list of message numbers
[ "Get", "a", "list", "of", "message", "numbers" ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/email.py#L190-L219
train
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", ".", ...
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", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/config.py#L82-L124
train
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"...
Generate page object from URL
[ "Generate", "page", "object", "from", "URL" ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/_devtools_/page_object_tools.py#L139-L177
train
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", ","...
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", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/data/data_management.py#L65-L94
train
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", ".", ...
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", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/data/data_management.py#L133-L152
train
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", ...
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", ...
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webelement.py#L33-L70
train
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", "=", ...
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", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webelement.py#L89-L114
train
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",...
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", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/web/webelement.py#L117-L131
train
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\"{...
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", "..." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/data_utils.py#L28-L51
train
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", "_", ...
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", "." ]
ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216
https://github.com/wiredrive/wtframework/blob/ef7f86c4d4cf7fb17745fd627b3cc4a41f4c0216/wtframework/wtf/utils/data_utils.py#L65-L74
train
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", ...
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", "()", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L87-L99
train
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", ...
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", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L320-L342
train
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",...
Load an ARFF File from a file.
[ "Load", "an", "ARFF", "File", "from", "a", "file", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L357-L367
train
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", ".",...
Parse an ARFF File already loaded into a string.
[ "Parse", "an", "ARFF", "File", "already", "loaded", "into", "a", "string", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L370-L383
train
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...
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", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L385-L398
train
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", "(", ")",...
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", "whe...
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L404-L422
train
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", "(", ")", "sel...
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", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L424-L436
train
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",...
Save an arff structure to a file.
[ "Save", "an", "arff", "structure", "to", "a", "file", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L438-L445
train
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", "]", "!=", "'\"'", "...
Converts a single data line to a string.
[ "Converts", "a", "single", "data", "line", "to", "a", "string", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L447-L532
train
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.'", "asse...
Write an arff structure to a string.
[ "Write", "an", "arff", "structure", "to", "a", "string", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L559-L584
train
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\"", "%", "(", ...
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", ...
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L592-L601
train
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", "]", "...
Print an overview of the ARFF file.
[ "Print", "an", "overview", "of", "the", "ARFF", "file", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L722-L732
train
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", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/arff.py#L746-L750
train
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", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L249-L295
train
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", "(", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L307-L344
train
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", "...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L346-L385
train
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", "(", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L387-L428
train
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", ")", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L430-L457
train
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...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L459-L485
train
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", ")", "...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L487-L514
train
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.1398...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L516-L542
train
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", "=", "[", "(", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L544-L580
train
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", ")", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L582-L612
train
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 poin...
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", "*", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L614-L655
train
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", "=", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L657-L688
train
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", "=...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L690-L716
train
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", ",",...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L718-L745
train
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", "-...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L747-L770
train
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", "-...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L772-L795
train
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", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L797-L820
train
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", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L822-L845
train
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", "(",...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L847-L867
train
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", ":", ...
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", ")", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L869-L912
train
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", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L914-L935
train
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"...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L937-L956
train
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", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L958-L990
train
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"...
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" ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L992-L1020
train
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", "+", "...
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" ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1022-L1047
train
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", "-",...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1049-L1067
train
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", "-",...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1069-L1087
train
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1123-L1147
train
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1150-L1174
train
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", "Co...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1177-L1202
train
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1205-L1229
train
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1232-L1256
train
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1259-L1283
train
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", ")", ")", ",", "'rg...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1286-L1314
train
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1317-L1341
train
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", ")", ")", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1344-L1370
train
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1373-L1401
train
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1404-L1424
train
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", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1707-L1744
train
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", "."...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1867-L1885
train
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...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1895-L1912
train
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", ")", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L1914-L1937
train
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", "+=", "...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L2089-L2127
train
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 al...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L2129-L2160
train
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", ...
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", "." ]
b3d88375be727a3a1ec5839fbc462e0e8e0836e4
https://github.com/xav/Grapefruit/blob/b3d88375be727a3a1ec5839fbc462e0e8e0836e4/grapefruit.py#L2162-L2183
train
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", "=", ...
Parse command-line arguments.
[ "Parse", "command", "-", "line", "arguments", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L19-L71
train
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"...
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", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L74-L94
train
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", "(", "ar...
Write to a single output file and/or subdirectory.
[ "Write", "to", "a", "single", "output", "file", "and", "/", "or", "subdirectory", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L97-L139
train
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"...
Write to multiple output files and/or subdirectories.
[ "Write", "to", "multiple", "output", "files", "and", "/", "or", "subdirectories", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L142-L190
train
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", ")", ...
Split query input into local files and URLs.
[ "Split", "query", "input", "into", "local", "files", "and", "URLs", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L193-L201
train
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'", "]", ")", ">"...
Detect whether to save to a single or multiple files.
[ "Detect", "whether", "to", "save", "to", "a", "single", "or", "multiple", "files", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L204-L211
train
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", "d...
Scrape webpage content.
[ "Scrape", "webpage", "content", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L214-L257
train
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", ":...
Prompt user for filetype if none specified.
[ "Prompt", "user", "for", "filetype", "if", "none", "specified", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L260-L272
train
huntrar/scrape
scrape/scrape.py
prompt_save_images
def prompt_save_images(args): """Prompt user to save images when crawling (for pdf and HTML formats).""" if args['images'] or args['no_images']: return if (args['pdf'] or args['html']) and (args['crawl'] or args['crawl_all']): save_msg = ('Choosing to save images will greatly slow the' ' crawling process.\nSave images anyways? (y/n): ') try: save_images = utils.confirm_input(input(save_msg)) except (KeyboardInterrupt, EOFError): return args['images'] = save_images args['no_images'] = not save_images
python
def prompt_save_images(args): """Prompt user to save images when crawling (for pdf and HTML formats).""" if args['images'] or args['no_images']: return if (args['pdf'] or args['html']) and (args['crawl'] or args['crawl_all']): save_msg = ('Choosing to save images will greatly slow the' ' crawling process.\nSave images anyways? (y/n): ') try: save_images = utils.confirm_input(input(save_msg)) except (KeyboardInterrupt, EOFError): return args['images'] = save_images args['no_images'] = not save_images
[ "def", "prompt_save_images", "(", "args", ")", ":", "if", "args", "[", "'images'", "]", "or", "args", "[", "'no_images'", "]", ":", "return", "if", "(", "args", "[", "'pdf'", "]", "or", "args", "[", "'html'", "]", ")", "and", "(", "args", "[", "'cr...
Prompt user to save images when crawling (for pdf and HTML formats).
[ "Prompt", "user", "to", "save", "images", "when", "crawling", "(", "for", "pdf", "and", "HTML", "formats", ")", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L275-L289
train
huntrar/scrape
scrape/scrape.py
command_line_runner
def command_line_runner(): """Handle command-line interaction.""" parser = get_parser() args = vars(parser.parse_args()) if args['version']: print(__version__) return if args['clear_cache']: utils.clear_cache() print('Cleared {0}.'.format(utils.CACHE_DIR)) return if not args['query']: parser.print_help() return # Enable cache unless user sets environ variable SCRAPE_DISABLE_CACHE if not os.getenv('SCRAPE_DISABLE_CACHE'): utils.enable_cache() # Save images unless user sets environ variable SCRAPE_DISABLE_IMGS if os.getenv('SCRAPE_DISABLE_IMGS'): args['no_images'] = True # Prompt user for filetype if none specified prompt_filetype(args) # Prompt user to save images when crawling (for pdf and HTML formats) prompt_save_images(args) # Scrape webpage content scrape(args)
python
def command_line_runner(): """Handle command-line interaction.""" parser = get_parser() args = vars(parser.parse_args()) if args['version']: print(__version__) return if args['clear_cache']: utils.clear_cache() print('Cleared {0}.'.format(utils.CACHE_DIR)) return if not args['query']: parser.print_help() return # Enable cache unless user sets environ variable SCRAPE_DISABLE_CACHE if not os.getenv('SCRAPE_DISABLE_CACHE'): utils.enable_cache() # Save images unless user sets environ variable SCRAPE_DISABLE_IMGS if os.getenv('SCRAPE_DISABLE_IMGS'): args['no_images'] = True # Prompt user for filetype if none specified prompt_filetype(args) # Prompt user to save images when crawling (for pdf and HTML formats) prompt_save_images(args) # Scrape webpage content scrape(args)
[ "def", "command_line_runner", "(", ")", ":", "parser", "=", "get_parser", "(", ")", "args", "=", "vars", "(", "parser", ".", "parse_args", "(", ")", ")", "if", "args", "[", "'version'", "]", ":", "print", "(", "__version__", ")", "return", "if", "args"...
Handle command-line interaction.
[ "Handle", "command", "-", "line", "interaction", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/scrape.py#L292-L322
train
chrisspen/weka
weka/classifiers.py
Classifier.load_raw
def load_raw(cls, model_fn, schema, *args, **kwargs): """ Loads a trained classifier from the raw Weka model format. Must specify the model schema and classifier name, since these aren't currently deduced from the model format. """ c = cls(*args, **kwargs) c.schema = schema.copy(schema_only=True) c._model_data = open(model_fn, 'rb').read() return c
python
def load_raw(cls, model_fn, schema, *args, **kwargs): """ Loads a trained classifier from the raw Weka model format. Must specify the model schema and classifier name, since these aren't currently deduced from the model format. """ c = cls(*args, **kwargs) c.schema = schema.copy(schema_only=True) c._model_data = open(model_fn, 'rb').read() return c
[ "def", "load_raw", "(", "cls", ",", "model_fn", ",", "schema", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "c", "=", "cls", "(", "*", "args", ",", "*", "*", "kwargs", ")", "c", ".", "schema", "=", "schema", ".", "copy", "(", "schema_on...
Loads a trained classifier from the raw Weka model format. Must specify the model schema and classifier name, since these aren't currently deduced from the model format.
[ "Loads", "a", "trained", "classifier", "from", "the", "raw", "Weka", "model", "format", ".", "Must", "specify", "the", "model", "schema", "and", "classifier", "name", "since", "these", "aren", "t", "currently", "deduced", "from", "the", "model", "format", "....
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/classifiers.py#L270-L279
train
chrisspen/weka
weka/classifiers.py
Classifier.train
def train(self, training_data, testing_data=None, verbose=False): """ Updates the classifier with new data. """ model_fn = None training_fn = None clean_training = False testing_fn = None clean_testing = False try: # Validate training data. if isinstance(training_data, basestring): assert os.path.isfile(training_data) training_fn = training_data else: assert isinstance(training_data, arff.ArffFile) fd, training_fn = tempfile.mkstemp(suffix='.arff') os.close(fd) with open(training_fn, 'w') as fout: fout.write(training_data.write()) clean_training = True assert training_fn # Validate testing data. if testing_data: if isinstance(testing_data, basestring): assert os.path.isfile(testing_data) testing_fn = testing_data else: assert isinstance(testing_data, arff.ArffFile) fd, testing_fn = tempfile.mkstemp(suffix='.arff') os.close(fd) with open(testing_fn, 'w') as fout: fout.write(testing_data.write()) clean_testing = True else: testing_fn = training_fn assert testing_fn # Validate model file. fd, model_fn = tempfile.mkstemp() os.close(fd) if self._model_data: fout = open(model_fn, 'wb') fout.write(self._model_data) fout.close() # Call Weka Jar. args = dict( CP=CP, classifier_name=self.name, model_fn=model_fn, training_fn=training_fn, testing_fn=testing_fn, ckargs=self._get_ckargs_str(), ) if self._model_data: # Load existing model. cmd = ( "java -cp %(CP)s %(classifier_name)s -l \"%(model_fn)s\" " "-t \"%(training_fn)s\" -T \"%(testing_fn)s\" -d \"%(model_fn)s\"") % args else: # Create new model file. cmd = ( "java -cp %(CP)s %(classifier_name)s -t \"%(training_fn)s\" " "-T \"%(testing_fn)s\" -d \"%(model_fn)s\" %(ckargs)s") % args if verbose: print(cmd) p = Popen( cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=sys.platform != "win32") stdin, stdout, stderr = (p.stdin, p.stdout, p.stderr) stdout_str = stdout.read() stderr_str = stderr.read() self.last_training_stdout = stdout_str self.last_training_stderr = stderr_str if verbose: print('stdout:') print(stdout_str) print('stderr:') print(stderr_str) # exclude "Warning" lines not to raise an error for a simple warning stderr_str = '\n'.join(l for l in stderr_str.decode('utf8').split('\n') if not "Warning" in l) if stderr_str: raise TrainingError(stderr_str) # Save schema. if not self.schema: self.schema = arff.ArffFile.load(training_fn, schema_only=True).copy(schema_only=True) # Save model. with open(model_fn, 'rb') as fin: self._model_data = fin.read() assert self._model_data finally: # Cleanup files. if model_fn: os.remove(model_fn) if training_fn and clean_training: os.remove(training_fn) if testing_fn and clean_testing: os.remove(testing_fn)
python
def train(self, training_data, testing_data=None, verbose=False): """ Updates the classifier with new data. """ model_fn = None training_fn = None clean_training = False testing_fn = None clean_testing = False try: # Validate training data. if isinstance(training_data, basestring): assert os.path.isfile(training_data) training_fn = training_data else: assert isinstance(training_data, arff.ArffFile) fd, training_fn = tempfile.mkstemp(suffix='.arff') os.close(fd) with open(training_fn, 'w') as fout: fout.write(training_data.write()) clean_training = True assert training_fn # Validate testing data. if testing_data: if isinstance(testing_data, basestring): assert os.path.isfile(testing_data) testing_fn = testing_data else: assert isinstance(testing_data, arff.ArffFile) fd, testing_fn = tempfile.mkstemp(suffix='.arff') os.close(fd) with open(testing_fn, 'w') as fout: fout.write(testing_data.write()) clean_testing = True else: testing_fn = training_fn assert testing_fn # Validate model file. fd, model_fn = tempfile.mkstemp() os.close(fd) if self._model_data: fout = open(model_fn, 'wb') fout.write(self._model_data) fout.close() # Call Weka Jar. args = dict( CP=CP, classifier_name=self.name, model_fn=model_fn, training_fn=training_fn, testing_fn=testing_fn, ckargs=self._get_ckargs_str(), ) if self._model_data: # Load existing model. cmd = ( "java -cp %(CP)s %(classifier_name)s -l \"%(model_fn)s\" " "-t \"%(training_fn)s\" -T \"%(testing_fn)s\" -d \"%(model_fn)s\"") % args else: # Create new model file. cmd = ( "java -cp %(CP)s %(classifier_name)s -t \"%(training_fn)s\" " "-T \"%(testing_fn)s\" -d \"%(model_fn)s\" %(ckargs)s") % args if verbose: print(cmd) p = Popen( cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=sys.platform != "win32") stdin, stdout, stderr = (p.stdin, p.stdout, p.stderr) stdout_str = stdout.read() stderr_str = stderr.read() self.last_training_stdout = stdout_str self.last_training_stderr = stderr_str if verbose: print('stdout:') print(stdout_str) print('stderr:') print(stderr_str) # exclude "Warning" lines not to raise an error for a simple warning stderr_str = '\n'.join(l for l in stderr_str.decode('utf8').split('\n') if not "Warning" in l) if stderr_str: raise TrainingError(stderr_str) # Save schema. if not self.schema: self.schema = arff.ArffFile.load(training_fn, schema_only=True).copy(schema_only=True) # Save model. with open(model_fn, 'rb') as fin: self._model_data = fin.read() assert self._model_data finally: # Cleanup files. if model_fn: os.remove(model_fn) if training_fn and clean_training: os.remove(training_fn) if testing_fn and clean_testing: os.remove(testing_fn)
[ "def", "train", "(", "self", ",", "training_data", ",", "testing_data", "=", "None", ",", "verbose", "=", "False", ")", ":", "model_fn", "=", "None", "training_fn", "=", "None", "clean_training", "=", "False", "testing_fn", "=", "None", "clean_testing", "=",...
Updates the classifier with new data.
[ "Updates", "the", "classifier", "with", "new", "data", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/classifiers.py#L312-L417
train
chrisspen/weka
weka/classifiers.py
Classifier.predict
def predict(self, query_data, verbose=False, distribution=False, cleanup=True): """ Iterates over the predicted values and probability (if supported). Each iteration yields a tuple of the form (prediction, probability). If the file is a test file (i.e. contains no query variables), then the tuple will be of the form (prediction, actual). See http://weka.wikispaces.com/Making+predictions for further explanation on interpreting Weka prediction output. """ model_fn = None query_fn = None clean_query = False stdout = None try: # Validate query data. if isinstance(query_data, basestring): assert os.path.isfile(query_data) query_fn = query_data else: #assert isinstance(query_data, arff.ArffFile) #TODO: doesn't work in Python 3.*? assert type(query_data).__name__ == 'ArffFile', 'Must be of type ArffFile, not "%s"' % type(query_data).__name__ fd, query_fn = tempfile.mkstemp(suffix='.arff') if verbose: print('writing', query_fn) os.close(fd) open(query_fn, 'w').write(query_data.write()) clean_query = True assert query_fn # Validate model file. fd, model_fn = tempfile.mkstemp() os.close(fd) assert self._model_data, "You must train this classifier before predicting." fout = open(model_fn, 'wb') fout.write(self._model_data) fout.close() # print(open(model_fn).read() # print(open(query_fn).read() # Call Weka Jar. args = dict( CP=CP, classifier_name=self.name, model_fn=model_fn, query_fn=query_fn, #ckargs = self._get_ckargs_str(), distribution=('-distribution' if distribution else ''), ) cmd = ("java -cp %(CP)s %(classifier_name)s -p 0 %(distribution)s -l \"%(model_fn)s\" -T \"%(query_fn)s\"") % args if verbose: print(cmd) p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) stdin, stdout, stderr = (p.stdin, p.stdout, p.stderr) stdout_str = stdout.read() stderr_str = stderr.read() if verbose: print('stdout:') print(stdout_str) print('stderr:') print(stderr_str) if stderr_str: raise PredictionError(stderr_str) if stdout_str: # inst# actual predicted error prediction #header = 'inst,actual,predicted,error'.split(',') query = arff.ArffFile.load(query_fn) query_variables = [ query.attributes[i] for i, v in enumerate(query.data[0]) if v == arff.MISSING] if not query_variables: query_variables = [query.attributes[-1]] # assert query_variables, \ # "There must be at least one query variable in the query." if verbose: print('query_variables:', query_variables) header = 'predicted'.split(',') # sample line: 1 1:? 4:36 + 1 # Expected output without distribution: #=== Predictions on test data === # # inst# actual predicted error prediction # 1 1:? 11:Acer_tr + 1 #=== Predictions on test data === # # inst# actual predicted error # 1 ? 7 ? #=== Predictions on test data === # # inst# actual predicted error prediction # 1 1:? 1:0 0.99 # 2 1:? 1:0 0.99 # 3 1:? 1:0 0.99 # 4 1:? 1:0 0.99 # 5 1:? 1:0 0.99 # Expected output with distribution: #=== Predictions on test data === # # inst# actual predicted error distribution # 1 1:? 11:Acer_tr + 0,0,0,0,0,0,0,0,0,0,*1,0,0,0,0,0... # Expected output with simple format: # inst# actual predicted error # 1 ? -3.417 ? q = re.findall( r'J48 pruned tree\s+\-+:\s+([0-9]+)\s+', stdout_str.decode('utf-8'), re.MULTILINE|re.DOTALL) if q: class_label = q[0] prob = 1.0 yield PredictionResult( actual=None, predicted=class_label, probability=prob,) elif re.findall(r'error\s+(?:distribution|prediction)', stdout_str.decode('utf-8')): # Check for distribution output. matches = re.findall( r"^\s*[0-9\.]+\s+[a-zA-Z0-9\.\?\:]+\s+(?P<cls_value>[a-zA-Z0-9_\.\?\:]+)\s+\+?\s+(?P<prob>[a-zA-Z0-9\.\?\,\*]+)", stdout_str.decode('utf-8'), re.MULTILINE) assert matches, ("No results found matching distribution pattern in stdout: %s") % stdout_str for match in matches: prediction, prob = match class_index, class_label = prediction.split(':') class_index = int(class_index) if distribution: # Convert list of probabilities into a hash linking the prob # to the associated class value. prob = dict(zip( query.attribute_data[query.attributes[-1]], map(float, prob.replace('*', '').split(',')))) else: prob = float(prob) class_label = query.attribute_data[query.attributes[-1]][class_index-1] yield PredictionResult( actual=None, predicted=class_label, probability=prob,) else: # Otherwise, assume a simple output. matches = re.findall( # inst# actual predicted r"^\s*([0-9\.]+)\s+([a-zA-Z0-9\-\.\?\:]+)\s+([a-zA-Z0-9\-_\.\?\:]+)\s+", stdout_str.decode('utf-8'), re.MULTILINE) assert matches, "No results found matching simple pattern in stdout: %s" % stdout_str #print('matches:',len(matches) for match in matches: inst, actual, predicted = match class_name = query.attributes[-1] actual_value = query.get_attribute_value(class_name, actual) predicted_value = query.get_attribute_value(class_name, predicted) yield PredictionResult( actual=actual_value, predicted=predicted_value, probability=None,) finally: # Cleanup files. if cleanup: if model_fn: self._model_data = open(model_fn, 'rb').read() os.remove(model_fn) if query_fn and clean_query: os.remove(query_fn)
python
def predict(self, query_data, verbose=False, distribution=False, cleanup=True): """ Iterates over the predicted values and probability (if supported). Each iteration yields a tuple of the form (prediction, probability). If the file is a test file (i.e. contains no query variables), then the tuple will be of the form (prediction, actual). See http://weka.wikispaces.com/Making+predictions for further explanation on interpreting Weka prediction output. """ model_fn = None query_fn = None clean_query = False stdout = None try: # Validate query data. if isinstance(query_data, basestring): assert os.path.isfile(query_data) query_fn = query_data else: #assert isinstance(query_data, arff.ArffFile) #TODO: doesn't work in Python 3.*? assert type(query_data).__name__ == 'ArffFile', 'Must be of type ArffFile, not "%s"' % type(query_data).__name__ fd, query_fn = tempfile.mkstemp(suffix='.arff') if verbose: print('writing', query_fn) os.close(fd) open(query_fn, 'w').write(query_data.write()) clean_query = True assert query_fn # Validate model file. fd, model_fn = tempfile.mkstemp() os.close(fd) assert self._model_data, "You must train this classifier before predicting." fout = open(model_fn, 'wb') fout.write(self._model_data) fout.close() # print(open(model_fn).read() # print(open(query_fn).read() # Call Weka Jar. args = dict( CP=CP, classifier_name=self.name, model_fn=model_fn, query_fn=query_fn, #ckargs = self._get_ckargs_str(), distribution=('-distribution' if distribution else ''), ) cmd = ("java -cp %(CP)s %(classifier_name)s -p 0 %(distribution)s -l \"%(model_fn)s\" -T \"%(query_fn)s\"") % args if verbose: print(cmd) p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) stdin, stdout, stderr = (p.stdin, p.stdout, p.stderr) stdout_str = stdout.read() stderr_str = stderr.read() if verbose: print('stdout:') print(stdout_str) print('stderr:') print(stderr_str) if stderr_str: raise PredictionError(stderr_str) if stdout_str: # inst# actual predicted error prediction #header = 'inst,actual,predicted,error'.split(',') query = arff.ArffFile.load(query_fn) query_variables = [ query.attributes[i] for i, v in enumerate(query.data[0]) if v == arff.MISSING] if not query_variables: query_variables = [query.attributes[-1]] # assert query_variables, \ # "There must be at least one query variable in the query." if verbose: print('query_variables:', query_variables) header = 'predicted'.split(',') # sample line: 1 1:? 4:36 + 1 # Expected output without distribution: #=== Predictions on test data === # # inst# actual predicted error prediction # 1 1:? 11:Acer_tr + 1 #=== Predictions on test data === # # inst# actual predicted error # 1 ? 7 ? #=== Predictions on test data === # # inst# actual predicted error prediction # 1 1:? 1:0 0.99 # 2 1:? 1:0 0.99 # 3 1:? 1:0 0.99 # 4 1:? 1:0 0.99 # 5 1:? 1:0 0.99 # Expected output with distribution: #=== Predictions on test data === # # inst# actual predicted error distribution # 1 1:? 11:Acer_tr + 0,0,0,0,0,0,0,0,0,0,*1,0,0,0,0,0... # Expected output with simple format: # inst# actual predicted error # 1 ? -3.417 ? q = re.findall( r'J48 pruned tree\s+\-+:\s+([0-9]+)\s+', stdout_str.decode('utf-8'), re.MULTILINE|re.DOTALL) if q: class_label = q[0] prob = 1.0 yield PredictionResult( actual=None, predicted=class_label, probability=prob,) elif re.findall(r'error\s+(?:distribution|prediction)', stdout_str.decode('utf-8')): # Check for distribution output. matches = re.findall( r"^\s*[0-9\.]+\s+[a-zA-Z0-9\.\?\:]+\s+(?P<cls_value>[a-zA-Z0-9_\.\?\:]+)\s+\+?\s+(?P<prob>[a-zA-Z0-9\.\?\,\*]+)", stdout_str.decode('utf-8'), re.MULTILINE) assert matches, ("No results found matching distribution pattern in stdout: %s") % stdout_str for match in matches: prediction, prob = match class_index, class_label = prediction.split(':') class_index = int(class_index) if distribution: # Convert list of probabilities into a hash linking the prob # to the associated class value. prob = dict(zip( query.attribute_data[query.attributes[-1]], map(float, prob.replace('*', '').split(',')))) else: prob = float(prob) class_label = query.attribute_data[query.attributes[-1]][class_index-1] yield PredictionResult( actual=None, predicted=class_label, probability=prob,) else: # Otherwise, assume a simple output. matches = re.findall( # inst# actual predicted r"^\s*([0-9\.]+)\s+([a-zA-Z0-9\-\.\?\:]+)\s+([a-zA-Z0-9\-_\.\?\:]+)\s+", stdout_str.decode('utf-8'), re.MULTILINE) assert matches, "No results found matching simple pattern in stdout: %s" % stdout_str #print('matches:',len(matches) for match in matches: inst, actual, predicted = match class_name = query.attributes[-1] actual_value = query.get_attribute_value(class_name, actual) predicted_value = query.get_attribute_value(class_name, predicted) yield PredictionResult( actual=actual_value, predicted=predicted_value, probability=None,) finally: # Cleanup files. if cleanup: if model_fn: self._model_data = open(model_fn, 'rb').read() os.remove(model_fn) if query_fn and clean_query: os.remove(query_fn)
[ "def", "predict", "(", "self", ",", "query_data", ",", "verbose", "=", "False", ",", "distribution", "=", "False", ",", "cleanup", "=", "True", ")", ":", "model_fn", "=", "None", "query_fn", "=", "None", "clean_query", "=", "False", "stdout", "=", "None"...
Iterates over the predicted values and probability (if supported). Each iteration yields a tuple of the form (prediction, probability). If the file is a test file (i.e. contains no query variables), then the tuple will be of the form (prediction, actual). See http://weka.wikispaces.com/Making+predictions for further explanation on interpreting Weka prediction output.
[ "Iterates", "over", "the", "predicted", "values", "and", "probability", "(", "if", "supported", ")", ".", "Each", "iteration", "yields", "a", "tuple", "of", "the", "form", "(", "prediction", "probability", ")", ".", "If", "the", "file", "is", "a", "test", ...
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/classifiers.py#L419-L592
train
chrisspen/weka
weka/classifiers.py
EnsembleClassifier.get_training_coverage
def get_training_coverage(self): """ Returns a ratio of classifiers that were able to be trained successfully. """ total = len(self.training_results) i = sum(1 for data in self.training_results.values() if not isinstance(data, basestring)) return i/float(total)
python
def get_training_coverage(self): """ Returns a ratio of classifiers that were able to be trained successfully. """ total = len(self.training_results) i = sum(1 for data in self.training_results.values() if not isinstance(data, basestring)) return i/float(total)
[ "def", "get_training_coverage", "(", "self", ")", ":", "total", "=", "len", "(", "self", ".", "training_results", ")", "i", "=", "sum", "(", "1", "for", "data", "in", "self", ".", "training_results", ".", "values", "(", ")", "if", "not", "isinstance", ...
Returns a ratio of classifiers that were able to be trained successfully.
[ "Returns", "a", "ratio", "of", "classifiers", "that", "were", "able", "to", "be", "trained", "successfully", "." ]
c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b
https://github.com/chrisspen/weka/blob/c86fc4b8eef1afd56f89ec28283bdf9e2fdc453b/weka/classifiers.py#L640-L646
train
huntrar/scrape
scrape/crawler.py
Crawler.get_new_links
def get_new_links(self, url, resp): """Get new links from a URL and filter them.""" links_on_page = resp.xpath('//a/@href') links = [utils.clean_url(u, url) for u in links_on_page] # Remove non-links through filtering by protocol links = [x for x in links if utils.check_protocol(x)] # Restrict new URLs by the domain of the input URL if not self.args['nonstrict']: domain = utils.get_domain(url) links = [x for x in links if utils.get_domain(x) == domain] # Filter URLs by regex keywords, if any if self.args['crawl']: links = utils.re_filter(links, self.args['crawl']) return links
python
def get_new_links(self, url, resp): """Get new links from a URL and filter them.""" links_on_page = resp.xpath('//a/@href') links = [utils.clean_url(u, url) for u in links_on_page] # Remove non-links through filtering by protocol links = [x for x in links if utils.check_protocol(x)] # Restrict new URLs by the domain of the input URL if not self.args['nonstrict']: domain = utils.get_domain(url) links = [x for x in links if utils.get_domain(x) == domain] # Filter URLs by regex keywords, if any if self.args['crawl']: links = utils.re_filter(links, self.args['crawl']) return links
[ "def", "get_new_links", "(", "self", ",", "url", ",", "resp", ")", ":", "links_on_page", "=", "resp", ".", "xpath", "(", "'//a/@href'", ")", "links", "=", "[", "utils", ".", "clean_url", "(", "u", ",", "url", ")", "for", "u", "in", "links_on_page", "...
Get new links from a URL and filter them.
[ "Get", "new", "links", "from", "a", "URL", "and", "filter", "them", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/crawler.py#L20-L36
train
huntrar/scrape
scrape/crawler.py
Crawler.page_crawled
def page_crawled(self, page_resp): """Check if page has been crawled by hashing its text content. Add new pages to the page cache. Return whether page was found in cache. """ page_text = utils.parse_text(page_resp) page_hash = utils.hash_text(''.join(page_text)) if page_hash not in self.page_cache: utils.cache_page(self.page_cache, page_hash, self.args['cache_size']) return False return True
python
def page_crawled(self, page_resp): """Check if page has been crawled by hashing its text content. Add new pages to the page cache. Return whether page was found in cache. """ page_text = utils.parse_text(page_resp) page_hash = utils.hash_text(''.join(page_text)) if page_hash not in self.page_cache: utils.cache_page(self.page_cache, page_hash, self.args['cache_size']) return False return True
[ "def", "page_crawled", "(", "self", ",", "page_resp", ")", ":", "page_text", "=", "utils", ".", "parse_text", "(", "page_resp", ")", "page_hash", "=", "utils", ".", "hash_text", "(", "''", ".", "join", "(", "page_text", ")", ")", "if", "page_hash", "not"...
Check if page has been crawled by hashing its text content. Add new pages to the page cache. Return whether page was found in cache.
[ "Check", "if", "page", "has", "been", "crawled", "by", "hashing", "its", "text", "content", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/crawler.py#L42-L53
train
huntrar/scrape
scrape/crawler.py
Crawler.crawl_links
def crawl_links(self, seed_url=None): """Find new links given a seed URL and follow them breadth-first. Save page responses as PART.html files. Return the PART.html filenames created during crawling. """ if seed_url is not None: self.seed_url = seed_url if self.seed_url is None: sys.stderr.write('Crawling requires a seed URL.\n') return [] prev_part_num = utils.get_num_part_files() crawled_links = set() uncrawled_links = OrderedSet() uncrawled_links.add(self.seed_url) try: while uncrawled_links: # Check limit on number of links and pages to crawl if self.limit_reached(len(crawled_links)): break url = uncrawled_links.pop(last=False) # Remove protocol, fragments, etc. to get unique URLs unique_url = utils.remove_protocol(utils.clean_url(url)) if unique_url not in crawled_links: raw_resp = utils.get_raw_resp(url) if raw_resp is None: if not self.args['quiet']: sys.stderr.write('Failed to parse {0}.\n'.format(url)) continue resp = lh.fromstring(raw_resp) if self.page_crawled(resp): continue crawled_links.add(unique_url) new_links = self.get_new_links(url, resp) uncrawled_links.update(new_links) if not self.args['quiet']: print('Crawled {0} (#{1}).'.format(url, len(crawled_links))) # Write page response to PART.html file utils.write_part_file(self.args, url, raw_resp, resp, len(crawled_links)) except (KeyboardInterrupt, EOFError): pass curr_part_num = utils.get_num_part_files() return utils.get_part_filenames(curr_part_num, prev_part_num)
python
def crawl_links(self, seed_url=None): """Find new links given a seed URL and follow them breadth-first. Save page responses as PART.html files. Return the PART.html filenames created during crawling. """ if seed_url is not None: self.seed_url = seed_url if self.seed_url is None: sys.stderr.write('Crawling requires a seed URL.\n') return [] prev_part_num = utils.get_num_part_files() crawled_links = set() uncrawled_links = OrderedSet() uncrawled_links.add(self.seed_url) try: while uncrawled_links: # Check limit on number of links and pages to crawl if self.limit_reached(len(crawled_links)): break url = uncrawled_links.pop(last=False) # Remove protocol, fragments, etc. to get unique URLs unique_url = utils.remove_protocol(utils.clean_url(url)) if unique_url not in crawled_links: raw_resp = utils.get_raw_resp(url) if raw_resp is None: if not self.args['quiet']: sys.stderr.write('Failed to parse {0}.\n'.format(url)) continue resp = lh.fromstring(raw_resp) if self.page_crawled(resp): continue crawled_links.add(unique_url) new_links = self.get_new_links(url, resp) uncrawled_links.update(new_links) if not self.args['quiet']: print('Crawled {0} (#{1}).'.format(url, len(crawled_links))) # Write page response to PART.html file utils.write_part_file(self.args, url, raw_resp, resp, len(crawled_links)) except (KeyboardInterrupt, EOFError): pass curr_part_num = utils.get_num_part_files() return utils.get_part_filenames(curr_part_num, prev_part_num)
[ "def", "crawl_links", "(", "self", ",", "seed_url", "=", "None", ")", ":", "if", "seed_url", "is", "not", "None", ":", "self", ".", "seed_url", "=", "seed_url", "if", "self", ".", "seed_url", "is", "None", ":", "sys", ".", "stderr", ".", "write", "("...
Find new links given a seed URL and follow them breadth-first. Save page responses as PART.html files. Return the PART.html filenames created during crawling.
[ "Find", "new", "links", "given", "a", "seed", "URL", "and", "follow", "them", "breadth", "-", "first", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/crawler.py#L55-L105
train
huntrar/scrape
scrape/utils.py
get_proxies
def get_proxies(): """Get available proxies to use with requests library.""" proxies = getproxies() filtered_proxies = {} for key, value in proxies.items(): if key.startswith('http://'): if not value.startswith('http://'): filtered_proxies[key] = 'http://{0}'.format(value) else: filtered_proxies[key] = value return filtered_proxies
python
def get_proxies(): """Get available proxies to use with requests library.""" proxies = getproxies() filtered_proxies = {} for key, value in proxies.items(): if key.startswith('http://'): if not value.startswith('http://'): filtered_proxies[key] = 'http://{0}'.format(value) else: filtered_proxies[key] = value return filtered_proxies
[ "def", "get_proxies", "(", ")", ":", "proxies", "=", "getproxies", "(", ")", "filtered_proxies", "=", "{", "}", "for", "key", ",", "value", "in", "proxies", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "'http://'", ")", ":", "if"...
Get available proxies to use with requests library.
[ "Get", "available", "proxies", "to", "use", "with", "requests", "library", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L63-L73
train
huntrar/scrape
scrape/utils.py
get_resp
def get_resp(url): """Get webpage response as an lxml.html.HtmlElement object.""" try: headers = {'User-Agent': random.choice(USER_AGENTS)} try: request = requests.get(url, headers=headers, proxies=get_proxies()) except MissingSchema: url = add_protocol(url) request = requests.get(url, headers=headers, proxies=get_proxies()) return lh.fromstring(request.text.encode('utf-8') if PY2 else request.text) except Exception: sys.stderr.write('Failed to retrieve {0}.\n'.format(url)) raise
python
def get_resp(url): """Get webpage response as an lxml.html.HtmlElement object.""" try: headers = {'User-Agent': random.choice(USER_AGENTS)} try: request = requests.get(url, headers=headers, proxies=get_proxies()) except MissingSchema: url = add_protocol(url) request = requests.get(url, headers=headers, proxies=get_proxies()) return lh.fromstring(request.text.encode('utf-8') if PY2 else request.text) except Exception: sys.stderr.write('Failed to retrieve {0}.\n'.format(url)) raise
[ "def", "get_resp", "(", "url", ")", ":", "try", ":", "headers", "=", "{", "'User-Agent'", ":", "random", ".", "choice", "(", "USER_AGENTS", ")", "}", "try", ":", "request", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ",",...
Get webpage response as an lxml.html.HtmlElement object.
[ "Get", "webpage", "response", "as", "an", "lxml", ".", "html", ".", "HtmlElement", "object", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L76-L88
train
huntrar/scrape
scrape/utils.py
enable_cache
def enable_cache(): """Enable requests library cache.""" try: import requests_cache except ImportError as err: sys.stderr.write('Failed to enable cache: {0}\n'.format(str(err))) return if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR) requests_cache.install_cache(CACHE_FILE)
python
def enable_cache(): """Enable requests library cache.""" try: import requests_cache except ImportError as err: sys.stderr.write('Failed to enable cache: {0}\n'.format(str(err))) return if not os.path.exists(CACHE_DIR): os.makedirs(CACHE_DIR) requests_cache.install_cache(CACHE_FILE)
[ "def", "enable_cache", "(", ")", ":", "try", ":", "import", "requests_cache", "except", "ImportError", "as", "err", ":", "sys", ".", "stderr", ".", "write", "(", "'Failed to enable cache: {0}\\n'", ".", "format", "(", "str", "(", "err", ")", ")", ")", "ret...
Enable requests library cache.
[ "Enable", "requests", "library", "cache", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L106-L115
train
huntrar/scrape
scrape/utils.py
hash_text
def hash_text(text): """Return MD5 hash of a string.""" md5 = hashlib.md5() md5.update(text) return md5.hexdigest()
python
def hash_text(text): """Return MD5 hash of a string.""" md5 = hashlib.md5() md5.update(text) return md5.hexdigest()
[ "def", "hash_text", "(", "text", ")", ":", "md5", "=", "hashlib", ".", "md5", "(", ")", "md5", ".", "update", "(", "text", ")", "return", "md5", ".", "hexdigest", "(", ")" ]
Return MD5 hash of a string.
[ "Return", "MD5", "hash", "of", "a", "string", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L127-L131
train
huntrar/scrape
scrape/utils.py
cache_page
def cache_page(page_cache, page_hash, cache_size): """Add a page to the page cache.""" page_cache.append(page_hash) if len(page_cache) > cache_size: page_cache.pop(0)
python
def cache_page(page_cache, page_hash, cache_size): """Add a page to the page cache.""" page_cache.append(page_hash) if len(page_cache) > cache_size: page_cache.pop(0)
[ "def", "cache_page", "(", "page_cache", ",", "page_hash", ",", "cache_size", ")", ":", "page_cache", ".", "append", "(", "page_hash", ")", "if", "len", "(", "page_cache", ")", ">", "cache_size", ":", "page_cache", ".", "pop", "(", "0", ")" ]
Add a page to the page cache.
[ "Add", "a", "page", "to", "the", "page", "cache", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L134-L138
train
huntrar/scrape
scrape/utils.py
re_filter
def re_filter(text, regexps): """Filter text using regular expressions.""" if not regexps: return text matched_text = [] compiled_regexps = [re.compile(x) for x in regexps] for line in text: if line in matched_text: continue for regexp in compiled_regexps: found = regexp.search(line) if found and found.group(): matched_text.append(line) return matched_text or text
python
def re_filter(text, regexps): """Filter text using regular expressions.""" if not regexps: return text matched_text = [] compiled_regexps = [re.compile(x) for x in regexps] for line in text: if line in matched_text: continue for regexp in compiled_regexps: found = regexp.search(line) if found and found.group(): matched_text.append(line) return matched_text or text
[ "def", "re_filter", "(", "text", ",", "regexps", ")", ":", "if", "not", "regexps", ":", "return", "text", "matched_text", "=", "[", "]", "compiled_regexps", "=", "[", "re", ".", "compile", "(", "x", ")", "for", "x", "in", "regexps", "]", "for", "line...
Filter text using regular expressions.
[ "Filter", "text", "using", "regular", "expressions", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L144-L160
train
huntrar/scrape
scrape/utils.py
remove_whitespace
def remove_whitespace(text): """Remove unnecessary whitespace while keeping logical structure. Keyword arguments: text -- text to remove whitespace from (list) Retain paragraph structure but remove other whitespace, such as between words on a line and at the start and end of the text. """ clean_text = [] curr_line = '' # Remove any newlines that follow two lines of whitespace consecutively # Also remove whitespace at start and end of text while text: if not curr_line: # Find the first line that is not whitespace and add it curr_line = text.pop(0) while not curr_line.strip() and text: curr_line = text.pop(0) if curr_line.strip(): clean_text.append(curr_line) else: # Filter the rest of the lines curr_line = text.pop(0) if not text: # Add the final line if it is not whitespace if curr_line.strip(): clean_text.append(curr_line) continue if curr_line.strip(): clean_text.append(curr_line) else: # If the current line is whitespace then make sure there is # no more than one consecutive line of whitespace following if not text[0].strip(): if len(text) > 1 and text[1].strip(): clean_text.append(curr_line) else: clean_text.append(curr_line) # Now filter each individual line for extraneous whitespace cleaner_text = [] for line in clean_text: clean_line = ' '.join(line.split()) if not clean_line.strip(): clean_line += '\n' cleaner_text.append(clean_line) return cleaner_text
python
def remove_whitespace(text): """Remove unnecessary whitespace while keeping logical structure. Keyword arguments: text -- text to remove whitespace from (list) Retain paragraph structure but remove other whitespace, such as between words on a line and at the start and end of the text. """ clean_text = [] curr_line = '' # Remove any newlines that follow two lines of whitespace consecutively # Also remove whitespace at start and end of text while text: if not curr_line: # Find the first line that is not whitespace and add it curr_line = text.pop(0) while not curr_line.strip() and text: curr_line = text.pop(0) if curr_line.strip(): clean_text.append(curr_line) else: # Filter the rest of the lines curr_line = text.pop(0) if not text: # Add the final line if it is not whitespace if curr_line.strip(): clean_text.append(curr_line) continue if curr_line.strip(): clean_text.append(curr_line) else: # If the current line is whitespace then make sure there is # no more than one consecutive line of whitespace following if not text[0].strip(): if len(text) > 1 and text[1].strip(): clean_text.append(curr_line) else: clean_text.append(curr_line) # Now filter each individual line for extraneous whitespace cleaner_text = [] for line in clean_text: clean_line = ' '.join(line.split()) if not clean_line.strip(): clean_line += '\n' cleaner_text.append(clean_line) return cleaner_text
[ "def", "remove_whitespace", "(", "text", ")", ":", "clean_text", "=", "[", "]", "curr_line", "=", "''", "# Remove any newlines that follow two lines of whitespace consecutively", "# Also remove whitespace at start and end of text", "while", "text", ":", "if", "not", "curr_lin...
Remove unnecessary whitespace while keeping logical structure. Keyword arguments: text -- text to remove whitespace from (list) Retain paragraph structure but remove other whitespace, such as between words on a line and at the start and end of the text.
[ "Remove", "unnecessary", "whitespace", "while", "keeping", "logical", "structure", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L163-L211
train
huntrar/scrape
scrape/utils.py
parse_text
def parse_text(infile, xpath=None, filter_words=None, attributes=None): """Filter text using XPath, regex keywords, and tag attributes. Keyword arguments: infile -- HTML or text content to parse (list) xpath -- an XPath expression (str) filter_words -- regex keywords (list) attributes -- HTML tag attributes (list) Return a list of strings of text. """ infiles = [] text = [] if xpath is not None: infile = parse_html(infile, xpath) if isinstance(infile, list): if isinstance(infile[0], lh.HtmlElement): infiles = list(infile) else: text = [line + '\n' for line in infile] elif isinstance(infile, lh.HtmlElement): infiles = [infile] else: text = [infile] else: infiles = [infile] if attributes is not None: attributes = [clean_attr(x) for x in attributes] attributes = [x for x in attributes if x] else: attributes = ['text()'] if not text: text_xpath = '//*[not(self::script) and not(self::style)]' for attr in attributes: for infile in infiles: if isinstance(infile, lh.HtmlElement): new_text = infile.xpath('{0}/{1}'.format(text_xpath, attr)) else: # re.split preserves delimiters place in the list new_text = [x for x in re.split('(\n)', infile) if x] text += new_text if filter_words is not None: text = re_filter(text, filter_words) return [''.join(x for x in line if x in string.printable) for line in remove_whitespace(text) if line]
python
def parse_text(infile, xpath=None, filter_words=None, attributes=None): """Filter text using XPath, regex keywords, and tag attributes. Keyword arguments: infile -- HTML or text content to parse (list) xpath -- an XPath expression (str) filter_words -- regex keywords (list) attributes -- HTML tag attributes (list) Return a list of strings of text. """ infiles = [] text = [] if xpath is not None: infile = parse_html(infile, xpath) if isinstance(infile, list): if isinstance(infile[0], lh.HtmlElement): infiles = list(infile) else: text = [line + '\n' for line in infile] elif isinstance(infile, lh.HtmlElement): infiles = [infile] else: text = [infile] else: infiles = [infile] if attributes is not None: attributes = [clean_attr(x) for x in attributes] attributes = [x for x in attributes if x] else: attributes = ['text()'] if not text: text_xpath = '//*[not(self::script) and not(self::style)]' for attr in attributes: for infile in infiles: if isinstance(infile, lh.HtmlElement): new_text = infile.xpath('{0}/{1}'.format(text_xpath, attr)) else: # re.split preserves delimiters place in the list new_text = [x for x in re.split('(\n)', infile) if x] text += new_text if filter_words is not None: text = re_filter(text, filter_words) return [''.join(x for x in line if x in string.printable) for line in remove_whitespace(text) if line]
[ "def", "parse_text", "(", "infile", ",", "xpath", "=", "None", ",", "filter_words", "=", "None", ",", "attributes", "=", "None", ")", ":", "infiles", "=", "[", "]", "text", "=", "[", "]", "if", "xpath", "is", "not", "None", ":", "infile", "=", "par...
Filter text using XPath, regex keywords, and tag attributes. Keyword arguments: infile -- HTML or text content to parse (list) xpath -- an XPath expression (str) filter_words -- regex keywords (list) attributes -- HTML tag attributes (list) Return a list of strings of text.
[ "Filter", "text", "using", "XPath", "regex", "keywords", "and", "tag", "attributes", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L214-L261
train
huntrar/scrape
scrape/utils.py
get_parsed_text
def get_parsed_text(args, infilename): """Parse and return text content of infiles. Keyword arguments: args -- program arguments (dict) infilenames -- name of user-inputted and/or downloaded file (str) Return a list of strings of text. """ parsed_text = [] if infilename.endswith('.html'): # Convert HTML to lxml object for content parsing html = lh.fromstring(read_files(infilename)) text = None else: html = None text = read_files(infilename) if html is not None: parsed_text = parse_text(html, args['xpath'], args['filter'], args['attributes']) elif text is not None: parsed_text = parse_text(text, args['xpath'], args['filter']) else: if not args['quiet']: sys.stderr.write('Failed to parse text from {0}.\n' .format(infilename)) return parsed_text
python
def get_parsed_text(args, infilename): """Parse and return text content of infiles. Keyword arguments: args -- program arguments (dict) infilenames -- name of user-inputted and/or downloaded file (str) Return a list of strings of text. """ parsed_text = [] if infilename.endswith('.html'): # Convert HTML to lxml object for content parsing html = lh.fromstring(read_files(infilename)) text = None else: html = None text = read_files(infilename) if html is not None: parsed_text = parse_text(html, args['xpath'], args['filter'], args['attributes']) elif text is not None: parsed_text = parse_text(text, args['xpath'], args['filter']) else: if not args['quiet']: sys.stderr.write('Failed to parse text from {0}.\n' .format(infilename)) return parsed_text
[ "def", "get_parsed_text", "(", "args", ",", "infilename", ")", ":", "parsed_text", "=", "[", "]", "if", "infilename", ".", "endswith", "(", "'.html'", ")", ":", "# Convert HTML to lxml object for content parsing", "html", "=", "lh", ".", "fromstring", "(", "read...
Parse and return text content of infiles. Keyword arguments: args -- program arguments (dict) infilenames -- name of user-inputted and/or downloaded file (str) Return a list of strings of text.
[ "Parse", "and", "return", "text", "content", "of", "infiles", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L264-L291
train
huntrar/scrape
scrape/utils.py
parse_html
def parse_html(infile, xpath): """Filter HTML using XPath.""" if not isinstance(infile, lh.HtmlElement): infile = lh.fromstring(infile) infile = infile.xpath(xpath) if not infile: raise ValueError('XPath {0} returned no results.'.format(xpath)) return infile
python
def parse_html(infile, xpath): """Filter HTML using XPath.""" if not isinstance(infile, lh.HtmlElement): infile = lh.fromstring(infile) infile = infile.xpath(xpath) if not infile: raise ValueError('XPath {0} returned no results.'.format(xpath)) return infile
[ "def", "parse_html", "(", "infile", ",", "xpath", ")", ":", "if", "not", "isinstance", "(", "infile", ",", "lh", ".", "HtmlElement", ")", ":", "infile", "=", "lh", ".", "fromstring", "(", "infile", ")", "infile", "=", "infile", ".", "xpath", "(", "xp...
Filter HTML using XPath.
[ "Filter", "HTML", "using", "XPath", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L309-L316
train
huntrar/scrape
scrape/utils.py
clean_url
def clean_url(url, base_url=None): """Add base netloc and path to internal URLs and remove www, fragments.""" parsed_url = urlparse(url) fragment = '{url.fragment}'.format(url=parsed_url) if fragment: url = url.split(fragment)[0] # Identify internal URLs and fix their format netloc = '{url.netloc}'.format(url=parsed_url) if base_url is not None and not netloc: parsed_base = urlparse(base_url) split_base = '{url.scheme}://{url.netloc}{url.path}/'.format(url=parsed_base) url = urljoin(split_base, url) netloc = '{url.netloc}'.format(url=urlparse(url)) if 'www.' in netloc: url = url.replace(netloc, netloc.replace('www.', '')) return url.rstrip(string.punctuation)
python
def clean_url(url, base_url=None): """Add base netloc and path to internal URLs and remove www, fragments.""" parsed_url = urlparse(url) fragment = '{url.fragment}'.format(url=parsed_url) if fragment: url = url.split(fragment)[0] # Identify internal URLs and fix their format netloc = '{url.netloc}'.format(url=parsed_url) if base_url is not None and not netloc: parsed_base = urlparse(base_url) split_base = '{url.scheme}://{url.netloc}{url.path}/'.format(url=parsed_base) url = urljoin(split_base, url) netloc = '{url.netloc}'.format(url=urlparse(url)) if 'www.' in netloc: url = url.replace(netloc, netloc.replace('www.', '')) return url.rstrip(string.punctuation)
[ "def", "clean_url", "(", "url", ",", "base_url", "=", "None", ")", ":", "parsed_url", "=", "urlparse", "(", "url", ")", "fragment", "=", "'{url.fragment}'", ".", "format", "(", "url", "=", "parsed_url", ")", "if", "fragment", ":", "url", "=", "url", "....
Add base netloc and path to internal URLs and remove www, fragments.
[ "Add", "base", "netloc", "and", "path", "to", "internal", "URLs", "and", "remove", "www", "fragments", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L348-L366
train
huntrar/scrape
scrape/utils.py
add_url_suffix
def add_url_suffix(url): """Add .com suffix to URL if none found.""" url = url.rstrip('/') if not has_suffix(url): return '{0}.com'.format(url) return url
python
def add_url_suffix(url): """Add .com suffix to URL if none found.""" url = url.rstrip('/') if not has_suffix(url): return '{0}.com'.format(url) return url
[ "def", "add_url_suffix", "(", "url", ")", ":", "url", "=", "url", ".", "rstrip", "(", "'/'", ")", "if", "not", "has_suffix", "(", "url", ")", ":", "return", "'{0}.com'", ".", "format", "(", "url", ")", "return", "url" ]
Add .com suffix to URL if none found.
[ "Add", ".", "com", "suffix", "to", "URL", "if", "none", "found", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L374-L379
train
huntrar/scrape
scrape/utils.py
get_outfilename
def get_outfilename(url, domain=None): """Construct the output filename from domain and end of path.""" if domain is None: domain = get_domain(url) path = '{url.path}'.format(url=urlparse(url)) if '.' in path: tail_url = path.split('.')[-2] else: tail_url = path if tail_url: if '/' in tail_url: tail_pieces = [x for x in tail_url.split('/') if x] tail_url = tail_pieces[-1] # Keep length of return string below or equal to max_len max_len = 24 if domain: max_len -= (len(domain) + 1) if len(tail_url) > max_len: if '-' in tail_url: tail_pieces = [x for x in tail_url.split('-') if x] tail_url = tail_pieces.pop(0) if len(tail_url) > max_len: tail_url = tail_url[:max_len] else: # Add as many tail pieces that can fit tail_len = 0 for piece in tail_pieces: tail_len += len(piece) if tail_len <= max_len: tail_url += '-' + piece else: break else: tail_url = tail_url[:max_len] if domain: return '{0}-{1}'.format(domain, tail_url).lower() return tail_url return domain.lower()
python
def get_outfilename(url, domain=None): """Construct the output filename from domain and end of path.""" if domain is None: domain = get_domain(url) path = '{url.path}'.format(url=urlparse(url)) if '.' in path: tail_url = path.split('.')[-2] else: tail_url = path if tail_url: if '/' in tail_url: tail_pieces = [x for x in tail_url.split('/') if x] tail_url = tail_pieces[-1] # Keep length of return string below or equal to max_len max_len = 24 if domain: max_len -= (len(domain) + 1) if len(tail_url) > max_len: if '-' in tail_url: tail_pieces = [x for x in tail_url.split('-') if x] tail_url = tail_pieces.pop(0) if len(tail_url) > max_len: tail_url = tail_url[:max_len] else: # Add as many tail pieces that can fit tail_len = 0 for piece in tail_pieces: tail_len += len(piece) if tail_len <= max_len: tail_url += '-' + piece else: break else: tail_url = tail_url[:max_len] if domain: return '{0}-{1}'.format(domain, tail_url).lower() return tail_url return domain.lower()
[ "def", "get_outfilename", "(", "url", ",", "domain", "=", "None", ")", ":", "if", "domain", "is", "None", ":", "domain", "=", "get_domain", "(", "url", ")", "path", "=", "'{url.path}'", ".", "format", "(", "url", "=", "urlparse", "(", "url", ")", ")"...
Construct the output filename from domain and end of path.
[ "Construct", "the", "output", "filename", "from", "domain", "and", "end", "of", "path", "." ]
bf877f6da5df3ed0f2bea60a95acf7df63c88002
https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L385-L426
train