Use `vd()`, `pr()` and `pd()` to output object structures with HTML `pre` tag and some basic syntax highlighting

@label print_r
@group Data
552368
public function print_r()
	{
		p('Use <code>pr()</code> to format and <code>print_r()</code>:');
		pr($this->data());

		p('Use <code>vd()</code> to format and <code>var_dump()</code>, with a slightly tweaked structure to bring it more into line with <code>pr()</code>:');
		vd($this->data());
		p('Note that all functions take variadic parameters, so you do the following:');
		echo '<pre class="code php">pr($foo, $bar, $baz);</pre>';
	}
609843
def custom_print(data_structure, indent):
    
    for key, value in data_structure.items():
        print("\n%s%s:" % (' ' * attribute_indent * indent, str(key)), end=' ')
        if isinstance(value, OrderedDict):
            custom_print(value, indent + 1)
        elif isinstance(value, dict):
            custom_print(value, indent + 1)
        else:
            print("%s" % (str(value)), end=' ')
119706
def _dump(self):
        """"""
        pp = pprint.PrettyPrinter(indent=4)

        print("=== Variables ===")
        print("-- Globals --")
        pp.pprint(self._global)
        print("-- Bot vars --")
        pp.pprint(self._var)
        print("-- Substitutions --")
        pp.pprint(self._sub)
        print("-- Person Substitutions --")
        pp.pprint(self._person)
        print("-- Arrays --")
        pp.pprint(self._array)

        print("=== Topic Structure ===")
        pp.pprint(self._topics)
        print("=== %Previous Structure ===")
        pp.pprint(self._thats)

        print("=== Includes ===")
        pp.pprint(self._includes)

        print("=== Inherits ===")
        pp.pprint(self._lineage)

        print("=== Sort Buffer ===")
        pp.pprint(self._sorted)

        print("=== Syntax Tree ===")
        pp.pprint(self._syntax)
278125
function _highlight(node, callback) {
    callback = callback || function() {};

    // The first argument can be an Event or a DOM Element.
    //
    // I was originally checking instanceof Event but that made it break
    // when using mootools.
    //
    // @see https://github.com/ccampbell/rainbow/issues/32
    node = node && typeof node.getElementsByTagName === 'function' ? node : document;

    const preBlocks = node.getElementsByTagName('pre');
    const codeBlocks = node.getElementsByTagName('code');
    const finalPreBlocks = [];
    const finalCodeBlocks = [];

    // First loop through all pre blocks to find which ones to highlight
    for (const preBlock of preBlocks) {
        _addPreloader(preBlock);

        // Strip whitespace around code tags when they are inside of a pre
        // tag.  This makes the themes look better because you can't
        // accidentally add extra linebreaks at the start and end.
        //
        // When the pre tag contains a code tag then strip any extra
        // whitespace.
        //
        // For example:
        //
        // <pre>
        //      <code>var foo = true;</code>
        // </pre>
        //
        // will become:
        //
        // <pre><code>var foo = true;</code></pre>
        //
        // If you want to preserve whitespace you can use a pre tag on
        // its own without a code tag inside of it.
        if (preBlock.getElementsByTagName('code').length) {

            // This fixes a race condition when Rainbow.color is called before
            // the previous color call has finished.
            if (!preBlock.getAttribute('data-trimmed')) {
                preBlock.setAttribute('data-trimmed', true);
                preBlock.innerHTML = preBlock.innerHTML.trim();
            }
            continue;
        }

        // If the pre block has no code blocks then we are going to want to
        // process it directly.
        finalPreBlocks.push(preBlock);
    }

    // @see http://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript
    // We are going to process all <code> blocks
    for (const codeBlock of codeBlocks) {
        finalCodeBlocks.push(codeBlock);
    }

    _highlightCodeBlocks(finalCodeBlocks.concat(finalPreBlocks), callback);
}
871826
def render_html(data_dir, output_dir):
    
    env = Environment(loader=PackageLoader('pa11ycrawler', 'templates'))
    env.globals["wcag_refs"] = wcag_refs
    pages = []
    counter = collections.Counter()
    grouped_violations = collections.defaultdict(dict)

    # render detail templates
    for data_file in data_dir.files('*.json'):
        data = json.load(data_file.open())
        num_error, num_warning, num_notice = pa11y_counts(data['pa11y'])

        data["num_error"] = num_error
        data["num_warning"] = num_warning
        data["num_notice"] = num_notice
        fname = data_file.namebase + ".html"
        html_path = output_dir / fname
        render_template(env, html_path, 'detail.html', data)

        data["filename"] = fname
        pages.append(data)

        for violation in data['pa11y']:
            violation_id = hashlib.md5(
                (violation['selector'] + violation['code']).encode('utf-8')
            ).hexdigest()

            if violation_id not in grouped_violations[violation['type']]:
                violation['pages'] = []
                grouped_violations[violation['type']][violation_id] = violation
                counter[violation['type']] += 1

            grouped_violations[violation['type']][violation_id]['pages'].append({
                'url': data['url'],
                'page_title': data['page_title']
            })

    def extract_nums(page):
        "Used to sort pages by violation counts"
        return (
            page["num_error"],
            page["num_warning"],
            page["num_notice"],
        )

    index_path = output_dir / INDEX_TEMPLATE
    render_template(env, index_path, INDEX_TEMPLATE, {
        "pages": sorted(pages, key=extract_nums, reverse=True),
        "num_error": counter["error"],
        "num_warning": counter["warning"],
        "num_notice": counter["notice"]
    })

    for violation_type in grouped_violations:
        unique_path = output_dir / u'{}s.html'.format(violation_type)
        render_template(env, unique_path, UNIQUE_TEMPLATE, {
            "grouped_violations": sorted(
                grouped_violations[violation_type].values(),
                key=lambda item: len(item['pages']),
                reverse=True
            ),
            "current_type": violation_type,
            "violation_counts": counter
        })
145897
def pprint(data, tag_lookup, indent=0):
    """"""
    output = ''
    if isinstance(data, dict):
        for key, value in data.items():
            tag = tag_lookup(key)
            if isinstance(value, (dict, list)) and tag.type is not read_bplist:
                output += '{0}{1}: {2}\n'.format(indent*' ', key, tag)
                output += pprint(value, tag_lookup, indent+2)
            else:
                output += '{0}{1}: {2} {3}\n'.format(
                    indent*' ', key, str(value), tag)
    elif isinstance(data, list):
        for elem in data:
            output += pprint(elem, tag_lookup, indent)
    else:
        raise exceptions.InvalidDmapDataError(
            'invalid dmap data: ' + str(data))
    return output
846342
def do_show(self, args):
		""""""
		self.print_line('')
		if args.thing == 'modules':
			self.print_line('Modules' + os.linesep + '=======')
			headers = ('Name', 'Description')
			rows = [(module.path, module.description) for module in self.frmwk.modules.values()]
		else:
			if self.frmwk.current_module and args.thing == 'options':
				options = self.frmwk.current_module.options
				self.print_line('Module Options' + os.linesep + '==============')
			if self.frmwk.current_module and args.thing == 'advanced':
				options = self.frmwk.current_module.advanced_options
				self.print_line('Advanced Module Options' + os.linesep + '=======================')
			elif self.frmwk.current_module is None and args.thing == 'options':
				options = self.frmwk.options
				self.print_line('Framework Options' + os.linesep + '=================')
			elif self.frmwk.current_module is None and args.thing == 'advanced':
				options = self.frmwk.advanced_options
				self.print_line('Advanced Framework Options' + os.linesep + '==========================')
			headers = ('Name', 'Value', 'Description')
			raw_options = [options.get_option(name) for name in options]
			rows = [(option.name, str(option.value), option.help) for option in raw_options]
		rows = sorted(rows, key=lambda row: row[0])
		self.print_line('')
		self.frmwk.print_table(rows, headers=headers, line_prefix='  ')
		self.print_line('')
		return
1108463
def print_subcommands(data, nested_content, markDownHelp=False, settings=None):
    

    definitions = map_nested_definitions(nested_content)
    items = []
    if 'children' in data:
        subCommands = nodes.section(ids=["Sub-commands:"])
        subCommands += nodes.title('Sub-commands:', 'Sub-commands:')

        for child in data['children']:
            sec = nodes.section(ids=[child['name']])
            sec += nodes.title(child['name'], child['name'])

            if 'description' in child and child['description']:
                desc = [child['description']]
            elif child['help']:
                desc = [child['help']]
            else:
                desc = ['Undocumented']

            # Handle nested content
            subContent = []
            if child['name'] in definitions:
                classifier, s, subContent = definitions[child['name']]
                if classifier == '@replace':
                    desc = [s]
                elif classifier == '@after':
                    desc.append(s)
                elif classifier == '@before':
                    desc.insert(0, s)

            for element in renderList(desc, markDownHelp):
                sec += element
            sec += nodes.literal_block(text=child['bare_usage'])
            for x in print_action_groups(child, nested_content + subContent, markDownHelp,
                                         settings=settings):
                sec += x

            for x in print_subcommands(child, nested_content + subContent, markDownHelp,
                                       settings=settings):
                sec += x

            if 'epilog' in child and child['epilog']:
                for element in renderList([child['epilog']], markDownHelp):
                    sec += element

            subCommands += sec
        items.append(subCommands)

    return items
1177190
function display_body(body, is_toplevel, output, allow_directives) {
          var last = body.length - 1;
          in_directive = allow_directives;
          body.forEach(function(stmt, i) {
              if (in_directive === true && !(stmt instanceof AST_Directive ||
                  stmt instanceof AST_EmptyStatement ||
                  (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String)
              )) {
                  in_directive = false;
              }
              if (!(stmt instanceof AST_EmptyStatement)) {
                  output.indent();
                  stmt.print(output);
                  if (!(i == last && is_toplevel)) {
                      output.newline();
                      if (is_toplevel) output.newline();
                  }
              }
              if (in_directive === true &&
                  stmt instanceof AST_SimpleStatement &&
                  stmt.body instanceof AST_String
              ) {
                  in_directive = false;
              }
          });
          in_directive = false;
      }
611679
def _repr_html_(self):
        """"""
        fmt = ""
        if self.n_scalars > 0:
            fmt += "<table>"
            fmt += "<tr><th>Header</th><th>Data Arrays</th></tr>"
            fmt += "<tr><td>"
        # Get the header info
        fmt += self.head(display=False, html=True)
        # Fill out scalar arrays
        if self.n_scalars > 0:
            fmt += "</td><td>"
            fmt += "\n"
            fmt += "<table>\n"
            row = "<tr><th>{}</th><th>{}</th><th>{}</th><th>{}</th><th>{}</th></tr>\n"
            fmt += row.format("Name", "Field", "Type", "Min", "Max")
            row = "<tr><td>{}</td><td>{}</td><td>{}</td><td>{:.3e}</td><td>{:.3e}</td></tr>\n"

            def format_array(key, field):
                """internal helper to foramt array information for printing"""
                arr = get_scalar(self, key)
                dl, dh = self.get_data_range(key)
                if key == self.active_scalar_info[1]:
                    key = '<b>{}</b>'.format(key)
                return row.format(key, field, arr.dtype, dl, dh)

            for i in range(self.GetPointData().GetNumberOfArrays()):
                key = self.GetPointData().GetArrayName(i)
                fmt += format_array(key, field='Points')
            for i in range(self.GetCellData().GetNumberOfArrays()):
                key = self.GetCellData().GetArrayName(i)
                fmt += format_array(key, field='Cells')
            fmt += "</table>\n"
            fmt += "\n"
            fmt += "</td></tr> </table>"
        return fmt
436258
def prnt(self):
        
        print("= = = =\n\n%s object key: \033[32m%s\033[0m" % (self.__class__.__name__, self.key))
        pprnt(self._data or self.clean_value())
610716
function Graphviz() {
		var sb = []
		function print(x) {
			sb.push(x)
		}
		print("digraph {")

		var seen_nodes = Object.create(null)
		function makeNodeLabel(node) {
			var str = []
			if (node.isObject) {
				str.push("object")
			}
			if (node.isAny) {
				str.push("any")
			}
			if (node.global) {
				str.push("global")
			}
			node.primitives.forEach(function(t) {
				str.push(formatType(t))
			})
			str.push(node.id)
			return str.join(',')
		}
		var tnode_id = 1;
		function makeTypeNodeId() {
			return 'T' + (tnode_id++)
		}
		function visitTypeNode(tnode, id) {
			print(id + ' [shape=diamond]')
		}
		function visitNode(node) {
			node = node.rep()
			if (seen_nodes[node.id])
				return
			seen_nodes[node.id] = true
			print(node.id + ' [shape=box,label="' + escapeLabel(makeNodeLabel(node)) + '"]')
			if (!node.global || isLive(node)) {
				markAsLive(node)
				node.properties.forEach(function(name,dst) {
					if (name in {})
						return // ignore trivial properties
					if (dst.type === 'node') {
						print(node.id + ' -> ' + dst.node.rep().id + ' [label="' + escapeLabel(name) + '"]')
						visitNode(dst.node)
					} else {
						var id = makeTypeNodeId()
						print(node.id + ' -> ' + id + ' [label="' + escapeLabel(name) + '"]')
						visitTypeNode(dst, id)
					}
				})
				node.prototypes.forEach(function(proto) {
					print(node.id + ' -> ' + proto.rep().id + ' [label="[proto]"]')
					visitNode(proto)
				})
			}
		}

		function visitFNode(fnode) {
			visitNode(fnode.self)
			visitNode(fnode.this)
			visitNode(fnode.arguments)
			visitNode(fnode.return)
			if (fnode.env)
				visitNode(fnode.env)
			// todo: calls?
		}
		var calln = 0
		function visitCall(call) {
			visitNode(call.self)
			visitNode(call.this)
			visitNode(call.arguments)
			visitNode(call.return)
			var id = 'call_' + (calln++)
			print(id + ' [shape=record,label="{{<self> self|<this> this|<arguments> arguments|<return> return}}"]')
			print(call.self.rep().id + " -> " + id + ':self')
			print(call.this.rep().id + " -> " + id + ':this')
			print(call.arguments.rep().id + " -> " + id + ':arguments')
			print(call.return.rep().id + " -> " + id + ':return')
		}

		var node2live = Object.create(null)
		function isLive(node) {
			return node2live[node.rep().id]
		}
		function markAsLive(node) {
			node2live[node.rep().id] = true
		}
		function checkLive(node) {
			node = node.rep()
			if (node.id in node2live)
				return node2live[node.id]
			node2live[node.id] = false
			var isLive = false
			node.properties.forEach(function(name,dst) {
				if (dst.type === 'node' && checkLive(dst.node)) {
					isLive = true
				}
			})
			return node2live[node.id] = isLive
		}
		
		function findAdditionalNodes() {
			all_unodes.forEach(function(node) {
				if (checkLive(node)) {
					visitNode(node)
				}
			})
		}

		this.visitNode = visitNode
		this.visitFNode = visitFNode
		this.visitCall = visitCall
		this.finish = function() {
			findAdditionalNodes()
			print("}\n")
			return sb.join('\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)
23591
def print_results_adj(results, indent=False, prt=sys.stdout):
        """"""
        # Print column headers if there are results to be printed
        if results:
            prt.write("{R}\n".format(R="\t".join(GOEnrichmentStudy.get_prtflds_default(results))))
        # Print the GOEA results
        for rec in results:
            prt.write("{R}\n".format(R=rec.__str__(indent=indent)))
537757
function debugPrint(label, arr, size) {
    var msg = '\n' + label + ' = ';
    for (var i = 0; i < arr.length; i += 2) {
        if (size === 32) {
            msg += uint32ToHex(arr[i]).toUpperCase();
            msg += ' ';
            msg += uint32ToHex(arr[i + 1]).toUpperCase();
        }
        else if (size === 64) {
            msg += uint32ToHex(arr[i + 1]).toUpperCase();
            msg += uint32ToHex(arr[i]).toUpperCase();
        }
        else
            throw new Error('Invalid size ' + size);
        if (i % 6 === 4) {
            msg += '\n' + new Array(label.length + 4).join(' ');
        }
        else if (i < arr.length - 2) {
            msg += ' ';
        }
    }
}
387439
function dump($show_attr = true, $deep = 0)
    {
        $lead = str_repeat('	', $deep);

        echo $lead . $this->tag;
        if ($show_attr && count($this->attr) > 0) {
            echo '(';
            foreach ($this->attr as $k => $v) {
                echo "[$k]=>\"" . $this->$k . '", ';
            }
            echo ')';
        }
        echo "\n";

        if ($this->nodes) {
            foreach ($this->nodes as $c) {
                $c->dump($show_attr, $deep + 1);
            }
        }
    }
881197
public void printHtmlType(PrintWriter out, String strTag, String strParams, String strData)
    {
        out.print(m_recDetail.getField(MenusModel.TYPE).toString());
    }