Generate a palette from the colors.
962787
def palette():
    """"""
    for i in range(0, 16):
        if i % 8 == 0:
            print()

        if i > 7:
            i = "8;5;%s" % i

        print("\033[4%sm%s\033[0m" % (i, " " * (80 // 20)), end="")

    print("\n")
1363433
private float colorToAngle(int color) {
		float[] colors = new float[3];
		Color.colorToHSV(color, colors);
		
		return (float) Math.toRadians(-colors[0]);
	}
1230119
def _from_p(self, mode):
        """"""
        self._check_modes(("P", "PA"))

        if not self.palette:
            raise RuntimeError("Can't convert palettized image, missing palette.")
        pal = np.array(self.palette)
        pal = da.from_array(pal, chunks=pal.shape)

        if pal.shape[1] == 4:
            # colormap's alpha overrides data alpha
            mode = "RGBA"
            alpha = None
        elif self.mode.endswith("A"):
            # add a new/fake 'bands' dimension to the end
            alpha = self.data.sel(bands="A").data[..., None]
            mode = mode + "A" if not mode.endswith("A") else mode
        else:
            alpha = None

        flat_indexes = self.data.sel(bands='P').data.ravel().astype('int64')
        dim_sizes = ((key, val) for key, val in self.data.sizes.items() if key != 'bands')
        dims, new_shape = zip(*dim_sizes)
        dims = dims + ('bands',)
        new_shape = new_shape + (pal.shape[1],)
        new_data = pal[flat_indexes].reshape(new_shape)
        coords = dict(self.data.coords)
        coords["bands"] = list(mode)

        if alpha is not None:
            new_arr = da.concatenate((new_data, alpha), axis=-1)
            data = xr.DataArray(new_arr, coords=coords, attrs=self.data.attrs, dims=dims)
        else:
            data = xr.DataArray(new_data, coords=coords, attrs=self.data.attrs, dims=dims)

        return data
222411
def chromaticity_to_XYZ(white, red, green, blue):
    """"""
    xW, yW = white
    xR, yR = red
    xG, yG = green
    xB, yB = blue
    R = G = B = 1.0

    z = yW * ((xG - xB) * yR - (xR - xB) * yG + (xR - xG) * yB)
    YA = yR / R  * ((xG - xB) * yW - (xW - xB) * yG + (xW - xG) * yB) / z
    XA = YA * xR / yR
    ZA = YA * ((1 - xR) / yR - 1)
    YB = - yG / G * ((xR - xB) * yW - (xW - xB) * yR + (xW - xR) * yB) / z
    XB = YB * xG / yG
    ZB = YB * ((1 - xG) / yG - 1)
    YC = yB / B * ((xR - xG) * yW - (xW - xG) * yR + (xW - xR) * yG) / z
    XC = YC * xB / yB
    ZC = YC * ((1 - xB) / yB - 1)
    XW = XA * R + XB * G + XC * B
    YW = YA * R + YB * G + YC * B
    ZW = ZA * R + ZB * G + ZC * B

    return (XW, YW, ZW), (XA, YA, ZA), (XB, YB, ZB), (XC, YC, ZC)
1232413
def get_colors(self, prefix, len_):
        """"""

        def color(tupl):
            """Make a color css"""
            return ((
                '%s.color-{0}, %s.color-{0} a:visited {{\n'
                '  stroke: {1};\n'
                '  fill: {1};\n'
                '}}\n'
            ) % (prefix, prefix)).format(*tupl)

        def value_color(tupl):
            """Make a value color css"""
            return ((
                '%s .text-overlay .color-{0} text {{\n'
                '  fill: {1};\n'
                '}}\n'
            ) % (prefix, )).format(*tupl)

        def ci_color(tupl):
            """Make a value color css"""
            if not tupl[1]:
                return ''
            return (('%s .color-{0} .ci {{\n'
                     '  stroke: {1};\n'
                     '}}\n') % (prefix, )).format(*tupl)

        if len(self.colors) < len_:
            missing = len_ - len(self.colors)
            cycles = 1 + missing // len(self.colors)
            colors = []
            for i in range(0, cycles + 1):
                for color_ in self.colors:
                    colors.append(darken(color_, 33 * i / cycles))
                    if len(colors) >= len_:
                        break
                else:
                    continue
                break
        else:
            colors = self.colors[:len_]

        # Auto compute foreground value color when color is missing
        value_colors = []
        for i in range(len_):
            if i < len(self.value_colors) and self.value_colors[i] is not None:
                value_colors.append(self.value_colors[i])
            else:
                value_colors.append(
                    'white' if is_foreground_light(colors[i]) else 'black'
                )

        return '\n'.join(
            chain(
                map(color, enumerate(colors)),
                map(value_color, enumerate(value_colors)),
                map(ci_color, enumerate(self.ci_colors))
            )
        )
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])
1099602
private int[] buildVertexColor() {
        int[] color = new int[g.length];

        int n = 1;
        Arrays.fill(color, -1);
        for (long cycle : cycles) {
            for (int i = 0; i < g.length; i++) {
                if ((cycle & 0x1) == 0x1) color[i] = color[i] < 0 ? n : 0;
                cycle >>= 1;
            }
            n++;
        }

        return color;
    }
788496
def palette( self ):
        
        palette = QPalette()
        
        for colorGroup, qColorGroup in self.GroupMapping.items():
            for colorRole, qColorRole in self.RoleMapping.items():
                color = self.color(colorRole, colorGroup)
                
                palette.setColor( qColorGroup,
                                  qColorRole,
                                  color )
        return palette
703736
function allocateColor( $name, $red, $green, $blue )
    {
        if ( isset( $this->Palette[$name] ) )
        {
            eZDebug::writeError( 'Color already defined: ' . $name, __METHOD__ );
            return null;
        }
        $red = max( 0, min( 255, $red ) );
        $green = max( 0, min( 255, $green ) );
        $blue = max( 0, min( 255, $blue ) );
        $color = ImageColorAllocate( $this->ImageObject, $red, $green, $blue );
        $this->Palette[$name] = $color;
        $this->PaletteIndex[] = $color;
        return $color;
    }
36459
function _retrieveColor(palette, color, hue = '500', format) {
    if (typeof palette !== 'string' || typeof color !== 'string' || typeof hue !== 'string' || typeof format !== 'string') {
        throw new TypeError('Expected a string');
    }

    let hexColor;
    let result;

    try {
        hexColor = (palette === 'md') ? colors[palette][color][hue].hex : colors[palette][color];

        switch (format) {
            case 'rgb':
                result = _toRGB(hexColor);
                result = `rgb(${result.r}, ${result.g}, ${result.b})`;
                break;
            case 'hex':
                result = `#${hexColor}`;
                break;
            case 'raw':
                result = _toRGB(hexColor);
                result.hex = hexColor;
                break;
            default:
        }
    } catch (err) {
        throw new RangeError('No matching color.');
    }
    return result;
}
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
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
1294604
def apply_palette(img, palette, options):

    '''

    '''

    if not options.quiet:
        print('  applying palette...')

    bg_color = palette[0]

    fg_mask = get_fg_mask(bg_color, img, options)

    orig_shape = img.shape

    pixels = img.reshape((-1, 3))
    fg_mask = fg_mask.flatten()

    num_pixels = pixels.shape[0]

    labels = np.zeros(num_pixels, dtype=np.uint8)

    labels[fg_mask], _ = vq(pixels[fg_mask], palette)

    return labels.reshape(orig_shape[:-1])
1134273
def _palette_cmd(self, event):
        """"""
        label = event.widget
        label.master.focus_set()
        label.master.configure(relief="sunken")
        r, g, b = self.winfo_rgb(label.cget("background"))
        r = round2(r * 255 / 65535)
        g = round2(g * 255 / 65535)
        b = round2(b * 255 / 65535)
        args = (r, g, b)
        if self.alpha_channel:
            a = self.alpha.get()
            args += (a,)
            self.alphabar.set_color(args)
        color = rgb_to_hexa(*args)
        h, s, v = rgb_to_hsv(r, g, b)
        self.red.set(r)
        self.green.set(g)
        self.blue.set(b)
        self.hue.set(h)
        self.saturation.set(s)
        self.value.set(v)
        self.hexa.delete(0, "end")
        self.hexa.insert(0, color.upper())
        self.bar.set(h)
        self.square.set_hsv((h, s, v))
        self._update_preview()
869286
def interpolate_colors(colors, flat=False, num_colors=256):
    

    palette = []

    for i in range(num_colors):
        index = (i * (len(colors) - 1)) / (num_colors - 1.0)
        index_int = int(index)
        alpha = index - float(index_int)

        if alpha > 0:
            r = (1.0 - alpha) * colors[index_int][
                0] + alpha * colors[index_int + 1][0]
            g = (1.0 - alpha) * colors[index_int][
                1] + alpha * colors[index_int + 1][1]
            b = (1.0 - alpha) * colors[index_int][
                2] + alpha * colors[index_int + 1][2]
        else:
            r = (1.0 - alpha) * colors[index_int][0]
            g = (1.0 - alpha) * colors[index_int][1]
            b = (1.0 - alpha) * colors[index_int][2]

        if flat:
            palette.extend((int(r), int(g), int(b)))
        else:
            palette.append((int(r), int(g), int(b)))

    return palette
1000974
def _merge_colormaps(kwargs):
    """"""
    from trollimage.colormap import Colormap
    full_cmap = None

    palette = kwargs['palettes']
    if isinstance(palette, Colormap):
        full_cmap = palette
    else:
        for itm in palette:
            cmap = create_colormap(itm)
            cmap.set_range(itm["min_value"], itm["max_value"])
            if full_cmap is None:
                full_cmap = cmap
            else:
                full_cmap = full_cmap + cmap

    return full_cmap
477649
function initColors() {
	var low, high,
	    result = new Uint8Array( 0x1000000 );

	for ( low = 0; low < 0x100; low++ ) {
		for ( high = 0; high < 0x100; high++ ) {
			addTile( low, high );
		}
	}

	return result;

	function addTile( low, high ) {
		var colorLow, colorHigh, color,
		    offset = ( low << 16 ) | ( high << 8 );

		for ( var i = 0; i < 8; i++ ) {
			colorLow = ( low & 1 );
	    	colorHigh = ( high & 1 ) << 1;
	    	color = ( colorHigh | colorLow );

			result[ offset + i ] = color;

			low >>= 1;
	    	high >>= 1;
		}
	}
}