Check and parse color specs as either a single [r,g,b] or a list of
    [[r,g,b],[r,g,b]...]
777522
def check_color(c):
    

    c = asarray(c)
    if c.ndim == 1:
        c = c.flatten()
        c = c[newaxis, :]
        if c.shape[1] != 3:
            raise Exception("Color must have three values per point")
    elif c.ndim == 2:
        if c.shape[1] != 3:
            raise Exception("Color array must have three values per point")
    return c
12757
def check_colormap(cmap):
    
    names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
                 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu',
                 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd',
                 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'Lightning'])
    if cmap not in names:
        raise Exception("Invalid cmap '%s',  must be one of %s" % (cmap, names))
    else:
        return cmap
760319
def _compute_iso_color(self):
        
        level_color = []
        colors = self._lc
        for i, index in enumerate(self._li):
            level_color.append(np.zeros((index, 4)) + colors[i])
        self._cl = np.vstack(level_color)
956942
def parse_map_Ks(self):
        """"""
        Kd = os.path.join(self.dir, " ".join(self.values[1:]))
        self.this_material.set_texture_specular_color(Kd)
770840
def read_colormap(fh, byteorder, dtype, count, offsetsize):
    """"""
    cmap = fh.read_array(byteorder+dtype[-1], count)
    cmap.shape = (3, -1)
    return cmap
261997
def getcolor(spec):
    
    if isinstance(spec, str):
        from matplotlib import colors
        return asarray(colors.hex2color(colors.cnames[spec]))
    else:
        return spec
854667
def make_color_tuple(color):
    
    R = color[1:3]
    G = color[3:5]
    B = color[5:7]

    R = int(R, 16)
    G = int(G, 16)
    B = int(B, 16)

    return R, G, B
660388
def _parse_fmt(fmt, color_key='colors', ls_key='linestyles',
               marker_key='marker'):
  ''''''
  try:  # Is fmt just a colorspec?
    color = mcolors.colorConverter.to_rgb(fmt)
  except ValueError:
    pass  # No, not just a color.
  else:
    # Either a color or a numeric marker style
    if fmt not in mlines.lineMarkers:
      return {color_key:color}

  result = dict()
  # handle the multi char special cases and strip them from the string
  if fmt.find('--') >= 0:
    result[ls_key] = '--'
    fmt = fmt.replace('--', '')
  if fmt.find('-.') >= 0:
    result[ls_key] = '-.'
    fmt = fmt.replace('-.', '')
  if fmt.find(' ') >= 0:
    result[ls_key] = 'None'
    fmt = fmt.replace(' ', '')

  for c in list(fmt):
    if c in mlines.lineStyles:
      if ls_key in result:
        raise ValueError('Illegal format string; two linestyle symbols')
      result[ls_key] = c
    elif c in mlines.lineMarkers:
      if marker_key in result:
        raise ValueError('Illegal format string; two marker symbols')
      result[marker_key] = c
    elif c in mcolors.colorConverter.colors:
      if color_key in result:
        raise ValueError('Illegal format string; two color symbols')
      result[color_key] = c
    else:
      raise ValueError('Unrecognized character %c in format string' % c)
  return result
1099475
def ParseCellSpec (spec):
        """"""
        m = __specRe.match(spec)
        (column, row) = m.groups()
        return (int(row), ColumnToIndex(column))
716432
function parseColor (str) {
    if (str.substr(0,1) === '#') {
      // Handle color shorthands (like #abc)
      var shorthand = str.length === 4,
          m = str.match(shorthand ? /\w/g : /\w{2}/g);

      if (!m) return;
      m = m.map(function(s) { return parseInt(shorthand ? s+s : s, 16) });
      return new nodes.RGBA(m[0],m[1],m[2],1);
    }
    else if (str.substr(0,3) === 'rgb'){
      var m = str.match(/([0-9]*\.?[0-9]+)/g);
      if (!m) return;
      m = m.map(function(s){return parseFloat(s, 10)});
      return new nodes.RGBA(m[0], m[1], m[2], m[3] || 1);
    }
    else {
      var rgb = colors[str];
      if (!rgb) return;
      return new nodes.RGBA(rgb[0], rgb[1], rgb[2], 1);
    }
  }
1006860
def _build_color_variants(cls):
    
    # Get the basic frame types first.
    frametypes = cls.sets(registered=False)

    _colornames = [
        # 'black', disabled for now, it won't show on my terminal.
        'red',
        'green',
        'yellow',
        'blue',
        'magenta',
        'cyan',
        'white',
    ]
    _colornames.extend('light{}'.format(s) for s in _colornames[:])
    for colorname in _colornames:
        for framesobj in frametypes:
            framename = '{}_{}'.format(framesobj.name, colorname)
            cls.register(
                framesobj.as_colr(fore=colorname),
                name=framename,
            )
366246
def parse_mode(mode, default_bitdepth=None):
    """"""
    # few special cases
    if mode == 'P':
        # Don't know what is pallette
        raise Error('Unknown colour mode:' + mode)
    elif mode == '1':
        # Logical
        return (True, False, 1)
    elif mode == 'I':
        # Integer
        return (True, False, 16)
    # here we go
    if mode.startswith('L'):
        grayscale = True
        mode = mode[1:]
    elif mode.startswith('RGB'):
        grayscale = False
        mode = mode[3:]
    else:
        raise Error('Unknown colour mode:' + mode)

    if mode.startswith('A'):
        alpha = True
        mode = mode[1:]
    else:
        alpha = False

    bitdepth = default_bitdepth
    if mode.startswith(';'):
        mode = mode[1:]
    if mode:
        try:
            bitdepth = int(mode)
        except (TypeError, ValueError):
            raise Error('Unsupported bitdepth mode:' + mode)
    return (grayscale, alpha, bitdepth)
1245683
def from_rgb(r, g=None, b=None):
    
    c = r if isinstance(r, list) else [r, g, b]
    best = {}

    for index, item in enumerate(colors):
        d = __distance(item, c)
        if(not best or d <= best['distance']):
            best = {'distance': d, 'index': index}

    if 'index' in best:
        return best['index']
    else:
        return 1
986405
def is_valid_rgb_color(value):
    
    if not value:
        return False

    regex = re.compile(RGB_COLOR_REGEX)
    return bool(regex.match(value))
248762
def hexcolor(color):
    " "
    # first, if this is a hex color already, return!
    # Python 3: needs rewrite for str/unicode change
    if isinstance(color, six.string_types):
        if color[0] == '#' and len(color)==7:
            return color.lower()

    # now, get color to an rgb tuple
    rgb = (0,0,0)
    if isinstance(color, tuple):
        rgb = color
    elif isinstance(color, list):
        rgb = tuple(color)
    elif isinstance(color, six.string_types):
        c = color.lower()
        if c.find(' ')>-1:    c = c.replace(' ','')
        if c.find('gray')>-1: c = c.replace('gray','grey')
        if c in x11_colors:
            rgb = x11_colors[c]
    else:
        try:
            rgb = color.Red(), color.Green(), color.Blue()
        except:
            pass

    # convert rgb to hex color
    col = '#%02x%02x%02x' % (rgb)
    return col.lower()
776915
function parseColor(col) {
  let tmp;
  if (typeof col === 'string') {
    col = col.trim();
    if (col.slice(0,1) === '#') {
      if (col.length === 7) {
        return {
          r: parseInt('0x' + col.substr(1,2)),
          g: parseInt('0x' + col.substr(3,2)),
          b: parseInt('0x' + col.substr(5,2)),
          a: 1
        };
      } else if (col.length === 4) {
        return {
          r: Math.pow(parseInt('0x' + col.substr(1,1))+1,2)-1,
          g: Math.pow(parseInt('0x' + col.substr(2,1))+1,2)-1,
          b: Math.pow(parseInt('0x' + col.substr(3,1))+1,2)-1,
          a: 1
        };
      } else if (col.length === 9) {
        return {
          r: parseInt('0x' + col.substr(1,2)),
          g: parseInt('0x' + col.substr(3,2)),
          b: parseInt('0x' + col.substr(5,2)),
          a: parseInt('0x' + col.substr(7,2)) / 255
        };
      } else if (col.length === 5) {
        return {
          r: Math.pow(parseInt('0x' + col.substr(1,1))+1,2)-1,
          g: Math.pow(parseInt('0x' + col.substr(2,1))+1,2)-1,
          b: Math.pow(parseInt('0x' + col.substr(3,1))+1,2)-1,
          a: parseInt('0x' + col.substr(4,1)) / 15
        };
      }
    } else if (col.slice(0,4) === 'rgba') {
      tmp = col.substr(5).split(',');
      return {
        r: parseInt(tmp[0]),
        g: parseInt(tmp[1]),
        b: parseInt(tmp[2]),
        a: parseFloat(tmp[3])
      };
    } else if (col.slice(0,4) === 'hsla') {
      tmp = col.substr(5).split(',').slice(0,4);
      tmp[0] = tmp[0] / 359;
      tmp[1] = tmp[1].slice(0,-1) / 100;
      tmp[2] = tmp[2].slice(0,-2) / 100;
      tmp = hslaToRgba(...tmp);
      return {
        r: tmp[0],
        g: tmp[1],
        b: tmp[2],
        a: parseFloat(tmp[3])
      };
    } else if (col.slice(0,3) === 'rgb') {
      tmp = col.substr(4).split(',');
      return {
        r: parseInt(tmp[0]),
        g: parseInt(tmp[1]),
        b: parseInt(tmp[2]),
        a: 1
      };
    } else if (col.slice(0,3) === 'hsl') {
      tmp = col.substr(4).split(',').slice(0,3);
      tmp[0] = tmp[0] / 359;
      tmp[1] = tmp[1].slice(0,-1) / 100;
      tmp[2] = tmp[2].slice(0,-2) / 100;
      tmp = hslToRgb(...tmp);
      return {
        r: tmp[0],
        g: tmp[1],
        b: tmp[2],
        a: 1
      };
    } else if (col.slice(0,2) === '0x') {
      return {
          r: parseInt('0x' + col.substr(2,2)),
          g: parseInt('0x' + col.substr(4,2)),
          b: parseInt('0x' + col.substr(6,2)),
          a: parseInt('0x' + col.substr(8,2)) / 255
        };
    } else if (col === 'transparent') {
      return {
          r: 0,
          g: 0,
          b: 0,
          a: 0
        };
    } else if (colorNames.hasOwnProperty(col)) {
      return parseColor(colorNames[col]);
    }
  }
}
1354327
def _validate_color(self, color):
        """"""

        three_digit_pattern = compile("^[a-f0-9]{3}$")
        six_digit_pattern = compile("^[a-f0-9]{6}$")

        if not match(three_digit_pattern, color)\
            and not match(six_digit_pattern, color):
                raise InvalidColorError(
                    "{} is not a valid color".format(color)
                )

        return color