text:
#include "config.h"
#include "core/editing/MarkupAccumulator.h"

#include "HTMLNames.h"
#include "XLinkNames.h"
#include "XMLNSNames.h"
#include "XMLNames.h"
#include "core/dom/CDATASection.h"
#include "core/dom/Comment.h"
#include "core/dom/DocumentFragment.h"
#include "core/dom/DocumentType.h"
#include "core/dom/ProcessingInstruction.h"
#include "core/editing/Editor.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLTemplateElement.h"
#include "platform/weborigin/KURL.h"
#include "wtf/unicode/CharacterNames.h"

namespace WebCore {

using namespace HTMLNames;

void MarkupAccumulator::appendCharactersReplacingEntities(StringBuilder& result, const String& source, unsigned offset, unsigned length, EntityMask entityMask)
{
    DEFINE_STATIC_LOCAL(const String, ampReference, ("&"));
    DEFINE_STATIC_LOCAL(const String, ltReference, ("<"));
    DEFINE_STATIC_LOCAL(const String, gtReference, (">"));
    DEFINE_STATIC_LOCAL(const String, quotReference, ("""));
    DEFINE_STATIC_LOCAL(const String, nbspReference, (" "));

    static const EntityDescription entityMaps[] = {
        { '&', ampReference, EntityAmp },
        { '<', ltReference, EntityLt },
        { '>', gtReference, EntityGt },
        { '"', quotReference, EntityQuot },
        { noBreakSpace, nbspReference, EntityNbsp },
    };

    if (!(offset + length))
        return;

    ASSERT(offset + length <= source.length());

    if (source.is8Bit()) {
        const LChar* text = source.characters8() + offset;

        size_t positionAfterLastEntity = 0;
        for (size_t i = 0; i < length; ++i) {
            for (size_t entityIndex = 0; entityIndex < WTF_ARRAY_LENGTH(entityMaps); ++entityIndex) {
                if (text[i] == entityMaps[entityIndex].entity && entityMaps[entityIndex].mask & entityMask) {
                    result.append(text + positionAfterLastEntity, i - positionAfterLastEntity);
                    result.append(entityMaps[entityIndex].reference);
                    positionAfterLastEntity = i + 1;
                    break;
                }
            }
        }
        result.append(text + positionAfterLastEntity, length - positionAfterLastEntity);
    } else {
        const UChar* text = source.characters16() + offset;

        size_t positionAfterLastEntity = 0;
        for (size_t i = 0; i < length; ++i) {
            for (size_t entityIndex = 0; entityIndex < WTF_ARRAY_LENGTH(entityMaps); ++entityIndex) {
                if (text[i] == entityMaps[entityIndex].entity && entityMaps[entityIndex].mask & entityMask) {
                    result.append(text + positionAfterLastEntity, i - positionAfterLastEntity);
                    result.append(entityMaps[entityIndex].reference);
                    positionAfterLastEntity = i + 1;
                    break;
                }
            }
        }
        result.append(text + positionAfterLastEntity, length - positionAfterLastEntity);
    }
}

MarkupAccumulator::MarkupAccumulator(Vector<Node*>* nodes, EAbsoluteURLs resolveUrlsMethod, const Range* range)
    : m_nodes(nodes)
    , m_range(range)
    , m_resolveURLsMethod(resolveUrlsMethod)
{
}

MarkupAccumulator::~MarkupAccumulator()
{
}

String MarkupAccumulator::serializeNodes(Node* targetNode, EChildrenOnly childrenOnly)
{
    return serializeNodes(targetNode, childrenOnly, 0);
}

String MarkupAccumulator::serializeNodes(Node* targetNode, EChildrenOnly childrenOnly, Vector<QualifiedName>* tagNamesToSkip)
{
    serializeNodesWithNamespaces(targetNode, childrenOnly, 0, tagNamesToSkip);
    return m_markup.toString();
}

void MarkupAccumulator::serializeNodesWithNamespaces(Node* targetNode, EChildrenOnly childrenOnly, const Namespaces* namespaces, Vector<QualifiedName>* tagNamesToSkip)
{
    if (tagNamesToSkip) {
        for (size_t i = 0; i < tagNamesToSkip->size(); ++i) {
            if (targetNode->hasTagName(tagNamesToSkip->at(i)))
                return;
        }
    }

    Namespaces namespaceHash;
    if (namespaces)
        namespaceHash = *namespaces;

    if (!childrenOnly)
        appendStartTag(targetNode, &namespaceHash);

    if (!(targetNode->document().isHTMLDocument() && elementCannotHaveEndTag(targetNode))) {
        Node* current = targetNode->hasTagName(templateTag) ? toHTMLTemplateElement(targetNode)->content()->firstChild() : targetNode->firstChild();
        for ( ; current; current = current->nextSibling())
            serializeNodesWithNamespaces(current, IncludeNode, &namespaceHash, tagNamesToSkip);
    }

    if (!childrenOnly)
        appendEndTag(targetNode);
}

String MarkupAccumulator::resolveURLIfNeeded(const Element* element, const String& urlString) const
{
    switch (m_resolveURLsMethod) {
    case ResolveAllURLs:
        return element->document().completeURL(urlString).string();

    case ResolveNonLocalURLs:
        if (!element->document().url().isLocalFile())
            return element->document().completeURL(urlString).string();
        break;

    case DoNotResolveURLs:
        break;
    }
    return urlString;
}

void MarkupAccumulator::appendString(const String& string)
{
    m_markup.append(string);
}

void MarkupAccumulator::appendStartTag(Node* node, Namespaces* namespaces)
{
    appendStartMarkup(m_markup, node, namespaces);
    if (m_nodes)
        m_nodes->append(node);
}

void MarkupAccumulator::appendEndTag(Node* node)
{
    appendEndMarkup(m_markup, node);
}

size_t MarkupAccumulator::totalLength(const Vector<String>& strings)
{
    size_t length = 0;
    for (size_t i = 0; i < strings.size(); ++i)
        length += strings[i].length();
    return length;
}

void MarkupAccumulator::concatenateMarkup(StringBuilder& result)
{
    result.append(m_markup);
}

void MarkupAccumulator::appendAttributeValue(StringBuilder& result, const String& attribute, bool documentIsHTML)
{
    appendCharactersReplacingEntities(result, attribute, 0, attribute.length(),
        documentIsHTML ? EntityMaskInHTMLAttributeValue : EntityMaskInAttributeValue);
}

void MarkupAccumulator::appendCustomAttributes(StringBuilder&, Element*, Namespaces*)
{
}

void MarkupAccumulator::appendQuotedURLAttributeValue(StringBuilder& result, const Element* element, const Attribute& attribute)
{
    ASSERT(element->isURLAttribute(attribute));
    const String resolvedURLString = resolveURLIfNeeded(element, attribute.value());
    UChar quoteChar = '"';
    String strippedURLString = resolvedURLString.stripWhiteSpace();
    if (protocolIsJavaScript(strippedURLString)) {
        // minimal escaping for javascript urls
        if (strippedURLString.contains('"')) {
            if (strippedURLString.contains('\''))
                strippedURLString.replaceWithLiteral('"', """);
            else
                quoteChar = '\'';
        }
        result.append(quoteChar);
        result.append(strippedURLString);
        result.append(quoteChar);
        return;
    }

    // FIXME: This does not fully match other browsers. Firefox percent-escapes non-ASCII characters for innerHTML.
    result.append(quoteChar);
    appendAttributeValue(result, resolvedURLString, false);
    result.append(quoteChar);
}

void MarkupAccumulator::appendNodeValue(StringBuilder& result, const Node* node, const Range* range, EntityMask entityMask)
{
    const String str = node->nodeValue();
    unsigned length = str.length();
    unsigned start = 0;

    if (range) {
        if (node == range->endContainer())
            length = range->endOffset();
        if (node == range->startContainer()) {
            start = range->startOffset();
            length -= start;
        }
    }

    appendCharactersReplacingEntities(result, str, start, length, entityMask);
}

bool MarkupAccumulator::shouldAddNamespaceElement(const Element* element)
{
    // Don't add namespace attribute if it is already defined for this elem.
    const AtomicString& prefix = element->prefix();
    if (prefix.isEmpty())
        return !element->hasAttribute(xmlnsAtom);

    DEFINE_STATIC_LOCAL(String, xmlnsWithColon, ("xmlns:"));
    return !element->hasAttribute(xmlnsWithColon + prefix);
}

bool MarkupAccumulator::shouldAddNamespaceAttribute(const Attribute& attribute, Namespaces& namespaces)
{
    // Don't add namespace attributes twice
    if (attribute.name() == XMLNSNames::xmlnsAttr) {
        namespaces.set(emptyAtom.impl(), attribute.value().impl());
        return false;
    }

    QualifiedName xmlnsPrefixAttr(xmlnsAtom, attribute.localName(), XMLNSNames::xmlnsNamespaceURI);
    if (attribute.name() == xmlnsPrefixAttr) {
        namespaces.set(attribute.localName().impl(), attribute.value().impl());
        return false;
    }

    return true;
}

void MarkupAccumulator::appendNamespace(StringBuilder& result, const AtomicString& prefix, const AtomicString& namespaceURI, Namespaces& namespaces)
{
    if (namespaceURI.isEmpty())
        return;

    // Use emptyAtoms's impl() for both null and empty strings since the HashMap can't handle 0 as a key
    StringImpl* pre = prefix.isEmpty() ? emptyAtom.impl() : prefix.impl();
    StringImpl* foundNS = namespaces.get(pre);
    if (foundNS != namespaceURI.impl()) {
        namespaces.set(pre, namespaceURI.impl());
        result.append(' ');
        result.append(xmlnsAtom.string());
        if (!prefix.isEmpty()) {
            result.append(':');
            result.append(prefix);
        }

        result.append('=');
        result.append('"');
        appendAttributeValue(result, namespaceURI, false);
        result.append('"');
    }
}

EntityMask MarkupAccumulator::entityMaskForText(Text* text) const
{
    if (!text->document().isHTMLDocument())
        return EntityMaskInPCDATA;

    const QualifiedName* parentName = 0;
    if (text->parentElement())
        parentName = &(text->parentElement())->tagQName();

    if (parentName && (*parentName == scriptTag || *parentName == styleTag || *parentName == xmpTag))
        return EntityMaskInCDATA;
    return EntityMaskInHTMLPCDATA;
}

void MarkupAccumulator::appendText(StringBuilder& result, Text* text)
{
    appendNodeValue(result, text, m_range, entityMaskForText(text));
}

void MarkupAccumulator::appendComment(StringBuilder& result, const String& comment)
{
    // FIXME: Comment content is not escaped, but XMLSerializer (and possibly other callers) should raise an exception if it includes "-->".
    result.appendLiteral("<!--");
    result.append(comment);
    result.appendLiteral("-->");
}

void MarkupAccumulator::appendXMLDeclaration(StringBuilder& result, const Document* document)
{
    if (!document->hasXMLDeclaration())
        return;

    result.appendLiteral("<?xml version=\"");
    result.append(document->xmlVersion());
    const String& encoding = document->xmlEncoding();
    if (!encoding.isEmpty()) {
        result.appendLiteral("\" encoding=\"");
        result.append(encoding);
    }
    if (document->xmlStandaloneStatus() != Document::StandaloneUnspecified) {
        result.appendLiteral("\" standalone=\"");
        if (document->xmlStandalone())
            result.appendLiteral("yes");
        else
            result.appendLiteral("no");
    }

    result.appendLiteral("\"?>");
}

void MarkupAccumulator::appendDocumentType(StringBuilder& result, const DocumentType* n)
{
    if (n->name().isEmpty())
        return;

    result.appendLiteral("<!DOCTYPE ");
    result.append(n->name());
    if (!n->publicId().isEmpty()) {
        result.appendLiteral(" PUBLIC \"");
        result.append(n->publicId());
        result.append('"');
        if (!n->systemId().isEmpty()) {
            result.append(' ');
            result.append('"');
            result.append(n->systemId());
            result.append('"');
        }
    } else if (!n->systemId().isEmpty()) {
        result.appendLiteral(" SYSTEM \"");
        result.append(n->systemId());
        result.append('"');
    }
    if (!n->internalSubset().isEmpty()) {
        result.append(' ');
        result.append('[');
        result.append(n->internalSubset());
        result.append(']');
    }
    result.append('>');
}

void MarkupAccumulator::appendProcessingInstruction(StringBuilder& result, const String& target, const String& data)
{
    // FIXME: PI data is not escaped, but XMLSerializer (and possibly other callers) this should raise an exception if it includes "?>".
    result.append('<');
    result.append('?');
    result.append(target);
    result.append(' ');
    result.append(data);
    result.append('?');
    result.append('>');
}

void MarkupAccumulator::appendElement(StringBuilder& result, Element* element, Namespaces* namespaces)
{
    appendOpenTag(result, element, namespaces);

    if (element->hasAttributes()) {
        unsigned length = element->attributeCount();
        for (unsigned int i = 0; i < length; i++)
            appendAttribute(result, element, *element->attributeItem(i), namespaces);
    }

    // Give an opportunity to subclasses to add their own attributes.
    appendCustomAttributes(result, element, namespaces);

    appendCloseTag(result, element);
}

void MarkupAccumulator::appendOpenTag(StringBuilder& result, Element* element, Namespaces* namespaces)
{
    result.append('<');
    result.append(element->nodeNamePreservingCase());
    if (!element->document().isHTMLDocument() && namespaces && shouldAddNamespaceElement(element))
        appendNamespace(result, element->prefix(), element->namespaceURI(), *namespaces);
}

void MarkupAccumulator::appendCloseTag(StringBuilder& result, Element* element)
{
    if (shouldSelfClose(element)) {
        if (element->isHTMLElement())
            result.append(' '); // XHTML 1.0 <-> HTML compatibility.
        result.append('/');
    }
    result.append('>');
}

static inline bool attributeIsInSerializedNamespace(const Attribute& attribute)
{
    return attribute.namespaceURI() == XMLNames::xmlNamespaceURI
        || attribute.namespaceURI() == XLinkNames::xlinkNamespaceURI
        || attribute.namespaceURI() == XMLNSNames::xmlnsNamespaceURI;
}

void MarkupAccumulator::appendAttribute(StringBuilder& result, Element* element, const Attribute& attribute, Namespaces* namespaces)
{
    bool documentIsHTML = element->document().isHTMLDocument();

    result.append(' ');

    if (documentIsHTML && !attributeIsInSerializedNamespace(attribute))
        result.append(attribute.name().localName());
    else {
        QualifiedName prefixedName = attribute.name();
        if (attribute.namespaceURI() == XLinkNames::xlinkNamespaceURI) {
            if (!attribute.prefix())
                prefixedName.setPrefix(xlinkAtom);
        } else if (attribute.namespaceURI() == XMLNames::xmlNamespaceURI) {
            if (!attribute.prefix())
                prefixedName.setPrefix(xmlAtom);
        } else if (attribute.namespaceURI() == XMLNSNames::xmlnsNamespaceURI) {
            if (attribute.name() != XMLNSNames::xmlnsAttr && !attribute.prefix())
                prefixedName.setPrefix(xmlnsAtom);
        }
        result.append(prefixedName.toString());
    }

    result.append('=');

    if (element->isURLAttribute(attribute))
        appendQuotedURLAttributeValue(result, element, attribute);
    else {
        result.append('"');
        appendAttributeValue(result, attribute.value(), documentIsHTML);
        result.append('"');
    }

    if (!documentIsHTML && namespaces && shouldAddNamespaceAttribute(attribute, *namespaces))
        appendNamespace(result, attribute.prefix(), attribute.namespaceURI(), *namespaces);
}

void MarkupAccumulator::appendCDATASection(StringBuilder& result, const String& section)
{
    // FIXME: CDATA content is not escaped, but XMLSerializer (and possibly other callers) should raise an exception if it includes "]]>".
    result.appendLiteral("<![CDATA[");
    result.append(section);
    result.appendLiteral("]]>");
}

void MarkupAccumulator::appendStartMarkup(StringBuilder& result, const Node* node, Namespaces* namespaces)
{
    switch (node->nodeType()) {
    case Node::TEXT_NODE:
        appendText(result, toText(const_cast<Node*>(node)));
        break;
    case Node::COMMENT_NODE:
        appendComment(result, toComment(node)->data());
        break;
    case Node::DOCUMENT_NODE:
        appendXMLDeclaration(result, toDocument(node));
        break;
    case Node::DOCUMENT_FRAGMENT_NODE:
        break;
    case Node::DOCUMENT_TYPE_NODE:
        appendDocumentType(result, toDocumentType(node));
        break;
    case Node::PROCESSING_INSTRUCTION_NODE:
        appendProcessingInstruction(result, toProcessingInstruction(node)->target(), toProcessingInstruction(node)->data());
        break;
    case Node::ELEMENT_NODE:
        appendElement(result, toElement(const_cast<Node*>(node)), namespaces);
        break;
    case Node::CDATA_SECTION_NODE:
        appendCDATASection(result, toCDATASection(node)->data());
        break;
    case Node::ATTRIBUTE_NODE:
    case Node::ENTITY_NODE:
    case Node::NOTATION_NODE:
    case Node::XPATH_NAMESPACE_NODE:
        ASSERT_NOT_REACHED();
        break;
    }
}

// Rules of self-closure
// 1. No elements in HTML documents use the self-closing syntax.
// 2. Elements w/ children never self-close because they use a separate end tag.
// 3. HTML elements which do not have a "forbidden" end tag will close with a separate end tag.
// 4. Other elements self-close.
bool MarkupAccumulator::shouldSelfClose(const Node* node)
{
    if (node->document().isHTMLDocument())
        return false;
    if (node->hasChildNodes())
        return false;
    if (node->isHTMLElement() && !elementCannotHaveEndTag(node))
        return false;
    return true;
}

bool MarkupAccumulator::elementCannotHaveEndTag(const Node* node)
{
    if (!node->isHTMLElement())
        return false;

    // FIXME: ieForbidsInsertHTML may not be the right function to call here
    // ieForbidsInsertHTML is used to disallow setting innerHTML/outerHTML
    // or createContextualFragment.  It does not necessarily align with
    // which elements should be serialized w/o end tags.
    return toHTMLElement(node)->ieForbidsInsertHTML();
}

void MarkupAccumulator::appendEndMarkup(StringBuilder& result, const Node* node)
{
    if (!node->isElementNode() || shouldSelfClose(node) || (!node->hasChildNodes() && elementCannotHaveEndTag(node)))
        return;

    result.append('<');
    result.append('/');
    result.append(toElement(node)->nodeNamePreservingCase());
    result.append('>');
}

}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _Base = require('./Base');

var _Base2 = _interopRequireDefault(_Base);

var _config = require('./config');

var _config2 = _interopRequireDefault(_config);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Toolbar component that vertically centers children with display flex
 */

var Toolbar = function Toolbar(props, _ref) {
  var rebass = _ref.rebass;

  var _config$rebass = _extends({}, _config2.default, rebass),
      scale = _config$rebass.scale,
      colors = _config$rebass.colors;

  return _react2.default.createElement(_Base2.default, _extends({}, props, {
    className: 'Toolbar',
    baseStyle: {
      display: 'flex',
      alignItems: 'center',
      minHeight: 48,
      paddingLeft: scale[1],
      paddingRight: scale[1],
      color: colors.white,
      backgroundColor: colors.primary
    } }));
};

Toolbar.contextTypes = {
  rebass: _react2.default.PropTypes.object
};

exports.default = Toolbar;

redpajama_set_name: RedPajamaGithub


text:
use code_translator::translate_operator;
use cretonne::entity::EntityRef;
use cretonne::ir::{self, InstBuilder, Ebb};
use cretonne::result::{CtonResult, CtonError};
use cretonne::timing;
use cton_frontend::{FunctionBuilderContext, FunctionBuilder, Variable};
use environ::FuncEnvironment;
use state::TranslationState;
use wasmparser::{self, BinaryReader};

/// WebAssembly to Cretonne IL function translator.
///
/// A `FuncTranslator` is used to translate a binary WebAssembly function into Cretonne IL guided
/// by a `FuncEnvironment` object. A single translator instance can be reused to translate multiple
/// functions which will reduce heap allocation traffic.
pub struct FuncTranslator {
    func_ctx: FunctionBuilderContext<Variable>,
    state: TranslationState,
}

impl FuncTranslator {
    /// Create a new translator.
    pub fn new() -> Self {
        Self {
            func_ctx: FunctionBuilderContext::new(),
            state: TranslationState::new(),
        }
    }

    /// Translate a binary WebAssembly function.
    ///
    /// The `code` slice contains the binary WebAssembly *function code* as it appears in the code
    /// section of a WebAssembly module, not including the initial size of the function code. The
    /// slice is expected to contain two parts:
    ///
    /// - The declaration of *locals*, and
    /// - The function *body* as an expression.
    ///
    /// See [the WebAssembly specification][wasm].
    ///
    /// [wasm]: https://webassembly.github.io/spec/binary/modules.html#code-section
    ///
    /// The Cretonne IR function `func` should be completely empty except for the `func.signature`
    /// and `func.name` fields. The signature may contain special-purpose arguments which are not
    /// regarded as WebAssembly local variables. Any signature arguments marked as
    /// `ArgumentPurpose::Normal` are made accessible as WebAssembly local variables.
    ///
    pub fn translate<FE: FuncEnvironment + ?Sized>(
        &mut self,
        code: &[u8],
        func: &mut ir::Function,
        environ: &mut FE,
    ) -> CtonResult {
        self.translate_from_reader(BinaryReader::new(code), func, environ)
    }

    /// Translate a binary WebAssembly function from a `BinaryReader`.
    pub fn translate_from_reader<FE: FuncEnvironment + ?Sized>(
        &mut self,
        mut reader: BinaryReader,
        func: &mut ir::Function,
        environ: &mut FE,
    ) -> CtonResult {
        let _tt = timing::wasm_translate_function();
        dbg!(
            "translate({} bytes, {}{})",
            reader.bytes_remaining(),
            func.name,
            func.signature
        );
        debug_assert_eq!(func.dfg.num_ebbs(), 0, "Function must be empty");
        debug_assert_eq!(func.dfg.num_insts(), 0, "Function must be empty");

        // This clears the `FunctionBuilderContext`.
        let mut builder = FunctionBuilder::new(func, &mut self.func_ctx);
        let entry_block = builder.create_ebb();
        builder.append_ebb_params_for_function_params(entry_block);
        builder.switch_to_block(entry_block); // This also creates values for the arguments.
        builder.seal_block(entry_block);
        // Make sure the entry block is inserted in the layout before we make any callbacks to
        // `environ`. The callback functions may need to insert things in the entry block.
        builder.ensure_inserted_ebb();

        let num_params = declare_wasm_parameters(&mut builder, entry_block);

        // Set up the translation state with a single pushed control block representing the whole
        // function and its return values.
        let exit_block = builder.create_ebb();
        builder.append_ebb_params_for_function_returns(exit_block);
        self.state.initialize(&builder.func.signature, exit_block);

        parse_local_decls(&mut reader, &mut builder, num_params)?;
        parse_function_body(reader, &mut builder, &mut self.state, environ)?;

        builder.finalize();
        Ok(())
    }
}

/// Declare local variables for the signature parameters that correspond to WebAssembly locals.
///
/// Return the number of local variables declared.
fn declare_wasm_parameters(builder: &mut FunctionBuilder<Variable>, entry_block: Ebb) -> usize {
    let sig_len = builder.func.signature.params.len();
    let mut next_local = 0;
    for i in 0..sig_len {
        let param_type = builder.func.signature.params[i];
        // There may be additional special-purpose parameters following the normal WebAssembly
        // signature parameters. For example, a `vmctx` pointer.
        if param_type.purpose == ir::ArgumentPurpose::Normal {
            // This is a normal WebAssembly signature parameter, so create a local for it.
            let local = Variable::new(next_local);
            builder.declare_var(local, param_type.value_type);
            next_local += 1;

            let param_value = builder.ebb_params(entry_block)[i];
            builder.def_var(local, param_value);
        }
    }

    next_local
}

/// Parse the local variable declarations that precede the function body.
///
/// Declare local variables, starting from `num_params`.
fn parse_local_decls(
    reader: &mut BinaryReader,
    builder: &mut FunctionBuilder<Variable>,
    num_params: usize,
) -> CtonResult {
    let mut next_local = num_params;
    let local_count = reader.read_local_count().map_err(
        |_| CtonError::InvalidInput,
    )?;

    let mut locals_total = 0;
    for _ in 0..local_count {
        builder.set_srcloc(cur_srcloc(reader));
        let (count, ty) = reader.read_local_decl(&mut locals_total).map_err(|_| {
            CtonError::InvalidInput
        })?;
        declare_locals(builder, count, ty, &mut next_local);
    }

    Ok(())
}

/// Declare `count` local variables of the same type, starting from `next_local`.
///
/// Fail of too many locals are declared in the function, or if the type is not valid for a local.
fn declare_locals(
    builder: &mut FunctionBuilder<Variable>,
    count: u32,
    wasm_type: wasmparser::Type,
    next_local: &mut usize,
) {
    // All locals are initialized to 0.
    use wasmparser::Type::*;
    let zeroval = match wasm_type {
        I32 => builder.ins().iconst(ir::types::I32, 0),
        I64 => builder.ins().iconst(ir::types::I64, 0),
        F32 => builder.ins().f32const(ir::immediates::Ieee32::with_bits(0)),
        F64 => builder.ins().f64const(ir::immediates::Ieee64::with_bits(0)),
        _ => panic!("invalid local type"),
    };

    let ty = builder.func.dfg.value_type(zeroval);
    for _ in 0..count {
        let local = Variable::new(*next_local);
        builder.declare_var(local, ty);
        builder.def_var(local, zeroval);
        *next_local += 1;
    }
}

/// Parse the function body in `reader`.
///
/// This assumes that the local variable declarations have already been parsed and function
/// arguments and locals are declared in the builder.
fn parse_function_body<FE: FuncEnvironment + ?Sized>(
    mut reader: BinaryReader,
    builder: &mut FunctionBuilder<Variable>,
    state: &mut TranslationState,
    environ: &mut FE,
) -> CtonResult {
    // The control stack is initialized with a single block representing the whole function.
    debug_assert_eq!(state.control_stack.len(), 1, "State not initialized");

    // Keep going until the final `End` operator which pops the outermost block.
    while !state.control_stack.is_empty() {
        builder.set_srcloc(cur_srcloc(&reader));
        let op = reader.read_operator().map_err(|_| CtonError::InvalidInput)?;
        translate_operator(op, builder, state, environ);
    }

    // The final `End` operator left us in the exit block where we need to manually add a return
    // instruction.
    //
    // If the exit block is unreachable, it may not have the correct arguments, so we would
    // generate a return instruction that doesn't match the signature.
    if state.reachable {
        debug_assert!(builder.is_pristine());
        if !builder.is_unreachable() {
            builder.ins().return_(&state.stack);
        }
    }

    // Discard any remaining values on the stack. Either we just returned them,
    // or the end of the function is unreachable.
    state.stack.clear();

    debug_assert!(reader.eof());

    Ok(())
}

/// Get the current source location from a reader.
fn cur_srcloc(reader: &BinaryReader) -> ir::SourceLoc {
    // We record source locations as byte code offsets relative to the beginning of the function.
    // This will wrap around of a single function's byte code is larger than 4 GB, but a) the
    // WebAssembly format doesn't allow for that, and b) that would hit other Cretonne
    // implementation limits anyway.
    ir::SourceLoc::new(reader.current_position() as u32)
}

#[cfg(test)]
mod tests {
    use cretonne::{ir, Context};
    use cretonne::ir::types::I32;
    use environ::{DummyEnvironment, FuncEnvironment};
    use super::FuncTranslator;

    #[test]
    fn small1() {
        // Implicit return.
        //
        // (func $small1 (param i32) (result i32)
        //     (i32.add (get_local 0) (i32.const 1))
        // )
        const BODY: [u8; 7] = [
            0x00,       // local decl count
            0x20, 0x00, // get_local 0
            0x41, 0x01, // i32.const 1
            0x6a,       // i32.add
            0x0b,       // end
        ];

        let mut trans = FuncTranslator::new();
        let runtime = DummyEnvironment::default();
        let mut ctx = Context::new();

        ctx.func.name = ir::ExternalName::testcase("small1");
        ctx.func.signature.params.push(ir::AbiParam::new(I32));
        ctx.func.signature.returns.push(ir::AbiParam::new(I32));

        trans
            .translate(&BODY, &mut ctx.func, &mut runtime.func_env())
            .unwrap();
        dbg!("{}", ctx.func.display(None));
        ctx.verify(runtime.func_env().flags()).unwrap();
    }

    #[test]
    fn small2() {
        // Same as above, but with an explicit return instruction.
        //
        // (func $small2 (param i32) (result i32)
        //     (return (i32.add (get_local 0) (i32.const 1)))
        // )
        const BODY: [u8; 8] = [
            0x00,       // local decl count
            0x20, 0x00, // get_local 0
            0x41, 0x01, // i32.const 1
            0x6a,       // i32.add
            0x0f,       // return
            0x0b,       // end
        ];

        let mut trans = FuncTranslator::new();
        let runtime = DummyEnvironment::default();
        let mut ctx = Context::new();

        ctx.func.name = ir::ExternalName::testcase("small2");
        ctx.func.signature.params.push(ir::AbiParam::new(I32));
        ctx.func.signature.returns.push(ir::AbiParam::new(I32));

        trans
            .translate(&BODY, &mut ctx.func, &mut runtime.func_env())
            .unwrap();
        dbg!("{}", ctx.func.display(None));
        ctx.verify(runtime.func_env().flags()).unwrap();
    }

    #[test]
    fn infloop() {
        // An infinite loop, no return instructions.
        //
        // (func $infloop (result i32)
        //     (local i32)
        //     (loop (result i32)
        //         (i32.add (get_local 0) (i32.const 1))
        //         (set_local 0)
        //         (br 0)
        //     )
        // )
        const BODY: [u8; 16] = [
            0x01,       // 1 local decl.
            0x01, 0x7f, // 1 i32 local.
            0x03, 0x7f, // loop i32
            0x20, 0x00, // get_local 0
            0x41, 0x01, // i32.const 0
            0x6a,       // i32.add
            0x21, 0x00, // set_local 0
            0x0c, 0x00, // br 0
            0x0b,       // end
            0x0b,       // end
        ];

        let mut trans = FuncTranslator::new();
        let runtime = DummyEnvironment::default();
        let mut ctx = Context::new();

        ctx.func.name = ir::ExternalName::testcase("infloop");
        ctx.func.signature.returns.push(ir::AbiParam::new(I32));

        trans
            .translate(&BODY, &mut ctx.func, &mut runtime.func_env())
            .unwrap();
        dbg!("{}", ctx.func.display(None));
        ctx.verify(runtime.func_env().flags()).unwrap();
    }
}


text:
describes.endtoend(
  'amp-selector',
  {
    fixture: 'amp-selector/amp-selector-tabs.html',

    versions: {
      '0.1': {
        environments: ['single', 'viewer-demo'],
      },
      '1.0': {
        environments: ['single', 'viewer-demo'],
        experiments: ['bento-selector'],
      },
    },
  },
  async (env) => {
    let controller;

    beforeEach(() => {
      controller = env.controller;
    });

    it('should render correctly', async () => {
      const selector = await controller.findElement('#tabs');

      await expect(controller.getElementAttribute(selector, 'role')).to.equal(
        'tablist'
      );

      const firstTab = await controller.findElement('#tab1Selector');
      await expect(controller.getElementAttribute(firstTab, 'selected')).to
        .exist;

      const image = await controller.findElement('#firstImage');
      await expect(
        controller.getElementProperty(image, 'clientWidth')
      ).to.be.greaterThan(0);

      const internalImg = await controller.findElement('#firstImage img');
      await expect(internalImg).to.exist;
    });

    it('should switch tabs on button click', async () => {
      const secondTab = await controller.findElement('#tab2Selector');
      await expect(controller.getElementAttribute(secondTab, 'selected')).to.not
        .exist;

      await controller.click(secondTab);
      await expect(controller.getElementAttribute(secondTab, 'selected')).to
        .exist;

      const image = await controller.findElement('#secondImage');
      await expect(
        controller.getElementProperty(image, 'clientWidth')
      ).to.be.greaterThan(0);

      const internalImg = await controller.findElement('#secondImage img');
      await expect(internalImg).to.exist;
    });

    it('should switch tabs on toggle ', async () => {
      const thirdTabToggle = await controller.findElement('#tab3Toggle');
      const thirdTab = await controller.findElement('#tab3Selector');
      await expect(controller.getElementAttribute(thirdTab, 'selected')).to.not
        .exist;

      await controller.click(thirdTabToggle);
      await expect(controller.getElementAttribute(thirdTab, 'selected')).to
        .exist;

      const image = await controller.findElement('#thirdImage');
      await expect(
        controller.getElementProperty(image, 'clientWidth')
      ).to.be.greaterThan(0);

      const internalImg = await controller.findElement('#thirdImage img');
      await expect(internalImg).to.exist;
    });
  }
);


text:
from django.db import models
from import_export import resources

class Provinsi(models.Model):
    nama_provinsi = models.CharField(max_length=100)
    keterangan = models.CharField(max_length=500)

    createtime = models.DateTimeField(auto_now_add=True, auto_now=False)
    updatetime = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.nama_provinsi

class ProvinsiResource(resources.ModelResource):
    class Meta:
        model = Provinsi

class Kabupaten(models.Model):
    id_provinsi = models.ForeignKey(Provinsi)
    nama_kabupaten = models.CharField(max_length=100)
    keterangan = models.CharField(max_length=500)

    createtime = models.DateTimeField(auto_now_add=True, auto_now=False)
    updatetime = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.nama_kabupaten

class KabupatenResource(resources.ModelResource):
    class Meta:
        model = Kabupaten

class Kecamatan(models.Model):
    id_kabupaten = models.ForeignKey(Kabupaten)
    nama_kecamatan = models.CharField(max_length=100)
    keterangan = models.CharField(max_length=500)

    createtime = models.DateTimeField(auto_now_add=True, auto_now=False)
    updatetime = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.nama_kecamatan

class KecamatanResource(resources.ModelResource):
    class Meta:
        model = Kecamatan

class Kelurahan(models.Model):
    id_kecamatan = models.ForeignKey(Kecamatan)
    nama_kelurahan = models.CharField(max_length=100)
    keterangan = models.CharField(max_length=500)

    createtime = models.DateTimeField(auto_now_add=True, auto_now=False)
    updatetime = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.nama_kelurahan

class KelurahanResource(resources.ModelResource):
    class Meta:
        model = Kelurahan

class Dusun(models.Model):
    id_kelurahan = models.ForeignKey(Kelurahan)
    nama_dusun = models.CharField(max_length=100)
    keterangan = models.CharField(max_length=500)

    createtime = models.DateTimeField(auto_now_add=True, auto_now=False)
    updatetime = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.nama_dusun

class DusunResource(resources.ModelResource):
    class Meta:
        model = Dusun
<<<<<<< HEAD
=======

class Peralatan(models.Model):
    nama_peralatan = models.CharField(max_length=100)

    createtime = models.DateTimeField(auto_now_add=True, auto_now=False)
    updatetime = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return self.nama_peralatan

class PeralatanResource(resources.ModelResource):
    class Meta:
        model = Peralatan
>>>>>>> 58d9661c466c7b4de1d8096096fb78de7020e426


text:
<component name="ArtifactManager">
  <artifact type="jar" name="runas-plugin">
    <output-path>$PROJECT_DIR$/</output-path>
    <root id="archive" name="runas.zip">
      <element id="artifact" artifact-name="runas-plugin (exploded)" />
    </root>
  </artifact>
</component>


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
  </head>

  <body>
    <form class="my-form">
       <input name="x" value="Hello World!">
       <output name="x"></output>
     </form>

    <script src="seemple.js"></script>
    <script src="seemple-parse-form.min.js"></script>
    <script>
     const object = {};
     Seemple.parseForm(object, '.my-form');

    </script>
  </body>
</html>


text:
FROM nginx:alpine

RUN set -x \
  && apk add --update --no-cache ca-certificates curl openssl


text:
package org.kie.server.api.marshalling;

public enum MarshallingFormat {
    XSTREAM(0, "xstream"), JAXB(1, "xml"), JSON(2, "json");

    private final int id;
    private final String type;

    MarshallingFormat( int id, String type ) {
        this.id = id;
        this.type = type;
    }

    public int getId() { return id; }

    public String getType() {
        return type;
    }

    public static MarshallingFormat fromId( int id ) {
        switch ( id ) {
            case 0 : return XSTREAM;
            case 1 : return JAXB;
            case 2 : return JSON;
            default: return null;
        }
    }

    public static MarshallingFormat fromType( String type ) {
        if ("xstream".equals(type)) {
            return XSTREAM;
        } else if ("xml".equals(type)) {
            return JAXB;
        } else if ("json".equals(type)) {
            return JSON;
        } else {
            return null;
        }
    }
}


text:
package org.apache.causeway.viewer.commons.services.userprof;

import javax.annotation.Priority;
import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import org.apache.causeway.applib.annotation.PriorityPrecedence;
import org.apache.causeway.applib.services.i18n.TranslationContext;
import org.apache.causeway.applib.services.i18n.TranslationService;
import org.apache.causeway.applib.services.user.UserMemento;
import org.apache.causeway.applib.services.user.UserService;
import org.apache.causeway.viewer.commons.applib.services.userprof.UserProfileUiModel;
import org.apache.causeway.viewer.commons.applib.services.userprof.UserProfileUiService;
import org.apache.causeway.viewer.commons.services.CausewayModuleViewerCommonsServices;

import lombok.RequiredArgsConstructor;
import lombok.val;

@Service
@Named(CausewayModuleViewerCommonsServices.NAMESPACE + ".UserProfileUiServiceDefault")
@Priority(PriorityPrecedence.LATE)
@Qualifier("Default")
@RequiredArgsConstructor(onConstructor_ = {@Inject})
public class UserProfileUiServiceDefault implements UserProfileUiService {

    private final UserService userService;
    private final TranslationService translationService;

    @Override
    public UserProfileUiModel userProfile() {
        return UserProfileUiModel.of(userProfileName(), userService.currentUser().orElse(null));
    }

    private String userProfileName() {
        return userService.currentUser()
                .map(this::userNameFor)
                .orElse(String.format("<%s>", translated("Anonymous")));
    }

    private String userNameFor(final UserMemento x) {
        final String username = x.getName();
        if (x.isImpersonating()) {
            return String.format("%s (%s)", username, translated("impersonating"));
        }
        val realName = x.getRealName();
        return !isNullOrEmpty(realName)
                ? realName
                : username;
    }

    private String translated(final String str) {
        return translationService.translate(TranslationContext.forClassName(getClass()), str);
    }

    private static boolean isNullOrEmpty(final String realName) {
        return realName == null || realName.equals("");
    }

}


text:
package sak.orbit.instruction;

import sak.orbit.core.Memory;

public class AddInstruction extends DoubleInstruction {

	/**
	 * @param instructionPointer
	 * @param dataPointer1
	 * @param dataPointer2
	 */
	public AddInstruction(final int instructionPointer, final int dataPointer1, final int dataPointer2) {
		super(instructionPointer, dataPointer1, dataPointer2);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see sak.orbit.core.DoubleInstruction#perform(double, double)
	 */
	public void doPerform(final Memory memory) {
		memory.setData(instructionPointer, memory.getData(dataPointer1) + memory.getData(dataPointer2));
	}
}


text:
namespace Google.Cloud.ServiceManagement.V1.Snippets
{
    // [START servicemanagement_v1_generated_ServiceManager_GetService_sync_flattened]
    using Google.Cloud.ServiceManagement.V1;

    public sealed partial class GeneratedServiceManagerClientSnippets
    {
        /// <summary>Snippet for GetService</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void GetService()
        {
            // Create client
            ServiceManagerClient serviceManagerClient = ServiceManagerClient.Create();
            // Initialize request argument(s)
            string serviceName = "";
            // Make the request
            ManagedService response = serviceManagerClient.GetService(serviceName);
        }
    }
    // [END servicemanagement_v1_generated_ServiceManager_GetService_sync_flattened]
}


text:
package se.chalmers.watchmetest.activity;

import se.chalmers.watchme.R;
import se.chalmers.watchme.activity.MainActivity;
import se.chalmers.watchme.activity.MovieDetailsActivity;
import se.chalmers.watchme.database.DatabaseHelper;
import se.chalmers.watchmetest.Constants;
import android.support.v4.view.ViewPager;
import android.test.ActivityInstrumentationTestCase2;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;

import com.jayway.android.robotium.solo.Solo;

/**
 * Class that tests functionality implemented in the MovieDetailsActivity class.
 * Tests are performed with methods from the robotium api.
 *
 * @author mattiashenriksson
 *
 */
public class MovieDetailsActivityTest extends
		ActivityInstrumentationTestCase2<MainActivity> {

	Solo solo;
	DatabaseHelper dbh;

	public MovieDetailsActivityTest() {
		super(MainActivity.class);
	}

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		solo = new Solo(getInstrumentation(), getActivity());
		dbh = new DatabaseHelper(getActivity());
	}

	@Override
	public void tearDown() throws Exception {
		// finish all activities that have been opened during test execution.
		solo.finishOpenedActivities();
		dbh.onUpgrade(dbh.getWritableDatabase(), 1, 1);
	}

	/**
	 * Test if details view shows the correct details of a movie
	 */
	public void testViewDetails() {
		// Clear list of movies stored in database
		dbh.onUpgrade(dbh.getWritableDatabase(), 1, 1);

		solo.waitForActivity("MainActivity");

		// Add movie
		solo.clickOnActionBarItem(R.id.menu_main_add_movie);
		solo.waitForActivity("AddMovieActivity");
		solo.enterText(Constants.TITLE_FIELD, "TEST_MOVIE");
		solo.setProgressBar(Constants.RATING_BAR, 1);
		solo.clickOnView(solo.getView(R.id.release_date_button));
		solo.waitForText("Done");
		solo.setDatePicker(Constants.DATE_PICKER, 2014 - 1, 12, 24);
		solo.clickOnText("Done");
		solo.waitForDialogToClose(Constants.WAIT_FOR_DIALOG_TO_CLOSE_TIME);
		solo.enterText(Constants.TAG_FIELD, "Action");
		solo.enterText(Constants.NOTE_FIELD, "Mum said I'd like this");
		solo.clickOnActionBarItem(R.id.menu_add_movie);

		// Navigate to details view
		solo.waitForActivity("MainActivity");
		solo.clickOnText("TEST_MOVIE");
		boolean isMovieDetailsActivityViewed = solo
				.waitForActivity("MovieDetailsActivity");
		assertTrue(isMovieDetailsActivityViewed);

		// Check if correct details are viewed
		boolean isTitleFound = solo.searchText("TEST_MOVIE");
		assertTrue(isTitleFound);

		RatingBar ratingBar = (RatingBar) solo.getView(R.id.my_rating_bar);
		assertTrue(ratingBar.getRating() == 1);

		TextView releaseDateLabel = (TextView) solo.getView(R.id.releaseDate);
		assertTrue(releaseDateLabel.getText().equals("24 Jan, 2014"));

		EditText noteField = (EditText) solo.getView(R.id.note_field_details);
		assertTrue(noteField.getText().toString()
				.equals("Mum said I'd like this"));

		EditText tagField = (EditText) solo.getView(R.id.tag_field_details);
		assertTrue(tagField.getText().toString().equals("action"));
	}

	/**
	 * Test if it's possible to edit a movie's details
	 */
	public void testEditDetails() {
		// Clear list of movies stored in database
		dbh.onUpgrade(dbh.getWritableDatabase(), 1, 1);

		solo.waitForActivity("MainActivity");

		// Add movie
		solo.clickOnActionBarItem(R.id.menu_main_add_movie);
		solo.waitForActivity("AddMovieActivity");
		solo.enterText(Constants.TITLE_FIELD, "TEST_MOVIE");
		solo.clickOnActionBarItem(R.id.menu_add_movie);

		// Navigate to details view
		solo.waitForActivity("MainActivity");
		solo.clickOnText("TEST_MOVIE");
		solo.waitForActivity("MovieDetailsActivity");

		// Check that correct details are viewed
		RatingBar ratingBar = (RatingBar) solo.getView(R.id.my_rating_bar);
		TextView releaseDateLabel = (TextView) solo.getView(R.id.releaseDate);
		EditText noteField = (EditText) solo.getView(R.id.note_field_details);
		EditText tagField = (EditText) solo.getView(R.id.tag_field_details);

		assertTrue(ratingBar.getRating() == 0);
		assertFalse(releaseDateLabel.getText().equals("24 Jan, 2014"));
		assertTrue(noteField.getText().toString().equals(""));
		assertTrue(tagField.getText().toString().equals(""));

		// Edit movie details
		solo.clickOnActionBarItem(R.id.menu_edit);
		solo.setProgressBar(Constants.RATING_BAR, 1);
		solo.clickOnView(solo.getView(R.id.release_date_button));
		solo.waitForText("Done");
		solo.setDatePicker(Constants.DATE_PICKER, 2014 - 1, 12, 24);
		solo.clickOnText("Done");
		solo.waitForDialogToClose(Constants.WAIT_FOR_DIALOG_TO_CLOSE_TIME);
		solo.enterText(0, "Action");
		solo.enterText(1, "Mum said I'd like this");
		solo.clickOnActionBarItem(R.id.menu_save);

		// Navigate out from and back to details view
		solo.clickOnActionBarHomeButton();
		solo.waitForActivity("MainActivity");
		solo.clickOnText("TEST_MOVIE");
		solo.waitForActivity("MovieDetailsActivity");

		// Check if new details are viewed
		assertTrue(ratingBar.getRating() == 1);
		assertTrue(releaseDateLabel.getText().equals("24 Jan, 2014"));
		assertTrue(noteField.getText().toString()
				.equals("Mum said I'd like this"));
		assertTrue(tagField.getText().toString().equals("Action"));
	}
}


text:
package com.zimbra.cs.mailclient.pop3;

import com.zimbra.cs.mailclient.MailInputStream;

import java.io.IOException;
import java.io.EOFException;

/**
 * POP3 server response message.
 */
public class Pop3Response {
    private final String command;
    private String status;
    private String message;
    private ContentInputStream cis;

    private static final String OK = "+OK";
    private static final String ERR = "-ERR";
    private static final String CONTINUATION = "+";

    private static final String CAPA = "CAPA";
    private static final String LIST = "LIST";
    private static final String RETR = "RETR";
    private static final String UIDL = "UIDL";

    public static Pop3Response read(String cmd, MailInputStream is) throws IOException {
        Pop3Response res = new Pop3Response(cmd);
        res.readResponse(is);
        return res;
    }

    private Pop3Response(String cmd) {
        command = cmd;
    }

    private void readResponse(MailInputStream is) throws IOException {
        String line = is.readLine();
        if (line == null) {
            throw new EOFException("Unexpected end of stream");
        }
        is.trace();
        int i = line.indexOf(' ');
        if (i == -1) {
            status = line;
            message = "";
        } else {
            status = line.substring(0, i);
            message = line.substring(i).trim();
        }
        if (isOK() && hasContent(command)) {
            cis = new ContentInputStream(is);
        }
    }

    private static boolean hasContent(String cmd) {
        return LIST.equalsIgnoreCase(cmd) || RETR.equalsIgnoreCase(cmd) ||
               UIDL.equalsIgnoreCase(cmd) || CAPA.equalsIgnoreCase(cmd);
    }

    public boolean isOK() { return status.equals(OK); }
    public boolean isERR() { return status.equals(ERR); }
    public boolean isContinuation() { return status.equals(CONTINUATION); }

    public String getMessage() { return message; }

    public ContentInputStream getContentInputStream() {
        return cis;
    }

    public void dispose() {
        if (cis != null) {
            try {
                cis.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}


text:
#ifndef QSVGSTYLE_P_H
#define QSVGSTYLE_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists purely as an
// implementation detail.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include "QtGui/qpainter.h"

#ifndef QT_NO_SVG

#include "QtGui/qpen.h"
#include "QtGui/qbrush.h"
#include "QtGui/qmatrix.h"
#include "QtGui/qcolor.h"
#include "QtGui/qfont.h"
#include <qdebug.h>

QT_BEGIN_NAMESPACE

class QPainter;
class QSvgNode;
class QSvgFont;
class QSvgTinyDocument;

template <class T> class QSvgRefCounter
{
public:
    QSvgRefCounter() { t = 0; }
    QSvgRefCounter(T *_t)
    {
        t = _t;
        if (t)
            t->ref();
    }
    QSvgRefCounter(const QSvgRefCounter &other)
    {
        t = other.t;
        if (t)
            t->ref();
    }
    QSvgRefCounter &operator =(T *_t)
    {
        if(_t)
            _t->ref();
        if (t)
            t->deref();
        t = _t;
        return *this;
    }
    QSvgRefCounter &operator =(const QSvgRefCounter &other)
    {
        if(other.t)
            other.t->ref();
        if (t)
            t->deref();
        t = other.t;
        return *this;
    }
    ~QSvgRefCounter()
    {
        if (t)
            t->deref();
    }

    inline T *operator->() const { return t; }
    inline operator T*() const { return t; }

private:
    T *t;
};

class QSvgRefCounted
{
public:
    QSvgRefCounted() { _ref = 0; }
    virtual ~QSvgRefCounted() {}
    void ref() {
        ++_ref;
//        qDebug() << this << ": adding ref, now " << _ref;
    }
    void deref() {
//        qDebug() << this << ": removing ref, now " << _ref;
        if(!--_ref) {
//            qDebug("     deleting");
            delete this;
        }
    }
private:
    int _ref;
};

struct QSvgExtraStates
{
    QSvgExtraStates();

    qreal fillOpacity;
    qreal strokeOpacity;
    QSvgFont *svgFont;
    Qt::Alignment textAnchor;
    int fontWeight;
    Qt::FillRule fillRule;
    qreal strokeDashOffset;
    bool vectorEffect; // true if pen is cosmetic
};

class QSvgStyleProperty : public QSvgRefCounted
{
public:
    enum Type
    {
        QUALITY,
        FILL,
        VIEWPORT_FILL,
        FONT,
        STROKE,
        SOLID_COLOR,
        GRADIENT,
        TRANSFORM,
        ANIMATE_TRANSFORM,
        ANIMATE_COLOR,
        OPACITY,
        COMP_OP
    };
public:
    virtual ~QSvgStyleProperty();
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states) = 0;
    virtual void revert(QPainter *p, QSvgExtraStates &states) =0;
    virtual Type type() const=0;
};

class QSvgFillStyleProperty : public QSvgStyleProperty
{
public:
    virtual QBrush brush(QPainter *p, QSvgExtraStates &states) = 0;
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
};

class QSvgQualityStyle : public QSvgStyleProperty
{
public:
    QSvgQualityStyle(int color);
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;
private:
    // color-render ing v 	v 	'auto' | 'optimizeSpeed' |
    //                                  'optimizeQuality' | 'inherit'
    int m_colorRendering;

    // shape-rendering v 	v 	'auto' | 'optimizeSpeed' | 'crispEdges' |
    //                                  'geometricPrecision' | 'inherit'
    //QSvgShapeRendering m_shapeRendering;

    // text-rendering    v 	v 	'auto' | 'optimizeSpeed' | 'optimizeLegibility'
    //                                | 'geometricPrecision' | 'inherit'
    //QSvgTextRendering m_textRendering;

    // vector-effect         v 	x 	'default' | 'non-scaling-stroke' | 'inherit'
    //QSvgVectorEffect m_vectorEffect;

    // image-rendering v 	v 	'auto' | 'optimizeSpeed' | 'optimizeQuality' |
    //                                      'inherit'
    //QSvgImageRendering m_imageRendering;
};

class QSvgOpacityStyle : public QSvgStyleProperty
{
public:
    QSvgOpacityStyle(qreal opacity);
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;
private:
    qreal m_opacity;
    qreal m_oldOpacity;
};

class QSvgFillStyle : public QSvgStyleProperty
{
public:
    QSvgFillStyle();
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;

    void setFillRule(Qt::FillRule f);
    void setFillOpacity(qreal opacity);
    void setFillStyle(QSvgFillStyleProperty* style);
    void setBrush(QBrush brush);

    const QBrush & qbrush() const
    {
        return m_fill;
    }

    qreal fillOpacity() const
    {
        return m_fillOpacity;
    }

    Qt::FillRule fillRule() const
    {
        return m_fillRule;
    }

    QSvgFillStyleProperty* style() const
    {
        return m_style;
    }

    void setGradientId(const QString &Id)
    {
        m_gradientId = Id;
    }

    QString gradientId() const
    {
        return m_gradientId;
    }

    void setGradientResolved(bool resolved)
    {
        m_gradientResolved = resolved;
    }

    bool isGradientResolved() const
    {
        return m_gradientResolved;
    }

private:
    // fill            v 	v 	'inherit' | <Paint.datatype>
    // fill-opacity    v 	v 	'inherit' | <OpacityValue.datatype>
    QBrush m_fill;
    QBrush m_oldFill;
    QSvgFillStyleProperty *m_style;

    Qt::FillRule m_fillRule;
    Qt::FillRule m_oldFillRule;
    qreal m_fillOpacity;
    qreal m_oldFillOpacity;

    QString m_gradientId;
    uint m_gradientResolved : 1;

    uint m_fillRuleSet : 1;
    uint m_fillOpacitySet : 1;
    uint m_fillSet : 1;
};

class QSvgViewportFillStyle : public QSvgStyleProperty
{
public:
    QSvgViewportFillStyle(const QBrush &brush);
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;

    const QBrush & qbrush() const
    {
        return m_viewportFill;
    }
private:
    // viewport-fill         v 	x 	'inherit' | <Paint.datatype>
    // viewport-fill-opacity 	v 	x 	'inherit' | <OpacityValue.datatype>
    QBrush m_viewportFill;

    QBrush m_oldFill;
};

class QSvgFontStyle : public QSvgStyleProperty
{
public:
    static const int LIGHTER = -1;
    static const int BOLDER = 1;

    QSvgFontStyle(QSvgFont *font, QSvgTinyDocument *doc);
    QSvgFontStyle();
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;

    void setSize(qreal size)
    {
        // Store the _pixel_ size in the font. Since QFont::setPixelSize() only takes an int, call
        // QFont::SetPointSize() instead. Set proper font size just before rendering.
        m_qfont.setPointSizeF(size);
        m_sizeSet = 1;
    }

    void setTextAnchor(Qt::Alignment anchor)
    {
        m_textAnchor = anchor;
        m_textAnchorSet = 1;
    }

    void setFamily(const QString &family)
    {
        m_qfont.setFamily(family);
        m_familySet = 1;
    }

    void setStyle(QFont::Style fontStyle) {
        m_qfont.setStyle(fontStyle);
        m_styleSet = 1;
    }

    void setVariant(QFont::Capitalization fontVariant)
    {
        m_qfont.setCapitalization(fontVariant);
        m_variantSet = 1;
    }

    static int SVGToQtWeight(int weight);

    void setWeight(int weight)
    {
        m_weight = weight;
        m_weightSet = 1;
    }

    QSvgFont * svgFont() const
    {
        return m_svgFont;
    }

    const QFont &qfont() const
    {
        return m_qfont;
    }

    QSvgTinyDocument *doc() const {return m_doc;}

private:
    QSvgFont *m_svgFont;
    QSvgTinyDocument *m_doc;
    QFont m_qfont;

    int m_weight;
    Qt::Alignment m_textAnchor;

    QSvgFont *m_oldSvgFont;
    QFont m_oldQFont;
    Qt::Alignment m_oldTextAnchor;
    int m_oldWeight;

    uint m_familySet : 1;
    uint m_sizeSet : 1;
    uint m_styleSet : 1;
    uint m_variantSet : 1;
    uint m_weightSet : 1;
    uint m_textAnchorSet : 1;
};

class QSvgStrokeStyle : public QSvgStyleProperty
{
public:
    QSvgStrokeStyle();
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;

    void setStroke(QBrush brush)
    {
        m_stroke.setBrush(brush);
        m_style = 0;
        m_strokeSet = 1;
    }

    void setStyle(QSvgFillStyleProperty *style)
    {
        m_style = style;
        m_strokeSet = 1;
    }

    void setDashArray(const QVector<qreal> &dashes);

    void setDashArrayNone()
    {
        m_stroke.setStyle(Qt::SolidLine);
        m_strokeDashArraySet = 1;
    }

    void setDashOffset(qreal offset)
    {
        m_strokeDashOffset = offset;
        m_strokeDashOffsetSet = 1;
    }

    void setLineCap(Qt::PenCapStyle cap)
    {
        m_stroke.setCapStyle(cap);
        m_strokeLineCapSet = 1;
    }

    void setLineJoin(Qt::PenJoinStyle join)
    {
        m_stroke.setJoinStyle(join);
        m_strokeLineJoinSet = 1;
    }

    void setMiterLimit(qreal limit)
    {
        m_stroke.setMiterLimit(limit);
        m_strokeMiterLimitSet = 1;
    }

    void setOpacity(qreal opacity)
    {
        m_strokeOpacity = opacity;
        m_strokeOpacitySet = 1;
    }

    void setWidth(qreal width)
    {
        m_stroke.setWidthF(width);
        m_strokeWidthSet = 1;
        Q_ASSERT(!m_strokeDashArraySet); // set width before dash array.
    }

    qreal width()
    {
        return m_stroke.widthF();
    }

    void setVectorEffect(bool nonScalingStroke)
    {
        m_vectorEffect = nonScalingStroke;
        m_vectorEffectSet = 1;
    }

    QSvgFillStyleProperty* style() const
    {
        return m_style;
    }

    void setGradientId(const QString &Id)
    {
        m_gradientId = Id;
    }

    QString gradientId() const
    {
        return m_gradientId;
    }

    void setGradientResolved(bool resolved)
    {
        m_gradientResolved = resolved;
    }

    bool isGradientResolved() const
    {
        return m_gradientResolved;
    }

    QPen stroke() const
    {
        return m_stroke;
    }

private:
    // stroke            v 	v 	'inherit' | <Paint.datatype>
    // stroke-dasharray  v 	v 	'inherit' | <StrokeDashArrayValue.datatype>
    // stroke-dashoffset v 	v 	'inherit' | <StrokeDashOffsetValue.datatype>
    // stroke-linecap    v 	v 	'butt' | 'round' | 'square' | 'inherit'
    // stroke-linejoin   v 	v 	'miter' | 'round' | 'bevel' | 'inherit'
    // stroke-miterlimit v 	v 	'inherit' | <StrokeMiterLimitValue.datatype>
    // stroke-opacity    v 	v 	'inherit' | <OpacityValue.datatype>
    // stroke-width      v 	v 	'inherit' | <StrokeWidthValue.datatype>
    QPen m_stroke;
    QPen m_oldStroke;
    qreal m_strokeOpacity;
    qreal m_oldStrokeOpacity;
    qreal m_strokeDashOffset;
    qreal m_oldStrokeDashOffset;

    QSvgFillStyleProperty *m_style;
    QString m_gradientId;
    uint m_gradientResolved : 1;
    uint m_vectorEffect : 1;
    uint m_oldVectorEffect : 1;

    uint m_strokeSet : 1;
    uint m_strokeDashArraySet : 1;
    uint m_strokeDashOffsetSet : 1;
    uint m_strokeLineCapSet : 1;
    uint m_strokeLineJoinSet : 1;
    uint m_strokeMiterLimitSet : 1;
    uint m_strokeOpacitySet : 1;
    uint m_strokeWidthSet : 1;
    uint m_vectorEffectSet : 1;
};

class QSvgSolidColorStyle : public QSvgFillStyleProperty
{
public:
    QSvgSolidColorStyle(const QColor &color);
    virtual Type type() const;

    const QColor & qcolor() const
    {
        return m_solidColor;
    }

    QBrush brush(QPainter *, QSvgExtraStates &)
    {
        return m_solidColor;
    }

private:
    // solid-color       v 	x 	'inherit' | <SVGColor.datatype>
    // solid-opacity     v 	x 	'inherit' | <OpacityValue.datatype>
    QColor m_solidColor;

    QBrush m_oldFill;
    QPen   m_oldStroke;
};

class QSvgGradientStyle : public QSvgFillStyleProperty
{
public:
    QSvgGradientStyle(QGradient *grad);
    ~QSvgGradientStyle() { delete m_gradient; }
    virtual Type type() const;

    void setStopLink(const QString &link, QSvgTinyDocument *doc);
    QString stopLink() const { return m_link; }
    void resolveStops();

    void setMatrix(const QMatrix &matrix);
    QMatrix  qmatrix() const
    {
        return m_matrix;
    }

    QGradient *qgradient() const
    {
        return m_gradient;
    }

    bool gradientStopsSet() const
    {
        return m_gradientStopsSet;
    }

    void setGradientStopsSet(bool set)
    {
        m_gradientStopsSet = set;
    }

    QBrush brush(QPainter *, QSvgExtraStates &);
private:
    QGradient      *m_gradient;
    QMatrix m_matrix;

    QSvgTinyDocument *m_doc;
    QString           m_link;
    bool m_gradientStopsSet;
};

class QSvgTransformStyle : public QSvgStyleProperty
{
public:
    QSvgTransformStyle(const QTransform &transform);
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;

    const QTransform & qtransform() const
    {
        return m_transform;
    }
private:
    //7.6 The transform  attribute
    QTransform m_transform;
    QTransform m_oldWorldTransform;
};

class QSvgAnimateTransform : public QSvgStyleProperty
{
public:
    enum TransformType
    {
        Empty,
        Translate,
        Scale,
        Rotate,
        SkewX,
        SkewY
    };
    enum Additive
    {
        Sum,
        Replace
    };
public:
    QSvgAnimateTransform(int startMs, int endMs, int by = 0);
    void setArgs(TransformType type, Additive additive, const QVector<qreal> &args);
    void setFreeze(bool freeze);
    void setRepeatCount(qreal repeatCount);
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;
    QSvgAnimateTransform::Additive additiveType() const
    {
        return m_additive;
    }

    bool animActive(qreal totalTimeElapsed)
    {
        if (totalTimeElapsed < m_from)
            return false;
        if (m_freeze || m_repeatCount < 0) // fill="freeze" or repeat="indefinite"
            return true;
        if (m_totalRunningTime == 0)
            return false;
        qreal animationFrame = (totalTimeElapsed - m_from) / m_totalRunningTime;
        if (animationFrame > m_repeatCount)
            return false;
        return true;
    }

    bool transformApplied() const
    {
        return m_transformApplied;
    }

    // Call this instead of revert if you know that revert is unnecessary.
    void clearTransformApplied()
    {
        m_transformApplied = false;
    }

protected:
    void resolveMatrix(const QSvgNode *node);
private:
    qreal m_from, m_to, m_by;
    qreal m_totalRunningTime;
    TransformType m_type;
    Additive m_additive;
    QVector<qreal> m_args;
    int m_count;
    QTransform m_transform;
    QTransform m_oldWorldTransform;
    bool m_finished;
    bool m_freeze;
    qreal m_repeatCount;
    bool m_transformApplied;
};

class QSvgAnimateColor : public QSvgStyleProperty
{
public:
    QSvgAnimateColor(int startMs, int endMs, int by = 0);
    void setArgs(bool fill, const QList<QColor> &colors);
    void setFreeze(bool freeze);
    void setRepeatCount(qreal repeatCount);
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;
private:
    qreal m_from, m_to, m_by;
    qreal m_totalRunningTime;
    QList<QColor> m_colors;
    QBrush m_oldBrush;
    QPen   m_oldPen;
    bool m_fill;
    bool m_finished;
    bool m_freeze;
    qreal m_repeatCount;
};

class QSvgCompOpStyle : public QSvgStyleProperty
{
public:
    QSvgCompOpStyle(QPainter::CompositionMode mode);
    virtual void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    virtual void revert(QPainter *p, QSvgExtraStates &states);
    virtual Type type() const;

    const QPainter::CompositionMode & compOp() const
    {
        return m_mode;
    }
private:
    //comp-op attribute
    QPainter::CompositionMode m_mode;

    QPainter::CompositionMode m_oldMode;
};

class QSvgStyle
{
public:
    QSvgStyle()
        : quality(0),
          fill(0),
          viewportFill(0),
          font(0),
          stroke(0),
          solidColor(0),
          gradient(0),
          transform(0),
          animateColor(0),
          opacity(0),
          compop(0)
    {}
    ~QSvgStyle();

    void apply(QPainter *p, const QSvgNode *node, QSvgExtraStates &states);
    void revert(QPainter *p, QSvgExtraStates &states);
    QSvgRefCounter<QSvgQualityStyle>      quality;
    QSvgRefCounter<QSvgFillStyle>         fill;
    QSvgRefCounter<QSvgViewportFillStyle> viewportFill;
    QSvgRefCounter<QSvgFontStyle>         font;
    QSvgRefCounter<QSvgStrokeStyle>       stroke;
    QSvgRefCounter<QSvgSolidColorStyle>   solidColor;
    QSvgRefCounter<QSvgGradientStyle>     gradient;
    QSvgRefCounter<QSvgTransformStyle>    transform;
    QSvgRefCounter<QSvgAnimateColor>      animateColor;
    QList<QSvgRefCounter<QSvgAnimateTransform> >   animateTransforms;
    QSvgRefCounter<QSvgOpacityStyle>      opacity;
    QSvgRefCounter<QSvgCompOpStyle>       compop;
};

/********************************************************/
// NOT implemented:

// color           v 	v 	'inherit' | <Color.datatype>
//QColor m_color;

// display         v 	x 	'inline' | 'block' | 'list-item'
//                                 | 'run-in' | 'compact' | 'marker' |
//                                 'table' | 'inline-table' |
//                                 'table-row-group' | 'table-header-group' |
//                                 'table-footer-group' | 'table-row' |
//                                 'table-column-group' | 'table-column' |
//                                 'table-cell' | 'table-caption' |
//                                 'none' | 'inherit'
//QSvgDisplayStyle m_display;

// display-align   v 	v 	'auto' | 'before' | 'center' | 'after' | 'inherit'
//QSvgDisplayAlign m_displayAlign;

// line-increment  v 	v 	'auto' | 'inherit' | <Number.datatype>
//int m_lineIncrement;

// text-anchor       v 	v 	'start' | 'middle' | 'end' | 'inherit'
//QSvgTextAnchor m_textAnchor;

// visibility 	v 	v 	'visible' | 'hidden' | 'inherit'
//QSvgVisibility m_visibility;

/******************************************************/
// the following do not make sense for us

// pointer-events  v 	v 	'visiblePainted' | 'visibleFill' | 'visibleStroke' |
//                              'visible' | 'painted' | 'fill' | 'stroke' | 'all' |
//                              'none' | 'inherit'
//QSvgPointEvents m_pointerEvents;

// audio-level     v  	x  	'inherit' | <Number.datatype>

QT_END_NAMESPACE

#endif // QT_NO_SVG
#endif // QSVGSTYLE_P_H


text:
 * A working GCC (on mac os x something like `xcode-select --install` will get you started)
 * [Go environment](http://golang.org/doc/code.html)
 * Git and Mercurial (for retrieving dependencies)

If you're on Mac OS X, [homebrew](http://brew.sh/) can be very helpful to fulfill these dependencies.

You can `go get -d github.com/cockroachdb/cockroach` or, alternatively,

```bash
mkdir -p $GOPATH/src/github.com/cockroachdb/
cd $GOPATH/src/github.com/cockroachdb/
git clone git@github.com:cockroachdb/cockroach.git
cd cockroach
```

Now you should be all set for `make build`, `make test` and everything else our Makefile has to
offer. Note that the first time you run `make` various dependent libraries and tools will be
downloaded and installed which can be somewhat time consuming. Be patient.

Note that if you edit a `.proto` file you will need to manually regenerate the associated
`.pb.{go,cc,h}` files using `go generate`.

To add or update a dependency, use `go get -u` and then
`glock save github.com/cockroachdb/cockroach` and commit the changes to the GLOCKFILE.

### Style guide
We're following the [Google Go Code Review](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) fairly closely. In particular, you want to watch out for proper punctuation and capitalization and make sure that your lines stay well below 80 characters.

### Code review workflow

+ All contributors need to sign the
  [Contributor License Agreement](https://www.clahub.com/agreements/cockroachdb/cockroach).

+ Create a local feature branch to do work on, ideally on one thing at a time.
  If you are working on your own fork, see
  [this tip](http://blog.campoy.cat/2014/03/github-and-go-forking-pull-requests-and.html)
  on forking in Go, which ensures that Go import paths will be correct.

`git checkout -b $USER/update-readme`

+ Hack away and commit your changes locally using `git add` and `git commit`.

`git commit -a -m 'update CONTRIBUTING.md'`

+ Run tests. It's usually enough to run `make test testrace`. You can also run `make acceptance` to have better test coverage. Running acceptance tests requires the Docker setup.

+ When you're ready for review, create a remote branch from your local branch. You may want to `git fetch origin` and run `git rebase origin/master` on your local feature branch before.

`git push -u origin $USER/update-readme`

+ Then [create a pull request using GitHub's UI](https://help.github.com/articles/creating-a-pull-request).

+ Address feedback in new commits. Wait (or ask) for new feedback on those commits if they are not straightforward.

+ Once ready to land your change, squash your commits. Where n is the number of commits in your branch, run
`git rebase -i HEAD~n`

 and subsequently update your remote (you will have to force the push, `git push -f $USER mybranch`). The pull request will update.

+ If you do not have write access to the repository and your pull request requires a manual merge, you may be asked to rebase again,
  `git fetch origin; git rebase -i origin/master` and update the PR again. Otherwise, you are free to merge your branch into origin/master directly or rebase first as you deem appropriate.


text:
package org.apache.ignite.jvmtest;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.ignite.internal.util.typedef.X;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.junit.Test;

/**
 * Java reg exp test.
 */
public class RegExpTest {
    /**
     * @throws Exception If failed.
     */
    @Test
    public void testRegExp() throws Exception {
        String normal =
            "swap-spaces/space1/b53b3a3d6ab90ce0268229151c9bde11|b53b3a3d6ab90ce0268229151c9bde11|1315392441288";

        byte[] b1 = new byte[200];
        byte[] b2 = normal.getBytes();

        U.arrayCopy(b2, 0, b1, 30, b2.length);

        CharSequence corrupt = new String(b1);

        String ptrn = "[a-z0-9/\\-]+\\|[a-f0-9]+\\|[0-9]+";

        Pattern p = Pattern.compile(ptrn);

        Matcher matcher = p.matcher(corrupt);

        assert matcher.find();

        X.println(String.valueOf(matcher.start()));

        assert normal.matches(ptrn);
    }
}


text:
title: Factorial
localeTitle: مضروب
---
## مضروب

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/rosetta-code/factorial/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
import { TimeSpan } from '../Timespan'
import { IMessage } from '../IMessage'

/**
 *
 *
 * @export
 * @interface IMessageTransport
 */
export interface IMessageTransport {

    /**
     * The name of the transport
     *
     * @type {string}
     * @memberof IMessageTransport
     */
    name: string;

    /**
     * Publishes an event message to the Endpoint
     *
     * @param {Message} message
     *
     * @memberOf IMessageTransport
     */
    publishAsync(message: IMessage<any>, timeToDelay?: TimeSpan): Promise<void>;

    /**
     * Sends a command message to the Endpoint
     *
     * @param {Message} message
     * @param {TimeSpan} timeToDelay
     *
     * @memberOf IMessageTransport
     */
    sendAsync(message: IMessage<any>, timeToDelay?: TimeSpan): Promise<void>;

    /**
     * Notifies subscribers when a message arrives indicating which
     * subscription the message is for via the MetaData property
     * Transport.Subscription
     *
     * @param {(message: IMessage<any>)} handler
     *
     * @memberOf IMessageTransport
     */
    onMessage(handler: (message: IMessage<any>) => void): void;

    /**
     * Marks the message as processed and prevents it from being sent again.
     *
     * @param {string} messageId
     *
     * @memberOf IMessageTransport
     */
    completeMessageAsync(messageId: string): Promise<void>;

    /**
     * Start listening for incoming messages
     *
     * @memberof IMessageTransport
     */
    startAsync(): Promise<void>;
}


text:
package org.jetbrains.plugins.groovy.codeInspection.changeToOperator.transformations;

import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.codeInspection.changeToOperator.data.MethodCallData;
import org.jetbrains.plugins.groovy.codeInspection.changeToOperator.data.OptionsData;

import static java.lang.String.format;

/**
 * e.g.
 * a.equals(b)  → (a == b)
 * !a.equals(b) → (a != b)
 */
public class BinaryTransformation extends Transformation {
  public BinaryTransformation(@Nullable IElementType operator) {
    super(operator);
  }

  @Override
  @Nullable
  public String getReplacement(MethodCallData methodInfo, OptionsData optionsData) {
    String lhs = getLhs(methodInfo);
    IElementType operator = getOperator(methodInfo, optionsData);
    String rhs = getRhs(methodInfo);
    if (lhs == null || operator == null || rhs == null) return null;

    return format("%s %s %s", lhs, operator, rhs);
  }

  @Nullable
  protected String getLhs(MethodCallData methodInfo) {
    return methodInfo.getBase();
  }

  @Nullable
  protected IElementType getOperator(MethodCallData methodInfo, OptionsData optionsData) {
    return operator;
  }

  @Nullable
  protected String getRhs(MethodCallData methodInfo) {
    return methodInfo.getArgument(0);
  }
}


text:
export default {
  props: {
    position: {
      type: String,
      default: 'topright'
    }
  },
  mounted () {
    this.controlOptions = {
      position: this.position
    };
  },
  beforeDestroy () {
    if (this.mapObject) {
      this.mapObject.remove();
    }
  }
};


text:
@interface PixelatorViewController : EditorViewController <UIAlertViewDelegate>

@end


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('crowdsourcing', '0068_worker_scope'),
    ]

    operations = [
        migrations.AddField(
            model_name='userprofile',
            name='ethnicity',
            field=models.CharField(choices=[(b'white', b'White'), (b'hispanic', b'Hispanic'), (b'black', b'Black'), (b'islander', b'Native Hawaiian or Other Pacific Islander'), (b'indian', b'Indian'), (b'asian', b'Asian'), (b'native', b'Native American or Alaska Native')], max_length=8, null=True),
        ),
        migrations.AddField(
            model_name='userprofile',
            name='job_tag',
            field=models.CharField(max_length=100, null=True),
        ),
        migrations.AlterField(
            model_name='userprofile',
            name='gender',
            field=models.CharField(choices=[(b'M', b'Male'), (b'F', b'Female'), (b'O', b'Other')], max_length=1),
        ),
    ]


text:
"""
Computes, plots, and saves the 2D vorticity field from a PetIBM simulation
after 2000 time steps (20 non-dimensional time-units).
"""

import pathlib
import h5py
import numpy
from matplotlib import pyplot

simu_dir = pathlib.Path(__file__).absolute().parents[1]

# Read vorticity field and its grid from files.
name = 'wz'
filepath = simu_dir / 'grid.h5'
f = h5py.File(filepath, 'r')
x, y = f[name]['x'][:], f[name]['y'][:]
X, Y = numpy.meshgrid(x, y)
timestep = 2000
filepath = simu_dir / 'solution' / '{:0>7}.h5'.format(timestep)
f = h5py.File(filepath, 'r')
wz = f[name][:]

# Read body coordinates from file.
filepath = simu_dir / 'circle.body'
with open(filepath, 'r') as infile:
    xb, yb = numpy.loadtxt(infile, dtype=numpy.float64,
                           unpack=True, skiprows=1)

pyplot.rc('font', family='serif', size=16)

# Plot the filled contour of the vorticity.
fig, ax = pyplot.subplots(figsize=(6.0, 6.0))
ax.grid()
ax.set_xlabel('x')
ax.set_ylabel('y')
levels = numpy.linspace(-3.0, 3.0, 16)
ax.contour(X, Y, wz, levels=levels, colors='black')
ax.plot(xb, yb, color='red')
ax.set_xlim(-1.0, 4.0)
ax.set_ylim(-2.0, 2.0)
ax.set_aspect('equal')
fig.tight_layout()

pyplot.show()

# Save figure.
fig_dir = simu_dir / 'figures'
fig_dir.mkdir(parents=True, exist_ok=True)
filepath = fig_dir / 'wz{:0>7}.png'.format(timestep)
fig.savefig(str(filepath), dpi=300)


text:
@interface CSAPI ()

- (id)initWithBookmark:(NSString *)aBookmark
              username:(NSString *)aUsername
              password:(NSString *)aPassword;
@end

@implementation TestApi

@synthesize requester;
@synthesize store;

+ (instancetype)apiWithBookmark:(NSString *)bookmark username:(NSString *)username password:(NSString *)password
{
    return [[TestApi alloc] initWithBookmark:bookmark
                                    username:username
                                    password:password];
}

@end


text:
@implementation PrivacyAccessMananger

+(instancetype)manager{

    static PrivacyAccessMananger * manager = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        manager = [[self alloc] init];

    });

    return manager;
}

#pragma mark - getAccessToCamera

-(void)getAccessToCamera:(void (^)(BOOL isAllowed))successBlock failureBlock:(void (^)(BOOL isDenyed))failureBlcik{

    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

    switch (status) {

            ///  未决定
        case AVAuthorizationStatusNotDetermined:
        {
            ///  申请权限

            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {

                kDISPATCH_MAIN_THREAD(^{

                    if (granted) {

                        successBlock(granted);
                    }

                    else{

                        failureBlcik(granted);
                    }

                });

            }];

            break;
        }

            ///  授权失败
        case AVAuthorizationStatusDenied:

            failureBlcik(false);

            break;

            ///  成功授权

        case AVAuthorizationStatusAuthorized:

            successBlock(true);

            break;

        default:

            failureBlcik(false);

            break;
    }

}

#pragma mark - getAccessToCameraAndMicroPhone

-(void)getAccessToCameraAndMicroPhone:(void (^)(BOOL))successBlock{

    AVAuthorizationStatus videoStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

    AVAuthorizationStatus audioStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];

    __block BOOL videoStatusValue = false;

    __block BOOL audioStatusValue = false;

    /// all access

    if (videoStatus == AVAuthorizationStatusAuthorized && audioStatus == AVAuthorizationStatusAuthorized) {

        successBlock(true);

        return;
    }

    /// all denyed

    else if (videoStatus == AVAuthorizationStatusDenied && audioStatus == AVAuthorizationStatusDenied){

        [self OpenSettingCenterWithTitle:cameraAndMicroPhonePromptTitle description:cameraAndMicroPhonePromptDetailInfo];

        return;
    }

    /// judge status

        /// video

    switch (videoStatus) {

            ///  未决定

        case AVAuthorizationStatusNotDetermined:
        {
            ///  申请权限

            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {

                kDISPATCH_MAIN_THREAD(^{

                    if (granted) {

                        videoStatusValue = true;
                    }

                    else{

                        videoStatusValue = false;
                    }

                });

            }];

            break;
        }

            ///  授权失败

        case AVAuthorizationStatusDenied:

            videoStatusValue = false;

            break;

            ///  成功授权

        case AVAuthorizationStatusAuthorized:

            videoStatusValue = true;

            break;

        default:

            videoStatusValue = false;

            break;
    }

        /// audio

    switch (audioStatus) {

            ///  未决定

        case AVAuthorizationStatusNotDetermined:
        {
            ///  申请权限

            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {

                kDISPATCH_MAIN_THREAD(^{

                    if (granted) {

                        audioStatusValue = true;
                    }

                    else{

                        audioStatusValue = false;
                    }

                });

            }];

            break;
        }

            ///  授权失败

        case AVAuthorizationStatusDenied:

            audioStatusValue = false;

            break;

            ///  成功授权

        case AVAuthorizationStatusAuthorized:

            audioStatusValue = true;

            break;

        default:

            audioStatusValue = false;

            break;
    }

    /// no  access to video

    if (!videoStatusValue) {

        [self OpenSettingCenterWithTitle:cameraPromptTitle description:cameraPromptDetailInfo];

        return;
    }

    /// no  access to audio

    if (!audioStatusValue) {

        [self OpenSettingCenterWithTitle:microPhonePromptTitle description:microPhonePromptDetailInfo];

        return;
    }

    /// all have access to

    if (videoStatusValue == true && audioStatusValue == true) {

        successBlock(true);
    }

}

#pragma mark - OpenSettingCenterWithTitle

-(void)OpenSettingCenterWithTitle:(NSString *)title description:(NSString *)description{

    DQAlertView *  alertView = [[DQAlertView alloc] initWithTitle:title message:description cancelButtonTitle:@"取消" otherButtonTitle:@"去设置"];

    alertView.otherButtonAction = ^{

        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    };

    [alertView show];
}

@end


text:
Make sure you have npm installed.
Run:
```
npm install http-server -g
```

Run:
```
http-server
```

View at: http://localhost:8080/0089-text-part-2-canvas

* NOTE: moved vendor and images out of folder.
  * Running from main directory instead inside this directory.

## CONCEPTS:

* Text using canvas as an overlay

## RESOURCES:

* https://github.com/davidwparker/programmingtil-webgl/tree/master/0089-text-part-2-canvas


text:
import * as ts from 'typescript';
import {AbsoluteFsPath} from '../../../src/ngtsc/file_system';
import {ImportRewriter, NoopImportRewriter, R3SymbolsImportRewriter} from '../../../src/ngtsc/imports';
import {NgccFlatImportRewriter} from './ngcc_import_rewriter';

/**
 * Information about a file that has been rendered.
 */
export interface FileToWrite {
  /** Path to where the file should be written. */
  path: AbsoluteFsPath;
  /** The contents of the file to be be written. */
  contents: string;
}

/**
 * Create an appropriate ImportRewriter given the parameters.
 */
export function getImportRewriter(
    r3SymbolsFile: ts.SourceFile|null, isCore: boolean, isFlat: boolean): ImportRewriter {
  if (isCore && isFlat) {
    return new NgccFlatImportRewriter();
  } else if (isCore) {
    return new R3SymbolsImportRewriter(r3SymbolsFile!.fileName);
  } else {
    return new NoopImportRewriter();
  }
}

export function stripExtension<T extends string>(filePath: T): T {
  return filePath.replace(/\.(js|d\.ts)$/, '') as T;
}


text:
package apple.foundation;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.uikit.*;
import apple.coreanimation.*;
import apple.coredata.*;
import apple.coremedia.*;
import apple.security.*;
import apple.dispatch.*;

@Library("Foundation/Foundation.h") @Mapping("NSURLAuthenticationChallenge")
public class NSURLAuthenticationChallenge
    extends NSObject
     {

    @Mapping("initWithProtectionSpace:proposedCredential:previousFailureCount:failureResponse:error:sender:")
    public NSURLAuthenticationChallenge(NSURLProtectionSpace space, NSURLCredential credential, @MachineSizedSInt long previousFailureCount, NSURLResponse response, NSError error, NSURLAuthenticationChallengeSender sender) { }
    @Mapping("initWithAuthenticationChallenge:sender:")
    public NSURLAuthenticationChallenge(NSURLAuthenticationChallenge challenge, NSURLAuthenticationChallengeSender sender) { }
    @Mapping("init")
    public NSURLAuthenticationChallenge() { }

    @Mapping("protectionSpace")
    public native NSURLProtectionSpace getProtectionSpace();
    @Mapping("proposedCredential")
    public native NSURLCredential getProposedCredential();
    @Mapping("previousFailureCount")
    public native @MachineSizedSInt long getPreviousFailureCount();
    @Mapping("failureResponse")
    public native NSURLResponse getFailureResponse();
    @Mapping("error")
    public native NSError getError();
    @Mapping("sender")
    public native NSURLAuthenticationChallengeSender getSender();

}


text:
Foundation version of the tabs directive.

### Settings ###

#### `<tabset>` ####

 * `vertical`
 	_(Defaults: false)_ :
 	Whether tabs appear vertically stacked.

 * `open-on-load`
  _(Defaults: true)_ :
  Whether to open an active tab automatically.

#### `<tab>` ####

 * `heading` or `<tab-heading>`
 	:
 	Heading text or HTML markup.

 * `active` <i class="fa fa-eye"></i>
 	_(Defaults: false)_ :
 	Whether tab is currently selected.

 * `select()`
 	_(Defaults: null)_ :
 	An optional expression called when tab is activated.


text:
package com.aol.cyclops.comprehensions;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import lombok.Value;
import lombok.val;

import org.junit.Test;

import com.aol.cyclops.comprehensions.donotation.UntypedDo;
import com.aol.cyclops.comprehensions.donotation.typed.Do;
import com.aol.cyclops.lambda.api.Decomposable;

public class DecomposableTest {

	@Test
	public void decomposable(){
		val one = new  MyCase("hello",20);
		val two  = new MyCase2("France");

		Stream<String> result = UntypedDo.add(one)
								  .add(two)
								  .yield(v1->v2-> v1.toString() + v2.toString());

		assertThat(result.collect(Collectors.toList()),equalTo(Arrays.asList("helloFrance","20France")));
	}

	@Value static class MyCase implements Decomposable{ String name; int value;}
	@Value static class MyCase2 implements Decomposable{ String country;}
}