def get_settings(self, rule): """Get the settings.""" obj = { "bold": False, "italic": False, "underline": False, "foreground": None, "background": None, "border": None } if re.search(r"(?<!-)\bfont-weight\s*:\s*bold", rule) is not None: obj["bold"] = True if re.search(r"(?<!-)\bfont-style\s*:\s*italic", rule) is not None: obj["italic"] = True if re.search(r"(?<!-)\btext-decoration\s*:\s*underline", rule) is not None: obj["underline"] = True m = re.search(r"(?<!-)\bborder\s*:\s*[\d]+px\s*\w+\s*(?P<color>#[a-zA-z\d]{6}|#[a-zA-z\d]{3}|\w+)", rule) if m: color = m.group('color') obj["border"] = normalize_hex(color) if color.startswith('#') else name_to_hex(color) m = re.search(r"(?<!-)\bcolor\s*:\s*(?P<color>#[a-zA-z\d]{6}|#[a-zA-z\d]{3}|\w+)", rule) if m: color = m.group('color') obj["foreground"] = normalize_hex(color) if color.startswith('#') else name_to_hex(color) m = re.search(r"(?<!-)\bbackground-color\s*:\s*(?P<color>#[a-zA-z\d]{6}|#[a-zA-z\d]{3}|\w+)", rule) if m: color = m.group('color') obj["background"] = normalize_hex(color) if color.startswith('#') else name_to_hex(color) return obj
def getColor(args): if "rgb" in args: index = args.index("rgb") + 1 rgbs = [int(x) for x in args[index:index+3]] color = webcolors.rgb_to_hex(rgbs) elif len(args) == 1: if args[0][0] == "#": color = args[0] else: # Name? try: color = webcolors.name_to_hex(args[0]) # No idea what it is then... except: color = None else: # Multiple things in the background line surely one of them is hex or a word for a in args: if "#" == a[0]: try: # To confirm it is a real hex, convert to RGB and back color = webcolors.rgb_to_hex( webcolors.hex_to_rgb(a)) break except: pass else: try: color = webcolors.name_to_hex(a) break except: pass color = None return color
def convert_color_for_html_input_type_color(color): # Need to interpret named color into hexidecimal format if color is None: # Pick a color that works against either black or white color = webcolors.name_to_hex('green') elif color == 'None': color = webcolors.name_to_hex('green') elif not color.startswith("#"): color = webcolors.name_to_hex(color) assert color.startswith("#") return color
def find_contrast(soup, URL, first_bool, stylesheetName, fullCSSStyleLink, rule, socketio): TYPE = "accessibility for colorblind users" SEVERITY = "warning" inaccessible_colors = [] if first_bool: create_print_json(TYPE, socketio) cssString = rule.cssText if rule.style['color'] and rule.style['background-color']: color = str(rule.style['color']) backgroundColor = str(rule.style['background-color']) # dumb edge case if color == "#FFF" or color == "#fff": color = "#FFFFFF" if backgroundColor == "#FFF" or backgroundColor == "#fff": backgroundColor = "#FFFFFF" # get them both in hex if color.startswith("#") and len(str(color)) == 7: colorHex = color elif not color.startswith("rgb"): colorHex = webcolors.name_to_hex(color) else: # rgb colorHex = webcolors.rgb_to_hex(color) if backgroundColor.startswith("#") and len(str(backgroundColor)) == 7: backgroundHex = backgroundColor elif not backgroundColor.startswith("rgb"): backgroundHex = webcolors.name_to_hex(backgroundColor) else: backgroundHex = webcolors.rgb_to_hex(backgroundColor) # now we have them both in hex val = distinguish_hex(colorHex, backgroundHex) if val == []: # no issue return True else: text = "Bad contrast ratio between: " + color + " and " + backgroundColor + ". Consider changing them to similar colors: " + str( val) create_error_json(TYPE, SEVERITY, fullCSSStyleLink, text=text, meta=rule.cssText, socketio=socketio) return False
def colorChecker(backgroundColor, textColor): if backgroundColor is None: backgroundColor = "Gray" if textColor is None: textColor = "Black" # convert color name to rgb for contrast check textRGB = ([i / 255 for i in webcolors.name_to_rgb(textColor)]) # convert color name to rgb for contrast check backgroundRGB = ([i / 255 for i in webcolors.name_to_rgb(backgroundColor)]) # check contrast ratio if contrast.passes_AA(contrast.rgb(textRGB, backgroundRGB)): return webcolors.name_to_hex(backgroundColor), webcolors.name_to_hex( textColor) # if failed, set color to default return webcolors.name_to_hex("Gray"), webcolors.name_to_hex("Black")
def add_calendar(self, user_id, calendar_name, calendar_color): calendar_name = calendar_name.strip() if not 4 <= len(calendar_name) <= 30: return self.error_dict(1, "Calendar name must be at least 4 and up to 30 characters long..") try: webcolors.name_to_hex(calendar_color) except ValueError: return self.error_dict(1, "Unknown calendar color.") try: return self.success_dict('calendar_id', self._db.add_calendar(user_id, calendar_name, calendar_color)) except Exception: return self.error_dict(2, "Database error. Contact administrator.")
def css_name_hex(self, name: str): """Retrouve l'hex lié au nom de couleur (CSS3/HTML)""" try: hex = webcolors.name_to_hex(name) return self.format_color(hex, "0x") except: return False
def parse_color(color): c = str(color).lower().strip() for k, v in _COLOR_FILTERS.items(): c = c.replace(k, v) hex = None try: hc = '#' + c if not c.startswith('#') else c rgb = webcolors.hex_to_rgb(hc) if rgb: return hc.upper() except Exception: # probably not a hex already pass try: hex = webcolors.name_to_hex(c) except Exception: pass if '%' in c: try: hex = webcolors.rgb_percent_to_hex( (int(x.strip()) for x in c.split(','))) except Exception: pass else: try: hex = webcolors.rgb_to_hex((int(x.strip()) for x in c.split(','))) except Exception: pass return hex
def _valid_color(color): if color == None or color == "None": return "00000000" if re.match("[A-F0-9]+", color): return color else: return webcolors.name_to_hex(color)[1:]
def __init__(self, string: str) -> Color: if string in CSS3_NAMES_TO_HEX: self.name = string self.hex = name_to_hex(string, spec=CSS3) else: self.name = None self.hex = string
def _ensure_hex_color(self, color): if color is None: return None try: return webcolors.name_to_hex(color) except ValueError: return color
def _define_route_color(self, route): """ Overriden to support color names """ if not route.route_color == '#FFFFFF': route.route_color = webcolors.name_to_hex(route.route_color) return route.route_color[1:]
def ent_name_to_color(ent_name): # Excel doesn't process linear-gradient colors # "R" suffix is for reverse # purplish = 'linear-gradient(90deg, #aa9cfc, #fc9ce7)' # original # purplishR = 'linear-gradient(45deg, #fc9ce7, #aa9cfc)' # yellowish = 'linear-gradient(90deg, #f9fc9c, #fac945)' # greenish = 'linear-gradient(90deg, #cdfc9c, #5cfa45)' # aquaish = 'linear-gradient(90deg, #9cfcea, #3cd3e7)' # aquaishR = 'linear-gradient(45deg, #3cd3e7, #9cfcea)' # fuchsiaish = 'linear-gradient(90deg, #fc9cde, #ff5aa4)' purplish = '#aa9cfc' # original yellowish = '#f9fc9c' greenish = '#cdfc9c' aquaish = '#9cfcea' fuchsiaish = '#fc9cde' if ent_name.startswith('COM'): return purplish if ent_name.startswith('SCI'): return aquaish if ent_name.startswith('ORD'): return greenish if ent_name.startswith('FAMCOM'): return yellowish if ent_name.startswith('FAMSCI'): return fuchsiaish return webcolors.name_to_hex('HotPink'.lower())
def assembleEmbed( title="", desc="", titleUrl="", hexcolor="#2E66B6", webcolor="", thumbnailUrl="", authorName="", authorUrl="", authorIcon="", fields={}, footerText="", footerUrl="", imageUrl="" ): """Assembles an embed with the specified parameters.""" if len(webcolor) > 1: hexcolor = webcolors.name_to_hex(webcolor) hexcolor = hexcolor[1:] embed = discord.Embed(title=title, description=desc, url=titleUrl, color=int(hexcolor, 16)) embed.set_author(name=authorName, url=authorUrl, icon_url=authorIcon) embed.set_thumbnail(url=thumbnailUrl) for field in fields: embed.add_field(name=field['name'], value=field['value'], inline=(field['inline'] == "True")) embed.set_footer(text=footerText, icon_url=footerUrl) embed.set_image(url=imageUrl) return embed
def light_set(): data = request.json or request.form brightness = data.get('brightness') rgb = data.get('rgb') color = data.get('color') temp = data.get('temp') if brightness: print('Set brightness: {}'.format(brightness)) yeelight.set_brightness(int(brightness)) if rgb: print('Set rgb: {}'.format(rgb)) yeelight.set_rgb(rgb) elif color: color = color.replace(' ', '') print('Set color {}'.format(color)) try: rgb = webcolors.name_to_hex(color)[1:] except ValueError as e: return str(e) else: yeelight.set_rgb(rgb) elif temp: temp = int(temp) print('Set temp: {}'.format(temp)) yeelight.set_temp(temp) sse.publish(get_status(), type='update') return 'OK' if any((brightness, rgb, temp)) else 'FAIL'
def normalize_color(color_name): try: hex_value = webcolors.name_to_hex(color_name) rgb_value = webcolors.name_to_rgb(color_name) return str(hex_value), str(rgb_value) except: color_words = color_name.split(" ") for i in range(1, len(color_words)): try: word = " ".join(color_words[i:]) hex_value = webcolors.name_to_hex(word) rgb_value = webcolors.name_to_rgb(word) return str(hex_value), str(rgb_value) except: continue return None, None
def etsy_colors(request, color): try: color_hex = name_to_hex(color) except ValueError: raise Http404('Color not valid') etsy = Etsy(settings.ETSY_CONSUMER_KEY, settings.ETSY_SHARED_SECRET) response = etsy.show_listings(color=color_hex) results = response['results'] if not results: raise Http404('no results') listings = [] for item in results: listing = {} listing['url'] = item['url'] listing['title'] = item['title'] result = etsy.get_image_for_listing(item['listing_id']) image_url = result['results'][0]['url_170x135'] listing['image_url'] = image_url listings.append(listing) return {'listings': listings, 'color': color}
def light(): data = request.json or request.form brightness = data.get('brightness') rgb = data.get('rgb') color = data.get('color') temp = data.get('temp') if brightness: print('Set brightness: {}'.format(brightness)) yeelight.set_brightness(int(brightness)) if rgb: print('Set rgb: {}'.format(rgb)) yeelight.set_rgb(rgb) elif color: color = color.replace(' ', '') print('Set color {}'.format(color)) try: rgb = webcolors.name_to_hex(color)[1:] except ValueError as e: return str(e) else: yeelight.set_rgb(rgb) elif temp: print('Set temp: {}'.format(temp)) yeelight.set_temp(temp) sse.publish(get_status(), type='update') return 'OK' if any((brightness, rgb, temp)) else 'FAIL'
def upload(): if request.method == 'POST': color_data = [] try: userID = str(request.cookies.get('userID')) time = str(datetime.now()) f = request.files['file'] colors = colorgram.extract(f, 6) for item in colors: actual_name, closest_name, hex_code = get_colour_name(item.rgb) proportion = str(format(item.proportion * 100, '.2f')) + '%' color_data.append({ 'name': closest_name, 'hex_approx': hex_code, 'hex_actual': webcolors.name_to_hex(closest_name), 'proportion': proportion }) except: print("error in insert operation") return render_template('index.html', data=color_data, title='Home') finally: return render_template('index.html', data=color_data, title='Home')
def color_check(data): data = data.strip() # if it's a text color like "green" if data.isalpha(): try: HEX = webcolors.name_to_hex(data) except (ValueError): print(f"\tNot a valid text color: {data}") return False, "" # if it's a hex number, assume it is if it starts with # and length 7 elif (data[1:].isalnum() and data[0] == '#' and len(data) == 7): try: HEX = webcolors.hex_to_rgb(data) # just to test HEX = data except (ValueError): print(f"\tNot a valid text color: {data}") return False, "" # else assume it's invalid else: print(f"\tNot a valid text color: {data}") return False, "" # convert to integers and make it valid return True, HEX
async def convert(cls, ctx: typing.Union[AoiContext, SlashContext], arg: str) -> "AoiColor": # noqa C901 orig = arg arg = arg.lower().strip("#x") if arg == "maddiepurple": arg = "a781e7" if arg.startswith("0x"): arg = arg try: clr = webcolors.html5_parse_simple_color( webcolors.name_to_hex(arg)) return cls(clr.red, clr.green, clr.blue) except ValueError: pass if len(arg) == 6: try: clr = webcolors.html5_parse_simple_color(f"#{arg}") return cls(clr.red, clr.green, clr.blue) except ValueError: raise commands.BadColourArgument(orig) elif len(arg) == 3: try: clr = webcolors.html5_parse_simple_color("#" + ''.join(f"{c}{c}" for c in arg)) return cls(clr.red, clr.green, clr.blue) except ValueError: raise commands.BadColourArgument(orig) raise commands.BadColourArgument(orig)
def to_partyspec(res, colors=None, order=None): if not order: order = res.keys() if colors: return [(p, res[p], webcolors.name_to_hex(colors[p])) for p in order] else: return [(p, res[p]) for p in res.keys()]
async def convert(cls, ctx: AoiContext, arg: str) -> "AoiColor": orig = arg arg = arg.lower().strip("#x") if arg.startswith("0x"): arg = arg try: clr = webcolors.html5_parse_simple_color( webcolors.name_to_hex(arg)) return cls(clr.red, clr.green, clr.blue) except ValueError: pass if len(arg) == 6: try: clr = webcolors.html5_parse_simple_color(f"#{arg}") return cls(clr.red, clr.green, clr.blue) except ValueError: return cls(0, 0, 0, attempt=orig) elif len(arg) == 3: try: clr = webcolors.html5_parse_simple_color("#" + ''.join(f"{c}{c}" for c in arg)) return cls(clr.red, clr.green, clr.blue) except ValueError: return cls(0, 0, 0, attempt=orig) return cls(0, 0, 0, attempt=orig)
def __init__(self, name='goldpads', gds_layer=0, gds_datatype=0, description='Gold pads liftoff', inverted=False, color=None, alpha=0.6): self.name = name self.gds_layer = gds_layer self.gds_datatype = gds_datatype self.description = description self.alpha = alpha try: if color is None: # not specified self.color = None elif np.size(color) == 3: # in format (0.5, 0.5, 0.5) self.color = webcolors.rgb_to_hex( np.array(np.array(color) * 255, dtype=int)) elif color[0] == '#': # in format #1d2e3f self.color = webcolors.hex_to_rgb(color) self.color = webcolors.rgb_to_hex(self.color) else: # in named format 'gold' self.color = webcolors.name_to_hex(color) except: raise ValueError("""[PHIDL] Layer() color must be specified as a 0-1 RGB triplet, (e.g. [0.5, 0.1, 0.9]), an HTML hex color (e.g. #a31df4), or a CSS3 color name (e.g. 'gold' or see http://www.w3schools.com/colors/colors_names.asp ) """) Layer.layer_dict[(gds_layer, gds_datatype)] = self
def setupUi(self): DIVariable = self DIVariable.setObjectName("DIVariable") DIVariable.resize(150, 25) DIVariable.setMinimumSize(QtCore.QSize(150, 25)) self.MainFrame = QtWidgets.QFrame(DIVariable) self.MainFrame.setGeometry(QtCore.QRect(0, 0, 150, 25)) self.MainFrame.setStyleSheet("background-color: rgb(255, 255, 255);") self.MainFrame.setFrameShape(QtWidgets.QFrame.NoFrame) self.MainFrame.setFrameShadow(QtWidgets.QFrame.Plain) self.MainFrame.setLineWidth(0) self.MainFrame.setObjectName("MainFrame") self.lblTileScroll = QtWidgets.QScrollArea(self.MainFrame) self.lblTileScroll.setGeometry(QtCore.QRect(0, 0, 110, 25)) self.lblTileScroll.setMinimumSize(QtCore.QSize(110, 20)) self.lblTileScroll.setMaximumSize(QtCore.QSize(100, 25)) self.lblTileScroll.setFrameShape(QtWidgets.QFrame.NoFrame) self.lblTileScroll.setFrameShadow(QtWidgets.QFrame.Plain) self.lblTileScroll.setLineWidth(0) self.lblTileScroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.lblTileScroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.lblTileScroll.setWidgetResizable(True) self.lblTileScroll.setObjectName("lblTileScroll") self.ScrollLayout = QtWidgets.QWidget() self.ScrollLayout.setGeometry(QtCore.QRect(0, 0, 110, 25)) self.ScrollLayout.setObjectName("ScrollLayout") self.vboxlayout = QtWidgets.QVBoxLayout(self.ScrollLayout) self.vboxlayout.setContentsMargins(0, 0, 0, 0) self.vboxlayout.setSpacing(0) self.vboxlayout.setObjectName("vboxlayout") self.lblTitle = QtWidgets.QLabel(self.ScrollLayout) self.lblTitle.setMaximumSize(QtCore.QSize(16666672, 16666672)) font = QtGui.QFont() font.setFamily("Roboto") font.setPointSize(11) font.setBold(True) font.setWeight(75) self.lblTitle.setFont(font) self.lblTitle.setLineWidth(0) self.lblTitle.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.lblTitle.setWordWrap(True) self.lblTitle.setIndent(5) self.lblTitle.setObjectName("lblTitle") self.vboxlayout.addWidget(self.lblTitle) self.lblTileScroll.setWidget(self.ScrollLayout) self.lblValue = QtWidgets.QLabel(self.MainFrame) self.lblValue.setGeometry(QtCore.QRect(123, 3, 16, 16)) self.lblValue.setStyleSheet("background-color:green;border-radius:5px;") self.lblValue.setFrameShape(QtWidgets.QFrame.Panel) self.lblValue.setText("") self.lblValue.setObjectName("lblValue") self.retranslateUi(DIVariable) QtCore.QMetaObject.connectSlotsByName(DIVariable) if int(self.__variable.value) == 0: self.lblValue.setStyleSheet("background-color:%s; border-radius:8px;" % webcolors.name_to_hex(self.__variable.displayColor)) else: self.lblValue.setStyleSheet("background-color:gray;border-radius:8px;") self.show()
def tryhard_name_to_hex(name: str) -> str | None: for spec in [CSS3, CSS21, CSS2, HTML4]: try: return name_to_hex(name.lower(), spec).lstrip("#").upper() # type: ignore except ValueError: continue return None
def to_internal_value(self, data): try: # force an error as validation color_name = webcolors.name_to_hex(data) except ValueError: raise serializers.ValidationError("Invalid color name.") return super().to_internal_value(color_name)
def _get_color(color: str): try: return webcolors.normalize_hex(color) except ValueError: pass try: return webcolors.name_to_hex(color) except ValueError: pass
def get_closest(hex): rgb = webcolors.hex_to_rgb(hex) try: closest_name = actual_name = webcolors.rgb_to_name(rgb) except ValueError: closest_name = closest_colour(rgb) actual_name = None if actual_name: actual = webcolors.name_to_hex(actual_name) else: actual = None closest = webcolors.name_to_hex(closest_name) return actual, closest
def test_name_to_hex(self): """ Test correct conversion of color names to hex. """ test_pairs = ((u'white', u'#ffffff'), (u'navy', u'#000080'), (u'goldenrod', u'#daa520')) for name, hex_value in test_pairs: self.assertEqual(hex_value, webcolors.name_to_hex(name))
def test_html_definition_conformance(self): """ Compare the results of name-to-hex conversion to the canonical hex values provided in the HTML 4 specification. """ for color, hex_value in HTML4_COLOR_DEFINITIONS.items(): normalized = webcolors.normalize_hex(hex_value) assert normalized == webcolors.name_to_hex(color)
def get_rgb_from_color(color): try: hex_color = name_to_hex(color) except ValueError: hex_color = color rgb_normalized = [ round(float(float(i) / 255), 2) for i in hex_to_rgb(hex_color) ] return rgb_normalized
def _get_color_hex(self, color_name): if color_name.startswith('#'): color_hex = color_name else: try: color_hex = webcolors.name_to_hex(color_name) except Exception as e: self._module.fail_json(msg="Failed to get RGB hex for color '%s': %s" % (color_name, e)) color_hex = color_hex.strip('#').upper() return color_hex
def fromCSSName(cls, cssname, huefxrng=HUEFX, lumfxrng=LUMFX): # Create an energy color from a css color name (note: requires webcolors module) try: import webcolors return cls.fromHex(webcolors.name_to_hex(cssname), huefxrng=huefxrng, lumfxrng=lumfxrng) except ImportError as e: raise ValueError( ("Unable to find web colors, making an energy" " color from {!r} is not possible".format(cssname)), file=sys.stderr, )
def parse_color(color: str) -> str: _color = color.lower() try: _color = webcolors.name_to_hex(_color)[1:] except ValueError: pass if re.fullmatch("^[0-9a-f]{6}$", _color): # Color in HTML notation return _color else: raise ColorParseError(f"{color} is not a valid color")
def getHexColorByName(name, language, colorReader=None): if not colorReader: colorReader = {} if language == "ru": for color in colorReader: if color in name.lower() and len(color) >= 3: return colorReader[color] return None try: color = webcolors.name_to_hex(name) return color except: return None
def get_pictures(required): gd_client = gdata.photos.service.PhotosService() photos = gd_client.SearchCommunityPhotos(required, limit='50') no_error = False j = 0 count = 0 purl1 = 'none' purl2 = 'none' purl3 = 'none' for photo in photos.entry: if j < 50: purl=photo.content.src NUM_CLUSTERS = 5 print 'reading image' URL = purl file = cStringIO.StringIO(urllib.urlopen(URL).read()) im = Image.open(file) im = im.resize((150, 150)) # optional, to reduce time ar = scipy.misc.fromimage(im) shape = ar.shape ar = ar.reshape(scipy.product(shape[:2]), shape[2]) print 'finding clusters' codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS) print 'cluster centres:\n', codes vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences index_max = scipy.argmax(counts) # find most frequent peak = codes[index_max] color = ''.join(chr(c) for c in peak).encode('hex') various=''.join(['#', color]) new_color=get_color_name(various, peak) new_name=webcolors.name_to_hex(new_color, spec='css3') print new_name print 'most frequent is %s (#%s)' % (peak, color) cat = col.lower() req = webcolors.hex_to_rgb(cat) new_cat=get_color_name(cat, req) print cat j += 1 print j if new_color == new_cat: no_error = True count += 1 print count if count == 1: purl1 = purl if count == 2: purl2 = purl if count == 3: purl3 = purl if j == 50 or count == 3: return purl1, purl2, purl3
def parse_args(suffix): """ 解析颜色和页面参数 """ suffix = suffix.rstrip(" \n") if suffix.find("#") != -1: #color = "#ff0000" #color = webcolors.name_to_hex("blue") m = suffix.split("#") color = webcolors.name_to_hex(m[1]) if len(m)>1 else m[0] page = m[0] if len(m) > 1 else '' else: color = None page = suffix return (color, page)
def sendMSG(Red,Gre,Blu): requested_colour = (Red, Gre, Blu) closest_name = closest_colour(requested_colour) Hex = webcolors.name_to_hex(closest_name).encode('ascii','ignore') ## HexV = ColrDTC.Hex ## Hex = "%s" %HexV ## self.message(Hex) ## Hex = "#101010" inpu = Hex[1:] ser.write('%s' %(Hex[1:])) ## ser.write('ff0000') time.sleep(1) return inpu
def get_color(color): if color.startswith('rgb'): r_, g_, b_ = color[3:] r, g, b = int(r_) * 40 + 55, int(g_) * 40 + 55, int(b_) * 40 + 55 return hex_rgb(r, g, b) if color.startswith('gray'): level = int(color[4:]) r, g, b = [255 - (level * (256.0 / 23))] * 3 return hex_rgb(r, g, b) try: return webcolors.name_to_hex(color) except: pass raise ValueError('No known color for %s' % color)
def update_leds(self, state): for i, color in enumerate(state): if not color.startswith('#'): color = name_to_hex(color) if color != self.prev_state[i]: led = self.numleds - (i + 1) color_code = color.lstrip('#') url = self.ledbar_api.format(led=led, color_code=color_code) log.debug('url: %s' % url) self.api_call(url) self.prev_state[i] = color
def find_hex_from_string(color_name): hex_code = "no hex" try: hex_code = webcolors.name_to_hex(color_name) # trim the '#' hex_code = hex_code[1,] except Exception: hex_code = "no hex" for color in colors: if color[1].lower() == color_name: hex_code = color[0] return hex_code
def test_name_to_hex_specs(self): """ Using one of the supported specifications succeeds; using an unsupported specification raises ValueError. """ for supported_spec in (u'html4', u'css2', u'css21', u'css3'): self.assertEqual(u'#ffffff', webcolors.name_to_hex(u'white', spec=supported_spec)) for unsupported_spec in (u'css1', u'css4', u'html5'): self.assertRaises(ValueError, webcolors.name_to_hex, 'white', spec=unsupported_spec)
def applyFmt(tblStyle, trStyle,tdStyle, cell,ws): # resolve all the styles finalStyle=deepcopy(tblStyle) if finalStyle == None: finalStyle ={} for s in [trStyle,tdStyle]: if s==None: continue for k,v in s.iteritems(): if v == False: continue finalStyle[k]=v font=Font() for k,v in finalStyle.iteritems(): if k == "italic" and v!=False: font.i=True if k == "underline" and v!=False: font.u=Font.UNDERLINE_SINGLE if k == "line-through" and v!=False: font.strikethrough=True if k == "font_name" and v!=False: font.name=v if k=="bold" and v==True: font.bold=True if k=='width' and v != "" and v != False: c,r=coordinate_from_string(cell.coordinate) m=re.match("([\d\.]+)(\D+)",v) if m != None: w=m.group(1) units=m.group(2) if units == "in": w=float(w)*12 ws.column_dimensions[c].width=w if k == "color" and v != False: if v[1]=="#": font.color = v[1:] else: try: hxcol=webcolors.name_to_hex(v) font.color=hxcol[1:] except: pass if k == "background-color" and v != False: c=Color(v[1:]) fill=PatternFill(patternType=fills.FILL_SOLID,fgColor=c) cell.fill = fill cell.font=font
def test_name_to_hex_specs(self): """ Using one of the supported specifications succeeds; using an unsupported specification raises ValueError. """ for supported_spec in webcolors.SUPPORTED_SPECIFICATIONS: result = webcolors.name_to_hex(u'white', spec=supported_spec) assert u'#ffffff' == result for unsupported_spec in (u'css1', u'css4', u'html5'): self.assertRaises( ValueError, webcolors.name_to_hex, 'white', spec=unsupported_spec )
def actuate( self, color ): if isinstance(color, tuple) and len(color) == 3: color = rgb_to_hex( color ) if isinstance(color, basestring): # check if the color is already in ninja-api supported format # if not, we'll pass it through webcolors if not re.match( NINJA_COLOR_RE, color ): if not color.startswith( '#' ): color = name_to_hex( color ) # ninja-api compatible color spec color = color.lstrip( '#' ).upper() return super(RGBLEDNinjaDevice, self).actuate( color ) else: raise ValueError( 'Color value must be a valid css3 color name or an (r,g,b) tuple' )
def normalize_color_to_hex(self, color_string): try: return webcolors.normalize_hex("#" + color_string) except ValueError: pass try: return webcolors.name_to_hex(color_string) except ValueError: pass try: return webcolors.normalize_hex(color_string) except ValueError: pass if color_string: logger.error('background_color value could not be parsed')
def get_color(color, with_a=True): thetype = l_type(color) if with_a and len(color) == 4 and thetype in (int, float): return color if not(with_a) and len(color) == 3 and thetype in (int,float): return color if thetype in (str, unicode): color = ''.join(color) from webcolors import name_to_hex from kivy.utils import get_color_from_hex try: named = name_to_hex(color) except ValueError,E: from utils import log log('Unkwon color name "%s"'%color) return [0, 0, 0, 1] if with_a else [0, 0, 0] r, g, b, a = get_color_from_hex(named) if with_a: return r, g, b, a return r, g, b
def get_color(color): if color.startswith('bold'): color = color[5:] if color.startswith('bright'): color = color[7:] if color.startswith('underline'): color = color[10:] if color.startswith('color'): number = int(color[3:]) r, g, b = xterm_to_rgb(number) return hex_rgb(r, g, b) if color.startswith('rgb'): r_, g_, b_ = color[3:] r, g, b = int(r_) * 40 + 55, int(g_) * 40 + 55, int(b_) * 40 + 55 return hex_rgb(r, g, b) if color.startswith('gray'): level = int(color[4:]) r, g, b = [255 - (level * (256.0 / 23))] * 3 return hex_rgb(r, g, b) try: return webcolors.name_to_hex(color) except: pass raise ValueError('No known color for %s' % color)
'ModifiedDate': max(dateset)}) # Nodes if args.nodes != 'skip': print("Normalising nodes", file=sys.stderr) sel = select([oqdacodes.c.id, oqdacodes.c.name, oqdacodes.c.memo, oqdacodes.c.color]) codes = [dict(row) for row in oqdadb.execute(sel)] codeuuid = {} for code in codes: code['uuid'] = uuid.uuid4() code['Color'] = int(webcolors.name_to_hex(code['color'])[1:], 16) code['CreatedBy'] = defaultuserid code['CreatedDate'] = min(dateset) code['ModifiedBy'] = defaultuserid code['ModifiedDate'] = max(dateset) codeuuid[code['id']] = code['uuid'] if len(codes) > 0: normdb.execute(normNode.insert().values({ 'Id' : bindparam('uuid'), 'Name' : bindparam('name'), 'Description': bindparam('memo') }), codes) # Sources if args.sources != 'skip':
# Use matplotlib and pygraphviz import re import matplotlib.pyplot as plt import pygraphviz as pgv import webcolors as wc width_box = 1.0 edge_width = 1.0 font_name = 'Arial' font_size = 12.0 #in pts subgrp_shape = 'tab' #http://www.graphviz.org/doc/info/shapes.html#d:style leafnde_shape = 'note' NODE_0 = wc.name_to_hex('white') #root NODE_1 = wc.name_to_hex('skyblue') #data/map/model NODE_2 = wc.name_to_hex('wheat') #uniform/static NODE_3 = wc.name_to_hex('lightgreen') #population NODE_4 = wc.name_to_hex('sandybrown') #parameter NODE_5 = wc.name_to_hex('lightgrey') #oned NODE_COLOR = [NODE_0, NODE_1, NODE_2, NODE_3, NODE_4, NODE_5] def add_child(G, parent_node, child, color=None, end_node=False): if parent_node=='/': child_x = parent_node+child else: child_x = parent_node+'/'+child G.add_node(child_x+'_point', shape='point', width=0.05) child_point_node = G.get_node(child_x+'_point')
def get_raw_colors(self, colors): raw_colors = [] for i in colors: raw_colors.append( int(webcolors.name_to_hex(i).replace('#', ''), 16)) return raw_colors
def to_hex(colorspec): """ desc: Converts a color specificaton to a seven-character lowercase hexadecimal color string, such as '#ff0000'. arguments: colorspec: desc: A color specification. type: [str, unicode, array-like, int] returns: desc: A hexadecimal color specification. type: unicode """ is_rgb = lambda c: hasattr(c, '__len__') \ and len(c) == 3 \ and all(isinstance(i, numbers.Integral) and 0 <= i <= 255 for i in c) if isinstance(colorspec, int): return webcolors.rgb_to_hex((colorspec, colorspec, colorspec)) if is_rgb(colorspec): return webcolors.rgb_to_hex(colorspec) if isinstance(colorspec, basestring): try: colorspec = int(colorspec) return webcolors.rgb_to_hex((colorspec, colorspec, colorspec)) except: pass if colorspec.startswith(u'#'): try: return webcolors.rgb_to_hex( webcolors.hex_to_rgb(colorspec)) except: raise osexception(u'Invalid color specification: %s' \ % safe_decode(colorspec)) if colorspec.startswith(u'rgb'): if u'%' in colorspec: l = colorspec[4:-1].split(u',') if len(l) != 3: raise osexception(u'Invalid color specification: %s' \ % safe_decode(colorspec)) for v in l: if u'%' not in v: raise osexception( u'Invalid color specification: %s' \ % safe_decode(colorspec)) try: l = tuple([v.strip() for v in l]) except: raise osexception(u'Invalid color specification: %s' \ % safe_decode(colorspec)) return webcolors.rgb_percent_to_hex(l) l = colorspec[4:-1].split(u',') if len(l) != 3: raise osexception(u'Invalid color specification: %s' \ % safe_decode(colorspec)) try: l = tuple([int(v) for v in l]) except: raise osexception(u'Invalid color specification: %s' \ % safe_decode(colorspec)) return webcolors.rgb_to_hex(l) try: return webcolors.name_to_hex(colorspec) except: raise osexception(u'Invalid color specification: %s' \ % safe_decode(colorspec)) raise osexception( u'Invalid color specification: %s' % safe_decode(colorspec))
def setGroup(self, value): groupValue = {} # END FADE IF SET COMMAND IS GIVEN if value.get('ctfade') is None: global ctFade ctFade.endRun() # XY xy = value.get('xy') if xy: groupValue.update({'xy':xy}) self._xy = xy # HUE hue = value.get('hue') if hue: groupValue.update({'hue':hue}) self._hue = hue #TRANS TIME transitiontime = value.get('transitiontime') if transitiontime: groupValue.update({'transitiontime':transitiontime}) #NAME COLOR name = value.get('name') if name: value['hex'] = name_to_hex(name) #HEX COLOR hexColor = value.get('hex') if hexColor: groupValue.update(self.hexColor(hexColor)) # PRESET preset = value.get('preset') if preset: if preset in PRESETS_CT: value['ct'] = PRESETS_CT.get(preset) # SET FOR LEVEL level = value.get('level') if level: if level > 0: if level > 100: level = 100 level = 100 if level >= 100 else level bri = int(255.0/100.0*level) level = level groupValue.update({'bri':bri}) if level <= 0: bri = 0 level = 0 self._on = False groupValue.update({'bri':bri,'on':False}) self._bri = bri self._level = level # SET FOR BRI bri = value.get('bri') if bri: if bri > 255: bri = 255 self._level = int(bri/255.0*100.0) if bri <= 0: bri = 0 self._level = 0 self._on = False groupValue.update({'on':False}) groupValue.update({'bri':bri}) self._bri = bri # SET CT: ct = value.get('ct') if ct: if 'K' in ct.upper(): ct = int(ct.upper().replace('K','')) ct = int(1000000/ct) if ct > 500: ct = 500 if ct < 153: ct = 153 groupValue.update({'ct':ct}) self._ct = ct # EFFECT effect = value.get('effect') if effect: groupValue.update({'effect':effect}) self._effect = effect # ALERT alert = value.get('alert') if alert: groupValue.update({'alert':alert}) self._alert = alert # SET FOR ON on = value.get('on') if on is not None: groupValue.update({'on':on}) self._on = on # Turn lights on unless told not to or has already been set if groupValue.get('on') is None and not value.get('onOn'): groupValue.update({'on':True}) self._on = True self.set_group(groupValue) return value
def regex_replace(match): hex_color = match.group(2) if "#" in match.group(2) else webcolors.name_to_hex(match.group(2)) return match.group().replace(match.group(2), to_gray(hex_color))