Fix palette values to full hex string
504362
function parsePalette (palette) {
  var vars = {
    camelCased : {},
    paramCased : {}
  };
  Object.keys(palette).forEach(function (key) {
    var hex = color(palette[key]).hexString();
    vars.camelCased[cameled(key)] = hex;
    vars.paramCased[dashed(key)] = hex;
  });
  return vars;
}
647461
def make_palette(self):
        

        p = array('B')
        t = array('B')

        for x in self.palette:
            p.extend(x[0:3])
            if len(x) > 3:
                t.append(x[3])
        p = tostring(p)
        t = tostring(t)
        if t:
            return p,t
        return p,None
80474
def map_colors(arr, crange, cmap, hex=True):
    
    if isinstance(crange, np.ndarray):
        xsorted = np.argsort(crange)
        ypos = np.searchsorted(crange, arr)
        arr = xsorted[ypos]
    else:
        if isinstance(crange, tuple):
            cmin, cmax = crange
        else:
            cmin, cmax = np.nanmin(arr), np.nanmax(arr)
        arr = (arr - cmin) / (cmax-cmin)
        arr = np.ma.array(arr, mask=np.logical_not(np.isfinite(arr)))
    arr = cmap(arr)
    if hex:
        return rgb2hex(arr)
    else:
        return arr
879398
function extractPalette(parts, theme) {
      // If the next section is one of the palettes we assume it's a two word palette
      // Two word palette can be also written in camelCase, forming camelCase to dash-case

      var isTwoWord = parts.length > 1 && colorPalettes.indexOf(parts[1]) !== -1;
      var palette = parts[0].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();

      if (isTwoWord)  palette = parts[0] + '-' + parts.splice(1, 1);

      if (colorPalettes.indexOf(palette) === -1) {
        // If the palette is not in the palette list it's one of primary/accent/warn/background
        var scheme = $mdTheming.THEMES[theme].colors[palette];
        if (!scheme) {
          throw new Error($mdUtil.supplant(
            'mdColors: couldn\'t find \'{palette}\' in the palettes.',
            {palette: palette}));
        }
        palette = scheme.name;
      }

      return palette;
    }
1154037
function adjustBrightness($hex, $steps)
    {
        // Steps should be between -255 and 255. Negative = darker, positive = lighter
        $steps = max(-255, min(255, $steps));

        // Normalize into a six character long hex string
        $hex = str_replace('#', '', $hex);
        if (strlen($hex) == 3) {
            $hex = str_repeat(substr($hex, 0, 1), 2) . str_repeat(substr($hex, 1, 1), 2) . str_repeat(substr($hex, 2, 1), 2);
        }

        // Split into three parts: R, G and B
        $color_parts = str_split($hex, 2);
        $return = '#';

        foreach ($color_parts as $color) {
            $color = hexdec($color); // Convert to decimal
            $color = max(0, min(255, $color + $steps)); // Adjust color
            $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
        }

        return $return;
    }
336535
def _hex_to_rgba(hexs):
    """"""
    hexs = np.atleast_1d(np.array(hexs, '|U9'))
    out = np.ones((len(hexs), 4), np.float32)
    for hi, h in enumerate(hexs):
        assert isinstance(h, string_types)
        off = 1 if h[0] == '#' else 0
        assert len(h) in (6+off, 8+off)
        e = (len(h)-off) // 2
        out[hi, :e] = [int(h[i:i+2], 16) / 255.
                       for i in range(off, len(h), 2)]
    return out
276938
def color_array_by_hue_mix(value, palette):
    
    if int(value, 2) > 0:

        # Convert bits to list and reverse order to avoid issues with
        # differing lengths
        int_list = [int(i) for i in list(value[2:])]
        int_list.reverse()

        # since this is a 1D array, we need the zeroth elements
        # of np.nonzero.
        locs = np.nonzero(int_list)[0]
        # print(locs)
        # print(palette)
        rgb_vals = [palette[i] for i in locs]

        rgb = [0]*len(rgb_vals[0])  # We don't know if it's rgb or rgba
        for val in rgb_vals:
            for index in range(len(val)):
                rgb[index] += val[index]

        for i in range(len(rgb)):
            rgb[i] /= len(locs)

        return tuple(rgb)

    if int(value, 2) == 0:
        return (1, 1, 1) if len(palette[0]) == 3 else (1, 1, 1, 1)

    return -1
92041
function hex(s) {
    var m = /rgba?\((\d+), (\d+), (\d+)/.exec(s),
      c = s.split("");
    if (m) {
      s = ( m[1] << 16 | m[2] << 8 | m[3] ).toString(16);
      while (s.length < 6)
        s = "0" + s;
    }
    return "#" + (s.length == 6 ? s : c[1] + c[1] + c[2] + c[2] + c[3] + c[3]);
  }
290571
def hexdiff(x, y):
    """"""
    x = bytes_encode(x)[::-1]
    y = bytes_encode(y)[::-1]
    SUBST = 1
    INSERT = 1
    d = {(-1, -1): (0, (-1, -1))}
    for j in range(len(y)):
        d[-1, j] = d[-1, j - 1][0] + INSERT, (-1, j - 1)
    for i in range(len(x)):
        d[i, -1] = d[i - 1, -1][0] + INSERT, (i - 1, -1)

    for j in range(len(y)):
        for i in range(len(x)):
            d[i, j] = min((d[i - 1, j - 1][0] + SUBST * (x[i] != y[j]), (i - 1, j - 1)),  # noqa: E501
                          (d[i - 1, j][0] + INSERT, (i - 1, j)),
                          (d[i, j - 1][0] + INSERT, (i, j - 1)))

    backtrackx = []
    backtracky = []
    i = len(x) - 1
    j = len(y) - 1
    while not (i == j == -1):
        i2, j2 = d[i, j][1]
        backtrackx.append(x[i2 + 1:i + 1])
        backtracky.append(y[j2 + 1:j + 1])
        i, j = i2, j2

    x = y = i = 0
    colorize = {0: lambda x: x,
                -1: conf.color_theme.left,
                1: conf.color_theme.right}

    dox = 1
    doy = 0
    btx_len = len(backtrackx)
    while i < btx_len:
        linex = backtrackx[i:i + 16]
        liney = backtracky[i:i + 16]
        xx = sum(len(k) for k in linex)
        yy = sum(len(k) for k in liney)
        if dox and not xx:
            dox = 0
            doy = 1
        if dox and linex == liney:
            doy = 1

        if dox:
            xd = y
            j = 0
            while not linex[j]:
                j += 1
                xd -= 1
            print(colorize[doy - dox]("%04x" % xd), end=' ')
            x += xx
            line = linex
        else:
            print("    ", end=' ')
        if doy:
            yd = y
            j = 0
            while not liney[j]:
                j += 1
                yd -= 1
            print(colorize[doy - dox]("%04x" % yd), end=' ')
            y += yy
            line = liney
        else:
            print("    ", end=' ')

        print(" ", end=' ')

        cl = ""
        for j in range(16):
            if i + j < btx_len:
                if line[j]:
                    col = colorize[(linex[j] != liney[j]) * (doy - dox)]
                    print(col("%02X" % orb(line[j])), end=' ')
                    if linex[j] == liney[j]:
                        cl += sane_color(line[j])
                    else:
                        cl += col(sane(line[j]))
                else:
                    print("  ", end=' ')
                    cl += " "
            else:
                print("  ", end=' ')
            if j == 7:
                print("", end=' ')

        print(" ", cl)

        if doy or not yy:
            doy = 0
            dox = 1
            i += 16
        else:
            if yy:
                dox = 0
                doy = 1
            else:
                i += 16
1045600
function convertHexColorToRgba(hex) {
  // Expand shorthand form (e.g. "#03F") to full form (e.g. "#0033FF")
  const shorthandRegex = /^#([a-f\d])([a-f\d])([a-f\d])$/i;
  const hexFull = `${hex}`.replace(shorthandRegex, (m, r, g, b) => {
    return r + r + g + g + b + b;
  });

  const result = /^#([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexFull);
  if (!result) {
    // Return untouched if not a hex code
    return hex;
  }

  const r = parseInt(result[1], 16);
  const g = parseInt(result[2], 16);
  const b = parseInt(result[3], 16);
  const a = 1;

  return `rgba(${r}, ${g}, ${b}, ${a})`;
}
1263000
def build_colormap(palette, dtype, info):
        """"""
        from trollimage.colormap import Colormap
        sqpalette = np.asanyarray(palette).squeeze() / 255.0
        if hasattr(palette, 'attrs') and 'palette_meanings' in palette.attrs:
            meanings = palette.attrs['palette_meanings']
            iterator = zip(meanings, sqpalette)
        else:
            iterator = enumerate(sqpalette[:-1])

        if dtype == np.dtype('uint8'):
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

        elif 'valid_range' in info:
            tups = [(val, tuple(tup))
                    for (val, tup) in iterator]
            colormap = Colormap(*tups)

            sf = info.get('scale_factor', np.array(1))
            colormap.set_range(
                *info['valid_range'] * sf + info.get('add_offset', 0))

        return colormap, sqpalette
302344
def color_hex_to_dec_tuple(color):
    
    assert len(color) in [3, 4, 6, 8]
    if len(color) in [3, 4]:
        color = "".join([c*2 for c in color])
    n = int(color, 16)
    t = ((n >> 16) & 255, (n >> 8) & 255, n & 255)
    if len(color) == 8:
        t = t + ((n >> 24) & 255,)
    return t
1205961
public static String toColorShorthand(String red, String green, String blue) {
		return shorthandHex(toColor(red, green, blue));
	}
735124
def color_hex(self):
        """"""
        def clamp(x):
            return max(0, min(int(x), 255))

        r, g, b = np.trunc(self.color_rgb * 255)
        return "#{0:02x}{1:02x}{2:02x}".format(clamp(r), clamp(g), clamp(b))
1166961
def build_colormap(palette, info):
        """"""

        from trollimage.colormap import Colormap
        if 'palette_meanings' in palette.attrs:
            palette_indices = palette.attrs['palette_meanings']
        else:
            palette_indices = range(len(palette))

        sqpalette = np.asanyarray(palette).squeeze() / 255.0
        tups = [(val, tuple(tup))
                for (val, tup) in zip(palette_indices, sqpalette)]
        colormap = Colormap(*tups)
        if 'palette_meanings' not in palette.attrs:
            sf = info.get('scale_factor', np.array(1))
            colormap.set_range(
                *(np.array(info['valid_range']) * sf + info.get('add_offset', 0)))

        return colormap, sqpalette
263942
def save_palette_as_image(filename, palette):
    ""
    output_filename = '%s_palette.png' % filename[:filename.rfind('.')]
    size = (80 * len(palette.colors), 80)
    im = Image.new('RGB', size)
    draw = ImageDraw.Draw(im)
    for i, c in enumerate(palette.colors):
        v = colorsys.rgb_to_hsv(*norm_color(c.value))[2]
        (x1, y1) = (i * 80, 0)
        (x2, y2) = ((i + 1) * 80 - 1, 79)
        draw.rectangle([(x1, y1), (x2, y2)], fill=c.value)
        if v < 0.6:
            # white with shadow
            draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (90, 90, 90))
            draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value))
        else:
            # dark with bright "shadow"
            draw.text((x1 + 4, y1 + 4), rgb_to_hex(c.value), (230, 230, 230))
            draw.text((x1 + 3, y1 + 3), rgb_to_hex(c.value), (0, 0, 0))

    im.save(output_filename, "PNG")
47810
def as_hex(self):
        
        hex = [mpl.colors.rgb2hex(rgb) for rgb in self]
        return ColorPalette(hex)