Generate a Jmol command String that colors the aligned residues of every
structure.
332264
public static String getJmolString(MultipleAlignment multAln,
			List<Atom[]> transformedAtoms, ColorBrewer colorPalette,
			boolean colorByBlocks) {

		// Color by blocks if specified
		if (colorByBlocks)
			return getMultiBlockJmolString(multAln, transformedAtoms,
					colorPalette, colorByBlocks);
		Color[] colors = colorPalette.getColorPalette(multAln.size());

		StringBuffer j = new StringBuffer();
		j.append(DEFAULT_SCRIPT);

		// Color the equivalent residues of every structure
		StringBuffer sel = new StringBuffer();
		sel.append("select *; color lightgrey; backbone 0.1; ");
		List<List<String>> allPDB = new ArrayList<List<String>>();

		// Get the aligned residues of every structure
		for (int i = 0; i < multAln.size(); i++) {

			List<String> pdb = MultipleAlignmentJmolDisplay.getPDBresnum(i,
					multAln, transformedAtoms.get(i));

			allPDB.add(pdb);
			sel.append("select ");
			int pos = 0;
			for (String res : pdb) {
				if (pos > 0)
					sel.append(",");
				pos++;

				sel.append(res);
				sel.append("/" + (i + 1));
			}
			if (pos == 0)
				sel.append("none");
			sel.append("; backbone 0.3 ; color [" + colors[i].getRed() + ","
					+ colors[i].getGreen() + "," + colors[i].getBlue() + "]; ");
		}

		j.append(sel);
		j.append("model 0;  ");
		j.append(LIGAND_DISPLAY_SCRIPT);

		return j.toString();
	}
860856
def _display(node, indent, expandattrs, expandvals, output):
    """"""
    attrs = _displayattrs(node.attrib, expandattrs)
    if node.text is None or not expandvals:
        val = ''
    elif isinstance(node.text, str):
        val = ' %s' % repr(node.text.strip())
    else:
        val = ' %s' % repr(node.text)  # node.text can be a tuple
    output.write(encode(indent + striptag(node.tag) + attrs + val + '\n'))
    for sub_node in node:
        _display(sub_node, indent + '  ', expandattrs, expandvals, output)
1321881
private void generateUMLClass(ClassDoc[] classes, String pkgname) throws IOException {
        for (int i=0; i<classes.length; i++) {
            ClassDoc c = classes[i];
            out.println("    <UML:Class stereotype=\"\" " +
                                     "package=\"" + pkgname + "\" " +
                                     "xmi.id=\"" + i + "\" " +
                                     "abstract=\"0\" " +
                                     "documentation=\"\" " +
                                     "name=\"" + c.name() + "\" " +
                                     "scope=\"200\">");
            MethodDoc[] methods = c.methods();
            for (int j=0; j<methods.length; j++) {
                MethodDoc md = methods[j];
                out.println("     <UML:Operation stereotype=\"\" " +
                                                "xmi.id=\"" + (1000*i + j) + "\" " +
                                                "type=\"void\" " +
                                                "abstract=\"0\" " +
                                                "documentation=\"\" " +
                                                "name=\"" + md.name() + "\" " +
                                                "scope=\"200\" />");
            }
            out.println("    </UML:Class>");
        }
    }
1064025
private void assembleLinkages(List<List<Atom[]>> matchedAtomsOfLinkages,
			ProteinModification mod, List<ModifiedCompound> ret) {
		ModificationCondition condition = mod.getCondition();
		List<ModificationLinkage> modLinks = condition.getLinkages();

		int nLink = matchedAtomsOfLinkages.size();
		int[] indices = new int[nLink];
		Set<ModifiedCompound> identifiedCompounds = new HashSet<ModifiedCompound>();
		while (indices[0]<matchedAtomsOfLinkages.get(0).size()) {
			List<Atom[]> atomLinkages = new ArrayList<Atom[]>(nLink);
			for (int iLink=0; iLink<nLink; iLink++) {
				Atom[] atoms = matchedAtomsOfLinkages.get(iLink).get(indices[iLink]);
				atomLinkages.add(atoms);
			}
			if (matchLinkages(modLinks, atomLinkages)) {
				// matched

				int n = atomLinkages.size();
				List<StructureAtomLinkage> linkages = new ArrayList<StructureAtomLinkage>(n);
				for (int i=0; i<n; i++) {
					Atom[] linkage = atomLinkages.get(i);
					StructureAtomLinkage link = StructureUtil.getStructureAtomLinkage(
							linkage[0], residues.contains(linkage[0].getGroup()),
							linkage[1], residues.contains(linkage[1].getGroup()));
					linkages.add(link);
				}

				ModifiedCompound mc = new ModifiedCompoundImpl(mod, linkages);
				if (!identifiedCompounds.contains(mc)) {
					ret.add(mc);
					identifiedCompounds.add(mc);
				}
			}

			// indices++ (e.g. [0,0,1]=>[0,0,2]=>[1,2,0])
			int i = nLink-1;
			while (i>=0) {
				if (i==0 || indices[i]<matchedAtomsOfLinkages.get(i).size()-1) {
					indices[i]++;
					break;
				} else {
					indices[i] = 0;
					i--;
				}
			}
		}
	}
1182898
def _colorize_single_line(line, regexp, color_def):
    """"""
    match = regexp.match(line)
    groupdict = match.groupdict()
    groups = match.groups()
    if not groupdict:
        # no named groups, just colorize whole line
        color = color_def[0]
        dark = color_def[1]
        cprint("%s\n" % line, color, fg_dark=dark)
    else:
        rev_groups = {v: k for k, v in groupdict.items()}
        for part in groups:
            if part in rev_groups and rev_groups[part] in color_def:
                group_name = rev_groups[part]
                cprint(
                    part,
                    color_def[group_name][0],
                    fg_dark=color_def[group_name][1],
                )
            else:
                cprint(part)
        cprint("\n")
17664
def output(*args, **kwargs):
    '''
    '''
    indent = kwargs.pop('indent', 0)
    sep = kwargs.pop('sep', None)
    kwargs['sep'] = u''  # Sanity
    if sep is None:
        sep = u' '
    indent_str = u' ' * (indent * tab_width)
    text = sep.join(map(str_, args))
    color = kwargs.pop('color', None)
    if color:
        color.bright = kwargs.pop('bright', None)
        text = ColorText(text, color)
    print(indent_str + text, **kwargs)
136329
def make_colormap(seq):
    
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)
502858
def __RenderModuleFlags(self, module, flags, output_lines, prefix=''):
    """"""
    if not isinstance(module, str):
      module = module.__name__
    output_lines.append('\n%s%s:' % (prefix, module))
    self.__RenderFlagList(flags, output_lines, prefix + '  ')
1189727
def add_mpl_colorbar(dfr, fig, dend, params, orientation="row"):
    """"""
    for name in dfr.index[dend["dendrogram"]["leaves"]]:
        if name not in params.classes:
            params.classes[name] = name

    # Assign a numerical value to each class, for mpl
    classdict = {cls: idx for (idx, cls) in enumerate(params.classes.values())}

    # colourbar
    cblist = []
    for name in dfr.index[dend["dendrogram"]["leaves"]]:
        try:
            cblist.append(classdict[params.classes[name]])
        except KeyError:
            cblist.append(classdict[name])
    colbar = pd.Series(cblist)

    # Create colourbar axis - could capture if needed
    if orientation == "row":
        cbaxes = fig.add_subplot(dend["gridspec"][0, 1])
        cbaxes.imshow(
            [[cbar] for cbar in colbar.values],
            cmap=plt.get_cmap(pyani_config.MPL_CBAR),
            interpolation="nearest",
            aspect="auto",
            origin="lower",
        )
    else:
        cbaxes = fig.add_subplot(dend["gridspec"][1, 0])
        cbaxes.imshow(
            [colbar],
            cmap=plt.get_cmap(pyani_config.MPL_CBAR),
            interpolation="nearest",
            aspect="auto",
            origin="lower",
        )
    clean_axis(cbaxes)
    return colbar
584175
def refinements(self):
        """"""

        # Show sticks for all residues interacing with the ligand
        cmd.select('AllBSRes', 'byres (Hydrophobic-P or HBondDonor-P or HBondAccept-P or PosCharge-P or NegCharge-P or '
                               'StackRings-P or PiCatRing-P or HalogenAcc or Metal-P)')
        cmd.show('sticks', 'AllBSRes')
        # Show spheres for the ring centroids
        cmd.hide('everything', 'centroids*')
        cmd.show('nb_spheres', 'centroids*')
        # Show spheres for centers of charge
        if self.object_exists('Chargecenter-P') or self.object_exists('Chargecenter-L'):
            cmd.hide('nonbonded', 'chargecenter*')
            cmd.show('spheres', 'chargecenter*')
            cmd.set('sphere_scale', 0.4, 'chargecenter*')
            cmd.color('yellow', 'chargecenter*')

        cmd.set('valence', 1)  # Show bond valency (e.g. double bonds)
        # Optional cartoon representation of the protein
        cmd.copy('%sCartoon' % self.protname, self.protname)
        cmd.show('cartoon', '%sCartoon' % self.protname)
        cmd.show('sticks', '%sCartoon' % self.protname)
        cmd.set('stick_transparency', 1, '%sCartoon' % self.protname)

        # Resize water molecules. Sometimes they are not heteroatoms HOH, but part of the protein
        cmd.set('sphere_scale', 0.2, 'resn HOH or Water')  # Needs to be done here because of the copy made
        cmd.set('sphere_transparency', 0.4, '!(resn HOH or Water)')

        if 'Centroids*' in cmd.get_names("selections"):
            cmd.color('grey80', 'Centroids*')
        cmd.hide('spheres', '%sCartoon' % self.protname)
        cmd.hide('cartoon', '%sCartoon and resn DA+DG+DC+DU+DT+A+G+C+U+T' % self.protname)  # Hide DNA/RNA Cartoon
        if self.ligname == 'SF4':  # Special case for iron-sulfur clusters, can't be visualized with sticks
            cmd.show('spheres', '%s' % self.ligname)

        cmd.hide('everything', 'resn HOH &!Water')  # Hide all non-interacting water molecules
        cmd.hide('sticks', '%s and !%s and !AllBSRes' %
                 (self.protname, self.ligname))  # Hide all non-interacting residues

        if self.ligandtype in ['PEPTIDE', 'INTRA']:
            self.adapt_for_peptides()

        if self.ligandtype == 'INTRA':
            self.adapt_for_intra()
150082
private Map<IChemObject, Color> makeHighlightAtomMap(List<IAtomContainer> reactants,
                                                         List<IAtomContainer> products) {
        Map<IChemObject, Color> colorMap = new HashMap<>();
        Map<Integer, Color> mapToColor = new HashMap<>();
        int colorIdx = -1;
        for (IAtomContainer mol : reactants) {
            int prevPalletIdx = colorIdx;
            for (IAtom atom : mol.atoms()) {
                int mapidx = accessAtomMap(atom);
                if (mapidx > 0) {
                    if (prevPalletIdx == colorIdx) {
                        colorIdx++; // select next color
                        if (colorIdx >= atomMapColors.length)
                            throw new IllegalArgumentException("Not enough colors to highlight atom mapping, please provide mode");
                    }
                    Color color = atomMapColors[colorIdx];
                    colorMap.put(atom, color);
                    mapToColor.put(mapidx, color);
                }
            }
            if (colorIdx > prevPalletIdx) {
                for (IBond bond : mol.bonds()) {
                    IAtom a1 = bond.getBegin();
                    IAtom a2 = bond.getEnd();
                    Color c1 = colorMap.get(a1);
                    Color c2 = colorMap.get(a2);
                    if (c1 != null && c1 == c2)
                        colorMap.put(bond, c1);
                }
            }
        }

        for (IAtomContainer mol : products) {
            for (IAtom atom : mol.atoms()) {
                int mapidx = accessAtomMap(atom);
                if (mapidx > 0) {
                    colorMap.put(atom, mapToColor.get(mapidx));
                }
            }
            for (IBond bond : mol.bonds()) {
                IAtom a1 = bond.getBegin();
                IAtom a2 = bond.getEnd();
                Color c1 = colorMap.get(a1);
                Color c2 = colorMap.get(a2);
                if (c1 != null && c1 == c2)
                    colorMap.put(bond, c1);
            }
        }

        return colorMap;
    }
872996
def __RenderOurModuleFlags(self, module, output_lines, prefix=''):
    """"""
    flags = self._GetFlagsDefinedByModule(module)
    if flags:
      self.__RenderModuleFlags(module, flags, output_lines, prefix)
948666
@Override
	public String colorBySymmetry() {
		// TODO needs some refactoring
		String pointGroup = rotationGroup.getPointGroup();
		QuatSymmetrySubunits subunits = rotationAxisAligner.getSubunits();
		List<Integer> modelNumbers = subunits.getModelNumbers();
		List<String> chainIds = subunits.getChainIds();
		List<List<Integer>> orbits = rotationAxisAligner.getOrbits();

		int n = subunits.getSubunitCount();
		int fold = rotationGroup.getRotation(0).getFold();

		Map<Color4f, List<String>> colorMap = new HashMap<Color4f, List<String>>();

		// Simple Cn symmetry
		if (pointGroup.startsWith("C") && n == fold) {
			colorMap = getCnColorMap();
			// complex cases
		} else if ((pointGroup.startsWith("D") && orbits.size() > 2) ||
				pointGroup.equals("T")|| pointGroup.equals("O") || pointGroup.equals("I")) {
			int nColor = 0;
			if (orbits.size() % 2 == 0) {
				nColor = orbits.size()/2;
			} else {
				nColor = (orbits.size() + 1)/2;
			}
			Color4f[] colors = getSymmetryColors(nColor);

			for (int i = 0; i < orbits.size(); i++) {
				int colorIndex = i;

				// reverse colors once the center of the structure has been reached
				if (i >= nColor) {
					colorIndex = orbits.size() - 1 - i;
				}
				Color4f c = colors[colorIndex];
				List<String> ids = colorMap.get(c);
				if (ids == null) {
					ids = new ArrayList<String>();
					colorMap.put(c,  ids);
				}
				for (int subunit: orbits.get(i)) {
					String id = getChainSpecification(modelNumbers, chainIds, subunit);
					ids.add(id);
				}
			}

			// Simple Dn symmetry
		} else {
			Color4f[] colors = getSymmetryColors(orbits.size());

			for (int i = 0; i < orbits.size(); i++) {
				Color4f c = new Color4f(colors[i]);
				List<String> ids = colorMap.get(c);
				if (ids == null) {
					ids = new ArrayList<String>();
					colorMap.put(c,  ids);
				}
				List<Integer> orbit = orbits.get(i);
				for (int j = 0; j < orbit.size(); j++) {
					String id = getChainSpecification(modelNumbers, chainIds, orbit.get(j));
					ids.add(id);
				}
			}
		}

		return defaultColoring + getJmolColorScript(colorMap) + getJmolLigandScript();
	}
1353116
def method2dot(mx, colors=None):
    

    if not colors:
        colors = {
            "true_branch": "green",
            "false_branch": "red",
            "default_branch": "purple",
            "jump_branch": "blue",
            "bg_idx": "lightgray",
            "idx": "blue",
            "bg_start_idx": "yellow",
            "bg_instruction": "lightgray",
            "instruction_name": "black",
            "instructions_operands": "yellow",
            "raw": "red",
            "string": "red",
            "literal": "green",
            "offset": "#4000FF",
            "method": "#DF3A01",
            "field": "#088A08",
            "type": "#0000FF",
            "registers_range": ("#999933", "#6666FF")
        }

    node_tpl = "\nstruct_%s [label=<\n<TABLE BORDER=\"0\" CELLBORDER=\"0\" CELLSPACING=\"3\">\n%s</TABLE>>];\n"
    label_tpl = "<TR><TD ALIGN=\"LEFT\" BGCOLOR=\"%s\"> <FONT FACE=\"Times-Bold\" color=\"%s\">%x</FONT> </TD><TD ALIGN=\"LEFT\" BGCOLOR=\"%s\"> <FONT FACE=\"Times-Bold\" color=\"%s\">%s </FONT> %s </TD></TR>\n"
    link_tpl = "<TR><TD PORT=\"%s\"></TD></TR>\n"

    edges_html = ""
    blocks_html = ""

    method = mx.get_method()
    sha256 = hashlib.sha256(bytearray("{}{}{}".format(
        mx.get_method().get_class_name(), mx.get_method().get_name(),
        mx.get_method().get_descriptor()), "UTF-8")).hexdigest()

    registers = {}
    if method.get_code():
        for DVMBasicMethodBlock in mx.basic_blocks.gets():
            for DVMBasicMethodBlockInstruction in DVMBasicMethodBlock.get_instructions():
                operands = DVMBasicMethodBlockInstruction.get_operands(0)
                for register in operands:
                    if register[0] == 0:
                        if register[1] not in registers:
                            registers[register[1]] = 0
                        registers[register[1]] += 1
#        for i in range(method.get_code().get_registers_size()):
#            registers[i] = 0

    if registers:
        registers_colors = color_range(colors["registers_range"][0],
                                       colors["registers_range"][1],
                                       len(registers))
        for i in registers:
            registers[i] = registers_colors.pop(0)

    new_links = []

    for DVMBasicMethodBlock in mx.basic_blocks.gets():
        ins_idx = DVMBasicMethodBlock.start
        block_id = hashlib.md5(bytearray(sha256 + DVMBasicMethodBlock.get_name(), "UTF-8")).hexdigest()

        content = link_tpl % 'header'

        for DVMBasicMethodBlockInstruction in DVMBasicMethodBlock.get_instructions():
            if DVMBasicMethodBlockInstruction.get_op_value(
            ) == 0x2b or DVMBasicMethodBlockInstruction.get_op_value() == 0x2c:
                new_links.append((DVMBasicMethodBlock, ins_idx,
                                  DVMBasicMethodBlockInstruction.get_ref_off() * 2 + ins_idx))
            elif DVMBasicMethodBlockInstruction.get_op_value() == 0x26:
                new_links.append((DVMBasicMethodBlock, ins_idx,
                                  DVMBasicMethodBlockInstruction.get_ref_off() * 2 + ins_idx))

            operands = DVMBasicMethodBlockInstruction.get_operands(ins_idx)
            output = ", ".join(mx.get_vm().get_operand_html(
                i, registers, colors, escape, textwrap.wrap) for i in operands)

            formatted_operands = DVMBasicMethodBlockInstruction.get_formatted_operands(
            )
            if formatted_operands:
                output += " ; %s" % str(formatted_operands)

            bg_idx = colors["bg_idx"]
            if ins_idx == 0 and "bg_start_idx" in colors:
                bg_idx = colors["bg_start_idx"]

            content += label_tpl % (
                bg_idx, colors["idx"], ins_idx, colors["bg_instruction"],
                colors["instruction_name"],
                DVMBasicMethodBlockInstruction.get_name(), output)

            ins_idx += DVMBasicMethodBlockInstruction.get_length()
            last_instru = DVMBasicMethodBlockInstruction

        # all blocks from one method parsed
        # updating dot HTML content
        content += link_tpl % 'tail'
        blocks_html += node_tpl % (block_id, content)

        # Block edges color treatment (conditional branchs colors)
        val = colors["true_branch"]
        if len(DVMBasicMethodBlock.childs) > 1:
            val = colors["false_branch"]
        elif len(DVMBasicMethodBlock.childs) == 1:
            val = colors["jump_branch"]

        values = None
        if (last_instru.get_op_value() == 0x2b or
                last_instru.get_op_value() == 0x2c
           ) and len(DVMBasicMethodBlock.childs) > 1:
            val = colors["default_branch"]
            values = ["default"]
            values.extend(DVMBasicMethodBlock.get_special_ins(
                ins_idx - last_instru.get_length()).get_values())

        # updating dot edges
        for DVMBasicMethodBlockChild in DVMBasicMethodBlock.childs:
            label_edge = ""

            if values:
                label_edge = values.pop(0)

            child_id = hashlib.md5(
                bytearray(sha256 + DVMBasicMethodBlockChild[-1].get_name(), "UTF-8")).hexdigest()
            edges_html += "struct_{}:tail -> struct_{}:header  [color=\"{}\", label=\"{}\"];\n".format(
                block_id, child_id, val, label_edge)
            # color switch
            if val == colors["false_branch"]:
                val = colors["true_branch"]
            elif val == colors["default_branch"]:
                val = colors["true_branch"]

        exception_analysis = DVMBasicMethodBlock.get_exception_analysis()
        if exception_analysis:
            for exception_elem in exception_analysis.exceptions:
                exception_block = exception_elem[-1]
                if exception_block:
                    exception_id = hashlib.md5(
                        bytearray(sha256 + exception_block.get_name(), "UTF-8")).hexdigest()
                    edges_html += "struct_{}:tail -> struct_{}:header  [color=\"{}\", label=\"{}\"];\n".format(
                        block_id, exception_id, "black", exception_elem[0])

    for link in new_links:
        DVMBasicMethodBlock = link[0]
        DVMBasicMethodBlockChild = mx.basic_blocks.get_basic_block(link[2])

        if DVMBasicMethodBlockChild:
            block_id = hashlib.md5(bytearray(sha256 + DVMBasicMethodBlock.get_name(
            ), "UTF-8")).hexdigest()
            child_id = hashlib.md5(bytearray(sha256 + DVMBasicMethodBlockChild.get_name(
            ), "UTF-8")).hexdigest()

            edges_html += "struct_{}:tail -> struct_{}:header  [color=\"{}\", label=\"data(0x{:x}) to @0x{:x}\", style=\"dashed\"];\n".format(
                block_id, child_id, "yellow", link[1], link[2])

    method_label = method.get_class_name() + "." + method.get_name(
    ) + "->" + method.get_descriptor()

    method_information = method.get_information()
    if method_information:
        method_label += "\\nLocal registers v%d ... v%d" % (
            method_information["registers"][0],
            method_information["registers"][1])
        if "params" in method_information:
            for register, rtype in method_information["params"]:
                method_label += "\\nparam v%d = %s" % (register, rtype)
        method_label += "\\nreturn = %s" % (method_information["return"])

    return {'name': method_label, 'nodes': blocks_html, 'edges': edges_html}
146851
static String generateParamList(JsDoc jsDoc) {
    ImmutableList<JsDoc.Param> params = jsDoc.params();
    List<String> functionParameters = new ArrayList<>();
    for (JsDoc.Param param : params) {
      if ("param".equals(param.annotationType())) {
        functionParameters.add(param.paramTypeName());
      }
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < functionParameters.size(); i++) {
      sb.append(functionParameters.get(i));
      if (i + 1 < functionParameters.size()) {
        sb.append(", ");
      }
    }
    return sb.toString();
  }
152271
def colorize_text(self, text):
        """"""
        # As originally implemented, this method acts upon all the contents of
        # the file as a single string using the MULTILINE option of the re
        # package. I believe this was ostensibly for performance reasons, but
        # it has a few side effects that are less than ideal. It's non-trivial
        # to avoid some substitutions based on other matches using this
        # technique, for example. In the case of block indents, e.g., backticks
        # that occur in the example ($ pwd is `pwd`) should not be escaped.
        # With the MULTILINE flag that is not simple. colorize_backticks() is
        # currently operating on a line by line basis and special casing for
        # this scenario. If these special cases proliferate, the line breaking
        # should occur here in order to minimize the number of iterations.

        result = text
        result = self.colorize_heading(result)
        result = self.colorize_block_indent(result)
        result = self.colorize_backticks(result)
        return result
21521
def pretty(self, indent=0, debug=False):
        
        debug_details = ''
        if debug:
            debug_details += '<isliteral=%r, iscanonical=%r>' % (self.isliteral, self.iscanonical)

        obj = "'%s'" % self.obj if isinstance(self.obj, basestring) else repr(self.obj)
        return (' ' * indent) + ('%s(%s%s)' % (self.__class__.__name__, debug_details, obj))