Validate a colormap

    Parameters
    ----------
    val: str or :class:`mpl.colors.Colormap`

    Returns
    -------
    str or :class:`mpl.colors.Colormap`

    Raises
    ------
    ValueError
4680
def validate_cmap(val):
    """"""
    from matplotlib.colors import Colormap
    try:
        return validate_str(val)
    except ValueError:
        if not isinstance(val, Colormap):
            raise ValueError(
                "Could not find a valid colormap!")
        return val
699397
def isconst(cls, val):
        ''' 

        '''
        return isinstance(val, string_types) and \
               ((len(val) == 7 and val[0] == "#") or val in enums.NamedColor)
43115
def to_rgba(val):
    '''
    
    '''
    if pimms.is_npmatrix(val) and val.shape[1] == 4: return val
    try: return np.asarray(matplotlib.colors.to_rgba(val))
    except Exception: return np.asarray([matplotlib.colors.to_rgba(u) for u in val])
86440
protected boolean checkvalue(String colorvalue) {

        boolean valid = validateColorValue(colorvalue);
        if (valid) {
            if (colorvalue.length() == 4) {
                char[] chr = colorvalue.toCharArray();
                for (int i = 1; i < 4; i++) {
                    String foo = String.valueOf(chr[i]);
                    colorvalue = colorvalue.replaceFirst(foo, foo + foo);
                }
            }
            m_textboxColorValue.setValue(colorvalue, true);
            m_colorField.getElement().getStyle().setBackgroundColor(colorvalue);
            m_colorValue = colorvalue;
        }
        return valid;
    }
133633
def validate(self, instance, value):
        """"""
        if not isinstance(value, (tuple, list, np.ndarray)):
            self.error(instance, value)
        if self.coerce:
            value = self.wrapper(value)
        valid_class = (
            self.wrapper if isinstance(self.wrapper, type) else np.ndarray
        )
        if not isinstance(value, valid_class):
            self.error(instance, value)
        allowed_kinds = ''.join(TYPE_MAPPINGS[typ] for typ in self.dtype)
        if value.dtype.kind not in allowed_kinds:
            self.error(instance, value, extra='Invalid dtype.')
        if self.shape is None:
            return value
        for shape in self.shape:
            if len(shape) != value.ndim:
                continue
            for i, shp in enumerate(shape):
                if shp not in ('*', value.shape[i]):
                    break
            else:
                return value
        self.error(instance, value, extra='Invalid shape.')
692200
def get_mpl_colormap(self, **kwargs):
        
        if not HAVE_MPL:    # pragma: no cover
            raise RuntimeError('matplotlib not available.')

        cmap = LinearSegmentedColormap.from_list(self.name,
                                                 self.mpl_colors, **kwargs)

        return cmap
142011
def toColor(val, colormap):
    """"""
    for i in range(0, len(colormap) - 1):
        if colormap[i + 1][0] > val:
            scale = (val - colormap[i][0]) / \
                (colormap[i + 1][0] - colormap[i][0])
            r = colormap[i][1][0] + \
                (colormap[i + 1][1][0] - colormap[i][1][0]) * scale
            g = colormap[i][1][1] + \
                (colormap[i + 1][1][1] - colormap[i][1][1]) * scale
            b = colormap[i][1][2] + \
                (colormap[i + 1][1][2] - colormap[i][1][2]) * scale
            return "#" + toHex(r) + toHex(g) + toHex(b)
    return "#" + toHex(colormap[-1][1][0]) + toHex(colormap[-1][1][1]) + toHex(colormap[-1][1][2])
858057
def validate_ENUM(in_value, restriction):
    
    value = _get_val(in_value)
    if type(value) is list:
        for subval in value:
            if type(subval) is tuple:
                subval = subval[1]
            validate_ENUM(subval, restriction)
    else:
        if value not in restriction:
            raise ValidationError("ENUM : %s"%(restriction))
226948
def _validate(self, val):
        
        if self.allow_None and val is None:
            return
        super(Range, self)._validate(val)

        self._checkBounds(val)
477047
private static Colour  parseColour(String val) throws SVGParseException
   {
      if (val.charAt(0) == '#')
      {
         IntegerParser  ip = IntegerParser.parseHex(val, 1, val.length());
         if (ip == null) {
            throw new SVGParseException("Bad hex colour value: "+val);
         }
         int  pos = ip.getEndPos();
         int  h1, h2, h3, h4;
         switch (pos) {
            case 4:
               int threehex = ip.value();
               h1 = threehex & 0xf00;  // r
               h2 = threehex & 0x0f0;  // g
               h3 = threehex & 0x00f;  // b
               return new Colour(0xff000000|h1<<12|h1<<8|h2<<8|h2<<4|h3<<4|h3);
            case 5:
               int fourhex = ip.value();
               h1 = fourhex & 0xf000;  // r
               h2 = fourhex & 0x0f00;  // g
               h3 = fourhex & 0x00f0;  // b
               h4 = fourhex & 0x000f;  // alpha
               return new Colour(h4<<28|h4<<24 | h1<<8|h1<<4 | h2<<4|h2 | h3|h3>>4);
            case 7:
               return new Colour(0xff000000 | ip.value());
            case 9:
               return new Colour(ip.value() << 24 | ip.value() >>> 8);
            default:
               // Hex value had bad length for a colour
               throw new SVGParseException("Bad hex colour value: "+val);
         }
      }

      String   valLowerCase = val.toLowerCase(Locale.US);
      boolean  isRGBA = valLowerCase.startsWith("rgba(");
      if (isRGBA || valLowerCase.startsWith("rgb("))
      {
         TextScanner  scan = new TextScanner(val.substring(isRGBA ? 5 : 4));
         scan.skipWhitespace();

         float  red = scan.nextFloat();
         if (!Float.isNaN(red) && scan.consume('%'))
            red = (red * 256) / 100;

         float  green = scan.checkedNextFloat(red);
         if (!Float.isNaN(green) && scan.consume('%'))
            green = (green * 256) / 100;

         float  blue = scan.checkedNextFloat(green);
         if (!Float.isNaN(blue) && scan.consume('%'))
            blue = (blue * 256) / 100;

         if (isRGBA) {
            float  alpha = scan.checkedNextFloat(blue);
            scan.skipWhitespace();
            if (Float.isNaN(alpha) || !scan.consume(')'))
               throw new SVGParseException("Bad rgba() colour value: "+val);
            return new Colour( clamp255(alpha * 256)<<24 | clamp255(red)<<16 | clamp255(green)<<8 | clamp255(blue) );
         } else {
            scan.skipWhitespace();
            if (Float.isNaN(blue) || !scan.consume(')'))
               throw new SVGParseException("Bad rgb() colour value: "+val);
            return new Colour( 0xff000000 | clamp255(red)<<16 | clamp255(green)<<8 | clamp255(blue) );
         }
      }
      else
      {
         boolean  isHSLA = valLowerCase.startsWith("hsla(");
         if (isHSLA || valLowerCase.startsWith("hsl("))
         {
            TextScanner  scan = new TextScanner(val.substring(isHSLA ? 5 : 4));
            scan.skipWhitespace();

            float  hue = scan.nextFloat();

            float  saturation = scan.checkedNextFloat(hue);
            if (!Float.isNaN(saturation))
               scan.consume('%');

            float  lightness = scan.checkedNextFloat(saturation);
            if (!Float.isNaN(lightness))
               scan.consume('%');

            if (isHSLA) {
               float alpha = scan.checkedNextFloat(lightness);
               scan.skipWhitespace();
               if (Float.isNaN(alpha) || !scan.consume(')'))
                  throw new SVGParseException("Bad hsla() colour value: "+val);
               return new Colour( clamp255(alpha * 256)<<24 | hslToRgb(hue, saturation, lightness) );
            } else {
               scan.skipWhitespace();
               if (Float.isNaN(lightness) || !scan.consume(')'))
                  throw new SVGParseException("Bad hsl() colour value: "+val);
               return new Colour( 0xff000000 | hslToRgb(hue, saturation, lightness) );
            }
         }
      }

      // Must be a colour keyword
      return parseColourKeyword(valLowerCase);
   }
1087794
def color=(color)
      validator = EnumAttributeValidator.new('String', ["9da2a6", "4ab200", "0b8000", "2952cc", "a82ee5", "e5457a", "b21212", "593c00", "e5BF00"])
      unless validator.valid?(color)
        fail ArgumentError, "invalid value for 'color', must be one of #{validator.allowable_values}."
      end
      @color = color
    end
913527
def _validate(self,val):
        """"""
        if isinstance(self.class_, tuple):
            class_name = ('(%s)' % ', '.join(cl.__name__ for cl in self.class_))
        else:
            class_name = self.class_.__name__
        if self.is_instance:
            if not (isinstance(val,self.class_)) and not (val is None and self.allow_None):
                raise ValueError(
                    "Parameter '%s' value must be an instance of %s, not '%s'" %
                    (self.name, class_name, val))
        else:
            if not (val is None and self.allow_None) and not (issubclass(val,self.class_)):
                raise ValueError(
                    "Parameter '%s' must be a subclass of %s, not '%s'" %
                    (val.__name__, class_name, val.__class__.__name__))
501647
def convert_color(color):
    
    if color is not None:

        # is the color a string
        if isinstance(color, str):
            # strip the color of white space
            color = color.strip()

            # if it starts with a # check it is a valid color
            if color[0] == "#":

                # check its format
                if len(color) != 7:
                    raise ValueError("{} is not a valid # color, it must be in the format #ffffff.".format(color))
                else:
                    # split the color into its hex values
                    hex_colors = (color[1:3], color[3:5], color[5:7])

                    # check hex values are between 00 and ff
                    for hex_color in hex_colors:
                        try:
                            int_color = int(hex_color, 16)
                        except:
                            raise ValueError("{} is not a valid value, it must be hex 00 - ff".format(hex_color))

                        if not (0 <= int_color <= 255):
                            raise ValueError("{} is not a valid color value, it must be 00 - ff".format(hex_color))

        # if the color is not a string, try and convert it
        else:
            # get the number of colors and check it is iterable
            try:
                no_of_colors = len(color)
            except:
                raise ValueError("A color must be a list or tuple of 3 values (red, green, blue)")

            if no_of_colors != 3:
                raise ValueError("A color must contain 3 values (red, green, blue)")

            # check the color values are between 0 and 255
            for c in color:
                if not (0 <= c <= 255):
                    raise ValueError("{} is not a valid color value, it must be 0 - 255")

            # convert to #ffffff format
            color = "#{:02x}{:02x}{:02x}".format(color[0], color[1], color[2])

    return color
1263215
def validate(self, value):
        
        val = value
        if isinstance(val, str):
            #FIXME: unsafe decoding
            val = unicode(value)
        val = super(String, self).validate(val)
        if not isinstance(val, unicode):
            raise ValueError("Not a string: %r" % (value, ))
        return val
220839
def validate_pair(ob: Any) -> bool:
    
    try:
        if len(ob) != 2:
            log.warning("Unexpected result: {!r}", ob)
            raise ValueError()
    except ValueError:
        return False
    return True
481684
def any_to_rgb(color):
    '''

    '''
    if isinstance(color, tuple):
        if len(color) == 3:
            color = color + (255,)
        return color
        
    if isinstance(color, str):
        return parse_color(color)
        
    raise ValueError("Color not recognized: {}".format(color))
28072
def color=(value)
      case value
        when Integer
          self.color_argb = value
        when Gosu::Color
          self.color_argb = value.to_i
        when Array
          self.color_argb = Gosu::Color.from_opengl value
        else
          raise TypeError, "Expected argb integer, rgba opengl float array or Gosu::Color"
      end

      value
    end