Helper function for the sparkline color functions below.
432490
def write_spark_color(element, color)  # :nodoc:
      attr = []

      attr << ['rgb',   color[:_rgb]]   if color[:_rgb]
      attr << ['theme', color[:_theme]] if color[:_theme]
      attr << ['tint',  color[:_tint]]  if color[:_tint]

      @writer.empty_tag(element, attr)
    end
246258
def _highlight_lines(self, tokensource):
        
        hls = self.hl_lines

        for i, (t, value) in enumerate(tokensource):
            if t != 1:
                yield t, value
            if i + 1 in hls:  # i + 1 because Python indexes start at 0
                if self.noclasses:
                    style = ''
                    if self.style.highlight_color is not None:
                        style = (' style="background-color: %s"' %
                                 (self.style.highlight_color,))
                    yield 1, '<span%s>%s</span>' % (style, value)
                else:
                    yield 1, '<span class="hll">%s</span>' % value
            else:
                yield 1, value
498679
def _coloredhelp(s):
    
    newlines = []
    bigindent = (' ' * 16)
    in_opts = False
    for line in s.split('\n'):
        linestripped = line.strip('\n').strip().strip(':')
        if linestripped == 'Usage':
            # label
            line = line.replace('Usage', str(C('Usage', **ARGS_LABEL)))
        elif linestripped == 'Options':
            line = line.replace('Options', str(C('Options', **ARGS_LABEL)))
            in_opts = True
        elif (':' in line) and (not line.startswith(bigindent)):
            # opt,desc line. colorize it.
            lineparts = line.split(':')
            opt = lineparts[0]
            vals = [lineparts[1]] if len(lineparts) == 2 else lineparts[1:]

            # colorize opt
            if ',' in opt:
                opts = opt.split(',')
            else:
                opts = [opt]
            optstr = ','.join(str(C(o, **ARGS_OPTIONS)) for o in opts)

            # colorize desc
            valstr = ':'.join(str(C(val, **ARGS_DESC)) for val in vals)
            line = ':'.join((optstr, valstr))
        elif in_opts and line.startswith(bigindent):
            # continued desc string..
            # Make any 'Default:Value' parts look the same as the opt,desc.

            line = ':'.join(str(C(s, **ARGS_DESC)) for s in line.split(':'))
        elif (not line.startswith('    ')):
            # header line.
            line = str(C(line, **ARGS_HEADER))
        else:
            # Everything else, usage mainly.
            if SCRIPT:
                line = line.replace(SCRIPT, str(C(SCRIPT, **ARGS_SCRIPT)))

        newlines.append(
            '{}{}'.format(line, C('', style='reset_all'))
        )
    return '\n'.join(newlines)
920039
def mpl_colors(self):
        
        mc = []

        for color in self.colors:
            mc.append(tuple([x / 255. for x in color]))

        return mc
1025513
def _colorbar_ticks(minval, maxval):
    """"""
    if not (np.isfinite(minval) and np.isfinite(maxval)):
        return [0, 0, 0]
    elif minval == maxval:
        return [minval]
    else:
        # Add eps to ensure values stay inside the range of the colorbar.
        # Otherwise they may occationally not display.
        eps = (maxval - minval) / 1e5
        return [minval + eps, (maxval + minval) / 2., maxval - eps]
864318
def text_list_to_colors(names):
    '''
    
    '''
    # STEP A: compute strings distance between all combnations of strings
    Dnames = np.zeros( (len(names), len(names)) )
    for i in range(len(names)):
        for j in range(len(names)):
            Dnames[i,j] = 1 - 2.0 * levenshtein(names[i], names[j]) / float(len(names[i]+names[j]))

    # STEP B: pca dimanesionality reduction to a single-dimension (from the distance space)
    pca = sklearn.decomposition.PCA(n_components = 1)
    pca.fit(Dnames)    
    
    # STEP C: mapping of 1-dimensional values to colors in a jet-colormap
    textToColor = pca.transform(Dnames)
    textToColor = 255 * (textToColor - textToColor.min()) / (textToColor.max() - textToColor.min())
    textmaps = generateColorMap();
    colors = [textmaps[int(c)] for c in textToColor]
    return colors
980883
def _create_ansi_color_dict(color_cls):
    "  "
    return {
        'ansidefault':   color_cls.BLACK,
        'ansiblack':     color_cls.BLACK,
        'ansidarkgray':  color_cls.BLACK | color_cls.INTENSITY,
        'ansilightgray': color_cls.GRAY,
        'ansiwhite':     color_cls.GRAY | color_cls.INTENSITY,
        
        # Low intensity.
        'ansidarkred':     color_cls.RED,
        'ansidarkgreen':   color_cls.GREEN,
        'ansibrown':       color_cls.YELLOW,
        'ansidarkblue':    color_cls.BLUE,
        'ansipurple':      color_cls.MAGENTA,
        'ansiteal':        color_cls.CYAN,

        # High intensity.
        'ansired':        color_cls.RED | color_cls.INTENSITY,
        'ansigreen':      color_cls.GREEN | color_cls.INTENSITY,
        'ansiyellow':     color_cls.YELLOW | color_cls.INTENSITY,
        'ansiblue':       color_cls.BLUE | color_cls.INTENSITY,
        'ansifuchsia':    color_cls.MAGENTA | color_cls.INTENSITY,
        'ansiturquoise':  color_cls.CYAN | color_cls.INTENSITY,
    }
531476
def _get_color_list():
    """"""
    if 'axes.prop_cycle' in plt.rcParams:
        return [p['color'] for p in list(plt.rcParams['axes.prop_cycle'])]
    else:
        return plt.rcParams['axes.color_cycle']
672646
def _get_colors(self, color_set, alpha, off_color, custom_colors={}):
        
        import matplotlib as mpl
        import matplotlib.pyplot as plt
        color_list = [off_color] * len(self.hkl_list)
        color_proxy_on_wulff = []
        miller_on_wulff = []
        e_surf_on_wulff = [(i, e_surf)
                           for i, e_surf in enumerate(self.e_surf_list)
                           if self.on_wulff[i]]

        c_map = plt.get_cmap(color_set)
        e_surf_on_wulff.sort(key=lambda x: x[1], reverse=False)
        e_surf_on_wulff_list = [x[1] for x in e_surf_on_wulff]
        if len(e_surf_on_wulff) > 1:
            cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list),
                                         vmax=max(e_surf_on_wulff_list))
        else:
            # if there is only one hkl on wulff, choose the color of the median
            cnorm = mpl.colors.Normalize(vmin=min(e_surf_on_wulff_list) - 0.1,
                                         vmax=max(e_surf_on_wulff_list) + 0.1)
        scalar_map = mpl.cm.ScalarMappable(norm=cnorm, cmap=c_map)

        for i, e_surf in e_surf_on_wulff:
            color_list[i] = scalar_map.to_rgba(e_surf, alpha=alpha)
            if tuple(self.miller_list[i]) in custom_colors.keys():
                color_list[i] = custom_colors[tuple(self.miller_list[i])]
            color_proxy_on_wulff.append(
                plt.Rectangle((2, 2), 1, 1, fc=color_list[i], alpha=alpha))
            miller_on_wulff.append(self.input_miller_fig[i])
        scalar_map.set_array([x[1] for x in e_surf_on_wulff])
        color_proxy = [plt.Rectangle((2, 2), 1, 1, fc=x, alpha=alpha)
                       for x in color_list]

        return color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, \
            e_surf_on_wulff_list
943029
function (lineData) {
                    return function (e, shape, chart, series) {
                        d3.select(shape).style("opacity", (series.lineMarkers || lineData.data.length < 2 ? dimple._helpers.opacity(e, chart, series) : 0));
                        dimple._removeTooltip(e, shape, chart, series);
                    };
                }
397964
def color(cls, value):
        """"""
        index = bisect(cls.breakpoints, value)
        return colors.fg(cls.colors_[index])
1284934
def _short_color_list(self):
        """"""
        return [c for c in colors.get_colors() if not re.search(r'\d', c)]
313901
function (r, g, b) {
            if (r > 255 || g > 255 || b > 255)
                throw "Invalid color component";
            return ((r << 16) | (g << 8) | b).toString(16);
        }
1129576
function (text, color, x, y, width) {
                        ctx.fillStyle = color;
                        var metric = ctx.measureText(text);
                        if (metric.width > width) {
                            while (text !== "") {
                                metric = ctx.measureText(text + "...");
                                if (metric.width <= width) {
                                    text += "...";
                                    break;
                                }
                                text = text.substr(0, text.length - 1);
                            }
                        }
                        ctx.fillText(text, x, y, width);
                    }
982019
def vals2colors(vals,cmap='GnBu_d',res=100):
    
    # flatten if list of lists
    if any(isinstance(el, list) for el in vals):
        vals = list(itertools.chain(*vals))

    # get palette from seaborn
    palette = np.array(sns.color_palette(cmap, res))
    ranks = np.digitize(vals, np.linspace(np.min(vals), np.max(vals)+1, res+1)) - 1
    return [tuple(i) for i in palette[ranks, :]]
129528
function(color) {
				if (!color || color === "") {
					return _colorLookup.black;
				} else if (_colorLookup[color]) {
					return _colorLookup[color];
				} else if (typeof(color) === "number") {
					return [color >> 16, (color >> 8) & 255, color & 255];
				} else if (color.charAt(0) === "#") {
					if (color.length === 4) { //for shorthand like #9F0
						color = "#" + color.charAt(1) + color.charAt(1) + color.charAt(2) + color.charAt(2) + color.charAt(3) + color.charAt(3);
					}
					color = parseInt(color.substr(1), 16);
					return [color >> 16, (color >> 8) & 255, color & 255];
				} else {
					return color.match(_numExp) || _colorLookup.transparent;
				}
			}
857706
function make_color(aggregates, all, leaf_only) {
    let colorRange;
    if (aggregates.length >= 2) {
        colorRange = [Infinity, -Infinity];
        for (let series of all) {
            let colorvals = series["data"];
            for (let i = 1; i < colorvals.length; ++i) {
                if ((leaf_only && colorvals[i].leaf) || !leaf_only) {
                    colorRange[0] = Math.min(colorRange[0], colorvals[i].colorValue);
                    colorRange[1] = Math.max(colorRange[1], colorvals[i].colorValue);
                }
            }
            if (colorRange[0] * colorRange[1] < 0) {
                let cmax = Math.max(Math.abs(colorRange[0]), Math.abs(colorRange[1]));
                colorRange = [-cmax, cmax];
            }
        }
    }
    return colorRange;
}