text:
<?php

require_once dirname(__FILE__).'/AbstractGeneratedCodeTest.php';

class GeneratedCodeWithCallbackTest extends AbstractGeneratedCodeTest
{
    public function setUp()
    {
        self::$client = new math\MathClient(
        getenv('GRPC_TEST_HOST'),
        ['credentials' => Grpc\ChannelCredentials::createInsecure(),
         'update_metadata' => function ($a_hash,
                                        $client = []) {
                                $a_copy = $a_hash;
                                $a_copy['foo'] = ['bar'];

                                return $a_copy;
                              }]);
    }

    public function tearDown()
    {
        self::$client->close();
    }
}


text:
digger.io is very good at making these things called 'apps'.

You have heard of them - there are thousands of them all clamouring for your attention via a little window called 'store' on your smartphone.

Also, it is getting easier to publish these 'apps' using simple HTML ([PhoneGap](http://phonegap.com/) and [trigger.io](https://trigger.io/) for example).

##Build
Easy:

	blueprints
	gui
	theme
	meta (icon, description etc)

Hard:

	yeoman, grunt and bower interface
	blueprint designer
	bootstrap theme generator
	build and deployment
	scaling
	analytics

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/devicefarm/DeviceFarm_EXPORTS.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace DeviceFarm
{
namespace Model
{

  /**
   *
Represents entity counters.

See Also:
   AWS
   * API Reference

   */
  class AWS_DEVICEFARM_API Counters
  {
  public:
    Counters();
    Counters(Aws::Utils::Json::JsonView jsonValue);
    Counters& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The total number of entities.

     */
    inline int GetTotal() const{ return m_total; }

    /**
     *
The total number of entities.

     */
    inline bool TotalHasBeenSet() const { return m_totalHasBeenSet; }

    /**
     *
The total number of entities.

     */
    inline void SetTotal(int value) { m_totalHasBeenSet = true; m_total = value; }

    /**
     *
The total number of entities.

     */
    inline Counters& WithTotal(int value) { SetTotal(value); return *this;}

    /**
     *
The number of passed entities.

     */
    inline int GetPassed() const{ return m_passed; }

    /**
     *
The number of passed entities.

     */
    inline bool PassedHasBeenSet() const { return m_passedHasBeenSet; }

    /**
     *
The number of passed entities.

     */
    inline void SetPassed(int value) { m_passedHasBeenSet = true; m_passed = value; }

    /**
     *
The number of passed entities.

     */
    inline Counters& WithPassed(int value) { SetPassed(value); return *this;}

    /**
     *
The number of failed entities.

     */
    inline int GetFailed() const{ return m_failed; }

    /**
     *
The number of failed entities.

     */
    inline bool FailedHasBeenSet() const { return m_failedHasBeenSet; }

    /**
     *
The number of failed entities.

     */
    inline void SetFailed(int value) { m_failedHasBeenSet = true; m_failed = value; }

    /**
     *
The number of failed entities.

     */
    inline Counters& WithFailed(int value) { SetFailed(value); return *this;}

    /**
     *
The number of warned entities.

     */
    inline int GetWarned() const{ return m_warned; }

    /**
     *
The number of warned entities.

     */
    inline bool WarnedHasBeenSet() const { return m_warnedHasBeenSet; }

    /**
     *
The number of warned entities.

     */
    inline void SetWarned(int value) { m_warnedHasBeenSet = true; m_warned = value; }

    /**
     *
The number of warned entities.

     */
    inline Counters& WithWarned(int value) { SetWarned(value); return *this;}

    /**
     *
The number of errored entities.

     */
    inline int GetErrored() const{ return m_errored; }

    /**
     *
The number of errored entities.

     */
    inline bool ErroredHasBeenSet() const { return m_erroredHasBeenSet; }

    /**
     *
The number of errored entities.

     */
    inline void SetErrored(int value) { m_erroredHasBeenSet = true; m_errored = value; }

    /**
     *
The number of errored entities.

     */
    inline Counters& WithErrored(int value) { SetErrored(value); return *this;}

    /**
     *
The number of stopped entities.

     */
    inline int GetStopped() const{ return m_stopped; }

    /**
     *
The number of stopped entities.

     */
    inline bool StoppedHasBeenSet() const { return m_stoppedHasBeenSet; }

    /**
     *
The number of stopped entities.

     */
    inline void SetStopped(int value) { m_stoppedHasBeenSet = true; m_stopped = value; }

    /**
     *
The number of stopped entities.

     */
    inline Counters& WithStopped(int value) { SetStopped(value); return *this;}

    /**
     *
The number of skipped entities.

     */
    inline int GetSkipped() const{ return m_skipped; }

    /**
     *
The number of skipped entities.

     */
    inline bool SkippedHasBeenSet() const { return m_skippedHasBeenSet; }

    /**
     *
The number of skipped entities.

     */
    inline void SetSkipped(int value) { m_skippedHasBeenSet = true; m_skipped = value; }

    /**
     *
The number of skipped entities.

     */
    inline Counters& WithSkipped(int value) { SetSkipped(value); return *this;}

  private:

    int m_total;
    bool m_totalHasBeenSet;

    int m_passed;
    bool m_passedHasBeenSet;

    int m_failed;
    bool m_failedHasBeenSet;

    int m_warned;
    bool m_warnedHasBeenSet;

    int m_errored;
    bool m_erroredHasBeenSet;

    int m_stopped;
    bool m_stoppedHasBeenSet;

    int m_skipped;
    bool m_skippedHasBeenSet;
  };

} // namespace Model
} // namespace DeviceFarm
} // namespace Aws


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
    internal partial class AbstractSuppressionCodeFixProvider
    {
        /// <summary>
        /// Helper methods for pragma suppression add/remove batch fixers.
        /// </summary>
        private static class PragmaBatchFixHelpers
        {
            public static CodeAction CreateBatchPragmaFix(
                AbstractSuppressionCodeFixProvider suppressionFixProvider,
                Document document,
                ImmutableArray<IPragmaBasedCodeAction> pragmaActions,
                ImmutableArray<Diagnostic> pragmaDiagnostics,
                FixAllState fixAllState,
                CancellationToken cancellationToken)
            {
                // This is a temporary generated code action, which doesn't need telemetry, hence suppressing RS0005.
#pragma warning disable RS0005 // Do not use generic CodeAction.Create to create CodeAction
                return CodeAction.Create(
                    ((CodeAction)pragmaActions[0]).Title,
                    createChangedDocument: ct =>
                        BatchPragmaFixesAsync(suppressionFixProvider, document, pragmaActions, pragmaDiagnostics, cancellationToken),
                    equivalenceKey: fixAllState.CodeActionEquivalenceKey);
#pragma warning restore RS0005 // Do not use generic CodeAction.Create to create CodeAction
            }

            private static async Task<Document> BatchPragmaFixesAsync(
                AbstractSuppressionCodeFixProvider suppressionFixProvider,
                Document document,
                ImmutableArray<IPragmaBasedCodeAction> pragmaActions,
                ImmutableArray<Diagnostic> diagnostics,
                CancellationToken cancellationToken)
            {
                // We apply all the pragma suppression fixes sequentially.
                // At every application, we track the updated locations for remaining diagnostics in the document.
                var currentDiagnosticSpans = new Dictionary<Diagnostic, TextSpan>();
                foreach (var diagnostic in diagnostics)
                {
                    currentDiagnosticSpans.Add(diagnostic, diagnostic.Location.SourceSpan);
                }

                var currentDocument = document;
                for (int i = 0; i < pragmaActions.Length; i++)
                {
                    var originalpragmaAction = pragmaActions[i];
                    var diagnostic = diagnostics[i];

                    // Get the diagnostic span for the diagnostic in latest document snapshot.
                    TextSpan currentDiagnosticSpan;
                    if (!currentDiagnosticSpans.TryGetValue(diagnostic, out currentDiagnosticSpan))
                    {
                        // Diagnostic whose location conflicts with a prior fix.
                        continue;
                    }

                    // Compute and apply pragma suppression fix.
                    var currentTree = await currentDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
                    var currentLocation = Location.Create(currentTree, currentDiagnosticSpan);
                    diagnostic = Diagnostic.Create(
                        id: diagnostic.Id,
                        category: diagnostic.Descriptor.Category,
                        message: diagnostic.GetMessage(),
                        severity: diagnostic.Severity,
                        defaultSeverity: diagnostic.DefaultSeverity,
                        isEnabledByDefault: diagnostic.Descriptor.IsEnabledByDefault,
                        warningLevel: diagnostic.WarningLevel,
                        title: diagnostic.Descriptor.Title,
                        description: diagnostic.Descriptor.Description,
                        helpLink: diagnostic.Descriptor.HelpLinkUri,
                        location: currentLocation,
                        additionalLocations: diagnostic.AdditionalLocations,
                        customTags: diagnostic.Descriptor.CustomTags,
                        properties: diagnostic.Properties,
                        isSuppressed: diagnostic.IsSuppressed);

                    var newSuppressionFixes = await suppressionFixProvider.GetSuppressionsAsync(currentDocument, currentDiagnosticSpan, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false);
                    var newSuppressionFix = newSuppressionFixes.SingleOrDefault();
                    if (newSuppressionFix != null)
                    {
                        var newPragmaAction = newSuppressionFix.Action as IPragmaBasedCodeAction ??
                            newSuppressionFix.Action.GetCodeActions().OfType<IPragmaBasedCodeAction>().SingleOrDefault();
                        if (newPragmaAction != null)
                        {
                            // Get the text changes with pragma suppression add/removals.
                            // Note: We do it one token at a time to ensure we get single text change in the new document, otherwise UpdateDiagnosticSpans won't function as expected.
                            // Update the diagnostics spans based on the text changes.
                            var startTokenChanges = await GetTextChangesAsync(newPragmaAction, currentDocument, diagnostics, currentDiagnosticSpans,
                                includeStartTokenChange: true, includeEndTokenChange: false, cancellationToken: cancellationToken).ConfigureAwait(false);

                            var endTokenChanges = await GetTextChangesAsync(newPragmaAction, currentDocument, diagnostics, currentDiagnosticSpans,
                                includeStartTokenChange: false, includeEndTokenChange: true, cancellationToken: cancellationToken).ConfigureAwait(false);

                            var currentText = await currentDocument.GetTextAsync(cancellationToken).ConfigureAwait(false);
                            var orderedChanges = startTokenChanges.Concat(endTokenChanges).OrderBy(change => change.Span).Distinct();
                            var newText = currentText.WithChanges(orderedChanges);
                            currentDocument = currentDocument.WithText(newText);

                            // Update the diagnostics spans based on the text changes.
                            UpdateDiagnosticSpans(diagnostics, currentDiagnosticSpans, orderedChanges);
                        }
                    }
                }

                return currentDocument;
            }

            private static async Task<IEnumerable<TextChange>> GetTextChangesAsync(
                IPragmaBasedCodeAction pragmaAction,
                Document currentDocument,
                ImmutableArray<Diagnostic> diagnostics,
                Dictionary<Diagnostic, TextSpan> currentDiagnosticSpans,
                bool includeStartTokenChange,
                bool includeEndTokenChange,
                CancellationToken cancellationToken)
            {
                var newDocument = await pragmaAction.GetChangedDocumentAsync(includeStartTokenChange, includeEndTokenChange, cancellationToken).ConfigureAwait(false);
                return await newDocument.GetTextChangesAsync(currentDocument, cancellationToken).ConfigureAwait(false);
            }

            private static void UpdateDiagnosticSpans(ImmutableArray<Diagnostic> diagnostics, Dictionary<Diagnostic, TextSpan> currentDiagnosticSpans, IEnumerable<TextChange> textChanges)
            {
                Func<TextSpan, TextChange, bool> isPriorSpan = (span, textChange) => span.End <= textChange.Span.Start;
                Func<TextSpan, TextChange, bool> isFollowingSpan = (span, textChange) => span.Start >= textChange.Span.End;
                Func<TextSpan, TextChange, bool> isEnclosingSpan = (span, textChange) => span.Contains(textChange.Span);

                foreach (var diagnostic in diagnostics)
                {
                    // We use 'originalSpan' to identify if the diagnostic is prior/following/enclosing with respect to each text change.
                    // We use 'currentSpan' to track updates made to the originalSpan by each text change.
                    TextSpan originalSpan;
                    if (!currentDiagnosticSpans.TryGetValue(diagnostic, out originalSpan))
                    {
                        continue;
                    }

                    var currentSpan = originalSpan;
                    foreach (var textChange in textChanges)
                    {
                        if (isPriorSpan(originalSpan, textChange))
                        {
                            // Prior span, needs no update.
                            continue;
                        }

                        var delta = textChange.NewText.Length - textChange.Span.Length;
                        if (delta != 0)
                        {
                            if (isFollowingSpan(originalSpan, textChange))
                            {
                                // Following span.
                                var newStart = currentSpan.Start + delta;
                                currentSpan = new TextSpan(newStart, currentSpan.Length);
                                currentDiagnosticSpans[diagnostic] = currentSpan;
                            }
                            else if (isEnclosingSpan(originalSpan, textChange))
                            {
                                // Enclosing span.
                                var newLength = currentSpan.Length + delta;
                                currentSpan = new TextSpan(currentSpan.Start, newLength);
                                currentDiagnosticSpans[diagnostic] = currentSpan;
                            }
                            else
                            {
                                // Overlapping span.
                                // Drop conflicting diagnostics.
                                currentDiagnosticSpans.Remove(diagnostic);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
}


text:
export ntp_server="ntp.nict.jp"

export http_proxy=http://proxy.http.example.com/
export https_proxy=http://proxy.https.example.com/
export ftp_proxy=http://proxy.ftp.example.com/
export rsync_proxy=http://proxy.rsync.example.com/
export no_proxy=localhost

export admin_mail_address=pocci@example.com
export service_type=/user_data/setup.jo.yml

export daily_backup_hour=-


text:
using System;

class CenturiesToMinutes
{
    static void Main()
    {
        int centuries = int.Parse(Console.ReadLine());

        int years = centuries * 100;
        int days =(int) (years * 365.2422);
        int hours = days * 24;
        int minutes = hours * 60;

        Console.WriteLine("{0} centuries = {1} years = {2} days = {3} hours = {4} minutes", centuries, years, days, hours, minutes);
    }
}


text:
/**
 * Autogenerated by Thrift Compiler (0.9.2)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package com.navercorp.pinpoint.thrift.dto.command;

import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.2)", date = "2015-8-18")
public class TCommandTransferResponse implements org.apache.thrift.TBase<TCommandTransferResponse, TCommandTransferResponse._Fields>, java.io.Serializable, Cloneable, Comparable<TCommandTransferResponse> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TCommandTransferResponse");

  private static final org.apache.thrift.protocol.TField ROUTE_RESULT_FIELD_DESC = new org.apache.thrift.protocol.TField("routeResult", org.apache.thrift.protocol.TType.I32, (short)1);
  private static final org.apache.thrift.protocol.TField PAYLOAD_FIELD_DESC = new org.apache.thrift.protocol.TField("payload", org.apache.thrift.protocol.TType.STRING, (short)2);
  private static final org.apache.thrift.protocol.TField MESSAGE_FIELD_DESC = new org.apache.thrift.protocol.TField("message", org.apache.thrift.protocol.TType.STRING, (short)3);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new TCommandTransferResponseStandardSchemeFactory());
    schemes.put(TupleScheme.class, new TCommandTransferResponseTupleSchemeFactory());
  }

  private TRouteResult routeResult; // required
  private ByteBuffer payload; // required
  private String message; // optional

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    /**
     *
     * @see TRouteResult
     */
    ROUTE_RESULT((short)1, "routeResult"),
    PAYLOAD((short)2, "payload"),
    MESSAGE((short)3, "message");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // ROUTE_RESULT
          return ROUTE_RESULT;
        case 2: // PAYLOAD
          return PAYLOAD;
        case 3: // MESSAGE
          return MESSAGE;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private static final _Fields optionals[] = {_Fields.MESSAGE};
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.ROUTE_RESULT, new org.apache.thrift.meta_data.FieldMetaData("routeResult", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.EnumMetaData(org.apache.thrift.protocol.TType.ENUM, TRouteResult.class)));
    tmpMap.put(_Fields.PAYLOAD, new org.apache.thrift.meta_data.FieldMetaData("payload", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING        , true)));
    tmpMap.put(_Fields.MESSAGE, new org.apache.thrift.meta_data.FieldMetaData("message", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TCommandTransferResponse.class, metaDataMap);
  }

  public TCommandTransferResponse() {
  }

  public TCommandTransferResponse(
    TRouteResult routeResult,
    ByteBuffer payload)
  {
    this();
    this.routeResult = routeResult;
    this.payload = org.apache.thrift.TBaseHelper.copyBinary(payload);
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public TCommandTransferResponse(TCommandTransferResponse other) {
    if (other.isSetRouteResult()) {
      this.routeResult = other.routeResult;
    }
    if (other.isSetPayload()) {
      this.payload = org.apache.thrift.TBaseHelper.copyBinary(other.payload);
    }
    if (other.isSetMessage()) {
      this.message = other.message;
    }
  }

  public TCommandTransferResponse deepCopy() {
    return new TCommandTransferResponse(this);
  }

  @Override
  public void clear() {
    this.routeResult = null;
    this.payload = null;
    this.message = null;
  }

  /**
   *
   * @see TRouteResult
   */
  public TRouteResult getRouteResult() {
    return this.routeResult;
  }

  /**
   *
   * @see TRouteResult
   */
  public void setRouteResult(TRouteResult routeResult) {
    this.routeResult = routeResult;
  }

  public void unsetRouteResult() {
    this.routeResult = null;
  }

  /** Returns true if field routeResult is set (has been assigned a value) and false otherwise */
  public boolean isSetRouteResult() {
    return this.routeResult != null;
  }

  public void setRouteResultIsSet(boolean value) {
    if (!value) {
      this.routeResult = null;
    }
  }

  public byte[] getPayload() {
    setPayload(org.apache.thrift.TBaseHelper.rightSize(payload));
    return payload == null ? null : payload.array();
  }

  public ByteBuffer bufferForPayload() {
    return org.apache.thrift.TBaseHelper.copyBinary(payload);
  }

  public void setPayload(byte[] payload) {
    this.payload = payload == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(payload, payload.length));
  }

  public void setPayload(ByteBuffer payload) {
    this.payload = org.apache.thrift.TBaseHelper.copyBinary(payload);
  }

  public void unsetPayload() {
    this.payload = null;
  }

  /** Returns true if field payload is set (has been assigned a value) and false otherwise */
  public boolean isSetPayload() {
    return this.payload != null;
  }

  public void setPayloadIsSet(boolean value) {
    if (!value) {
      this.payload = null;
    }
  }

  public String getMessage() {
    return this.message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public void unsetMessage() {
    this.message = null;
  }

  /** Returns true if field message is set (has been assigned a value) and false otherwise */
  public boolean isSetMessage() {
    return this.message != null;
  }

  public void setMessageIsSet(boolean value) {
    if (!value) {
      this.message = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case ROUTE_RESULT:
      if (value == null) {
        unsetRouteResult();
      } else {
        setRouteResult((TRouteResult)value);
      }
      break;

    case PAYLOAD:
      if (value == null) {
        unsetPayload();
      } else {
        setPayload((ByteBuffer)value);
      }
      break;

    case MESSAGE:
      if (value == null) {
        unsetMessage();
      } else {
        setMessage((String)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case ROUTE_RESULT:
      return getRouteResult();

    case PAYLOAD:
      return getPayload();

    case MESSAGE:
      return getMessage();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case ROUTE_RESULT:
      return isSetRouteResult();
    case PAYLOAD:
      return isSetPayload();
    case MESSAGE:
      return isSetMessage();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof TCommandTransferResponse)
      return this.equals((TCommandTransferResponse)that);
    return false;
  }

  public boolean equals(TCommandTransferResponse that) {
    if (that == null)
      return false;

    boolean this_present_routeResult = true && this.isSetRouteResult();
    boolean that_present_routeResult = true && that.isSetRouteResult();
    if (this_present_routeResult || that_present_routeResult) {
      if (!(this_present_routeResult && that_present_routeResult))
        return false;
      if (!this.routeResult.equals(that.routeResult))
        return false;
    }

    boolean this_present_payload = true && this.isSetPayload();
    boolean that_present_payload = true && that.isSetPayload();
    if (this_present_payload || that_present_payload) {
      if (!(this_present_payload && that_present_payload))
        return false;
      if (!this.payload.equals(that.payload))
        return false;
    }

    boolean this_present_message = true && this.isSetMessage();
    boolean that_present_message = true && that.isSetMessage();
    if (this_present_message || that_present_message) {
      if (!(this_present_message && that_present_message))
        return false;
      if (!this.message.equals(that.message))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    List<Object> list = new ArrayList<Object>();

    boolean present_routeResult = true && (isSetRouteResult());
    list.add(present_routeResult);
    if (present_routeResult)
      list.add(routeResult.getValue());

    boolean present_payload = true && (isSetPayload());
    list.add(present_payload);
    if (present_payload)
      list.add(payload);

    boolean present_message = true && (isSetMessage());
    list.add(present_message);
    if (present_message)
      list.add(message);

    return list.hashCode();
  }

  @Override
  public int compareTo(TCommandTransferResponse other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;

    lastComparison = Boolean.valueOf(isSetRouteResult()).compareTo(other.isSetRouteResult());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetRouteResult()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.routeResult, other.routeResult);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetPayload()).compareTo(other.isSetPayload());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetPayload()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.payload, other.payload);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetMessage()).compareTo(other.isSetMessage());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetMessage()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.message, other.message);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("TCommandTransferResponse(");
    boolean first = true;

    sb.append("routeResult:");
    if (this.routeResult == null) {
      sb.append("null");
    } else {
      sb.append(this.routeResult);
    }
    first = false;
    if (!first) sb.append(", ");
    sb.append("payload:");
    if (this.payload == null) {
      sb.append("null");
    } else {
      org.apache.thrift.TBaseHelper.toString(this.payload, sb);
    }
    first = false;
    if (isSetMessage()) {
      if (!first) sb.append(", ");
      sb.append("message:");
      if (this.message == null) {
        sb.append("null");
      } else {
        sb.append(this.message);
      }
      first = false;
    }
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    // check for sub-struct validity
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class TCommandTransferResponseStandardSchemeFactory implements SchemeFactory {
    public TCommandTransferResponseStandardScheme getScheme() {
      return new TCommandTransferResponseStandardScheme();
    }
  }

  private static class TCommandTransferResponseStandardScheme extends StandardScheme<TCommandTransferResponse> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, TCommandTransferResponse struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // ROUTE_RESULT
            if (schemeField.type == org.apache.thrift.protocol.TType.I32) {
              struct.routeResult = com.navercorp.pinpoint.thrift.dto.command.TRouteResult.findByValue(iprot.readI32());
              struct.setRouteResultIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // PAYLOAD
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.payload = iprot.readBinary();
              struct.setPayloadIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 3: // MESSAGE
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.message = iprot.readString();
              struct.setMessageIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, TCommandTransferResponse struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.routeResult != null) {
        oprot.writeFieldBegin(ROUTE_RESULT_FIELD_DESC);
        oprot.writeI32(struct.routeResult.getValue());
        oprot.writeFieldEnd();
      }
      if (struct.payload != null) {
        oprot.writeFieldBegin(PAYLOAD_FIELD_DESC);
        oprot.writeBinary(struct.payload);
        oprot.writeFieldEnd();
      }
      if (struct.message != null) {
        if (struct.isSetMessage()) {
          oprot.writeFieldBegin(MESSAGE_FIELD_DESC);
          oprot.writeString(struct.message);
          oprot.writeFieldEnd();
        }
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class TCommandTransferResponseTupleSchemeFactory implements SchemeFactory {
    public TCommandTransferResponseTupleScheme getScheme() {
      return new TCommandTransferResponseTupleScheme();
    }
  }

  private static class TCommandTransferResponseTupleScheme extends TupleScheme<TCommandTransferResponse> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, TCommandTransferResponse struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      BitSet optionals = new BitSet();
      if (struct.isSetRouteResult()) {
        optionals.set(0);
      }
      if (struct.isSetPayload()) {
        optionals.set(1);
      }
      if (struct.isSetMessage()) {
        optionals.set(2);
      }
      oprot.writeBitSet(optionals, 3);
      if (struct.isSetRouteResult()) {
        oprot.writeI32(struct.routeResult.getValue());
      }
      if (struct.isSetPayload()) {
        oprot.writeBinary(struct.payload);
      }
      if (struct.isSetMessage()) {
        oprot.writeString(struct.message);
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, TCommandTransferResponse struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      BitSet incoming = iprot.readBitSet(3);
      if (incoming.get(0)) {
        struct.routeResult = com.navercorp.pinpoint.thrift.dto.command.TRouteResult.findByValue(iprot.readI32());
        struct.setRouteResultIsSet(true);
      }
      if (incoming.get(1)) {
        struct.payload = iprot.readBinary();
        struct.setPayloadIsSet(true);
      }
      if (incoming.get(2)) {
        struct.message = iprot.readString();
        struct.setMessageIsSet(true);
      }
    }
  }

}


text:
CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(40) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


text:
   /*******************************************************/
   /*      "C" Language Integrated Production System      */
   /*                                                     */
   /*            CLIPS Version 6.40  01/06/16             */
   /*                                                     */
   /*         DEFMODULE BASIC COMMANDS HEADER FILE        */
   /*******************************************************/

/*************************************************************/
/* Purpose: Implements core commands for the deffacts        */
/*   construct such as clear, reset, save, undeffacts,       */
/*   ppdeffacts, list-deffacts, and get-deffacts-list.       */
/*                                                           */
/* Principal Programmer(s):                                  */
/*      Gary D. Riley                                        */
/*                                                           */
/* Contributing Programmer(s):                               */
/*      Brian L. Dantes                                      */
/*                                                           */
/* Revision History:                                         */
/*                                                           */
/*      6.30: Removed conditional code for unsupported       */
/*            compilers/operating systems (IBM_MCW and       */
/*            MAC_MCW).                                      */
/*                                                           */
/*            Added const qualifiers to remove C++           */
/*            deprecation warnings.                          */
/*                                                           */
/*            Converted API macros to function calls.        */
/*                                                           */
/*************************************************************/

#ifndef _H_modulbsc

#pragma once

#define _H_modulbsc

#include "evaluatn.h"

   void                           DefmoduleBasicCommands(void *);
   void                           EnvGetDefmoduleListFunction(UDFContext *,CLIPSValue *);
   void                           EnvGetDefmoduleList(void *,DATA_OBJECT_PTR);
   void                           PPDefmoduleCommand(UDFContext *,CLIPSValue *);
   bool                           PPDefmodule(void *,const char *,const char *);
   void                           ListDefmodulesCommand(UDFContext *,CLIPSValue *);
   void                           EnvListDefmodules(void *,const char *);

#endif /* _H_modulbsc */


text:
CKEDITOR.plugins.setLang( 'uploadwidget', 'pt-br', {
	abort: 'Envio cancelado pelo usuário.',
	doneOne: 'Arquivo enviado com sucesso.',
	doneMany: 'Enviados %1 arquivos com sucesso.',
	uploadOne: 'Enviando arquivo({percentage}%)...',
	uploadMany: 'Enviando arquivos, {current} de {max} completos ({percentage}%)...'
} );


text:
<!DOCTYPE html>
<title>CSS aspect-ratio: A stretch alignment in one axis, and a definite length in the other causes the aspect-ratio to be ignored.</title>
<link rel="help" href="https://drafts.csswg.org/css-sizing-4/#aspect-ratio">
<link rel="help" href="https://drafts.csswg.org/css-grid/#grid-item-sizing">
<link rel="match" href="../../reference/ref-filled-green-100px-square.xht" />

Test passes if there is a filled green square and no red.


text:
define([
    'jquery',
    'underscore',
    'lib/mustache',
    'colors',
    'calculations',
    'interactioncoordinator',
    'modelviews/currentworkplane',
    'scene',
    'geomnode',
    'geometrygraphsingleton',
    'modelviews/vertexMV',
    'modelviews/originview',
    'modelviews/zanchorview',
    'modelviews/originDOMView',
    'modelviews/transforms/uvwrotationsceneviews',
    'selection',
    'asyncAPI',
    'icons',
  ], function(
    $,
    _,
    Mustache,
    colors,
    calc,
    coordinator,
    currentWorkplane,
    sceneModel,
    geomNode,
    geometryGraph,
    VertexMV,
    OriginView,
    ZAnchorView,
    OriginDOMView,
    UVWRotationSceneViews,
    selection,
    AsyncAPI,
    icons) {

    var EditingModel = VertexMV.EditingModel.extend({

      initialize: function(options) {
        this.SceneView = GridView;
        VertexMV.EditingModel.prototype.initialize.call(this, options);
        this.views.push(new EditingDOMView({model: this}));
        this.views.push(new OriginView({model: this, vertex: this.vertex, origin: this.vertex.workplane.origin, isGlobal: true }));
        this.views.push(new OriginDOMView({model: this, vertex: this.vertex, origin: this.vertex.workplane.origin, isGlobal: true }));
        this.views.push(new ZAnchorView({model: this, vertex: this.vertex, origin: this.vertex.workplane.origin, isGlobal: true }));
        this.views.push(new UVWRotationSceneViews.U({initiator: this, model: this, vertex: this.vertex, isWorkplane: true}));
        this.views.push(new UVWRotationSceneViews.V({initiator: this, model: this, vertex: this.vertex, isWorkplane: true}));
        this.views.push(new UVWRotationSceneViews.W({initiator: this, model: this, vertex: this.vertex, isWorkplane: true}));
        coordinator.on('sceneClick', this.tryCommit, this);
      },

      destroy: function() {
        VertexMV.EditingModel.prototype.destroy.call(this);
        coordinator.off('sceneClick', this.tryCommit, this);
      },

      getExtents: function() {
        return {
          center: new THREE.Vector3(),
          dx: Math.sqrt(45*45/3),
          dy: Math.sqrt(45*45/3),
          dz: Math.sqrt(45*45/3),
        };
      },

      hideOtherViews: function() {
      },

      rotate: function(origin, axisAngle) {
        this.vertex.workplane.axis.x = parseFloat(axisAngle.axis.x.toFixed(3));
        this.vertex.workplane.axis.y = parseFloat(axisAngle.axis.y.toFixed(3));
        this.vertex.workplane.axis.z = parseFloat(axisAngle.axis.z.toFixed(3));
        this.vertex.workplane.angle  = parseFloat(axisAngle.angle.toFixed(2));
        this.vertex.trigger('change', this.vertex);

      },

    });

    var DisplayModel = VertexMV.DisplayModel.extend({

      initialize: function(options) {
        this.displayModelConstructor = DisplayModel;
        this.SceneView = GridView;
        this.savedWorkplanes = [];
        VertexMV.DisplayModel.prototype.initialize.call(this, options);

        currentWorkplane.set(this);

        coordinator.on('mousemove', this.mousemove, this);
        coordinator.on('sceneClick', this.workplaneClick, this);
        coordinator.on('sceneDblClick', this.workplaneDblClick, this);

        geometryGraph.on('vertexAdded', this.vertexAdded, this);
        geometryGraph.on('vertexRemoved', this.vertexRemoved, this);
        geometryGraph.on('vertexReplaced', this.vertexReplaced, this);

        selection.on('selected', this.vertexSelected, this);
        selection.on('deselected', this.vertexDeselected, this);

        this.views.push(new DisplayDOMView({model: this}));
      },

      destroy: function() {
        VertexMV.DisplayModel.prototype.destroy.call(this);
        coordinator.off('mousemove', this.mousemove, this);
        coordinator.off('sceneClick', this.workplaneClick, this);
        coordinator.off('sceneDblClick', this.workplaneDblClick, this);
        geometryGraph.off('vertexAdded', this.vertexAdded, this);
        geometryGraph.off('vertexRemoved', this.vertexRemoved, this);
        geometryGraph.off('vertexReplaced', this.vertexReplaced, this);

        selection.off('selected', this.vertexSelected, this);
        selection.off('deselected', this.vertexDeselected, this);

      },

      workplaneClick: function() {
        VertexMV.eventProxy.trigger('workplaneClick');
      },

      workplaneDblClick: function() {
        VertexMV.eventProxy.trigger('workplaneDblClick');
      },

      mousemove: function(event) {
        VertexMV.eventProxy.trigger('workplanePositionChanged', event);
      },

      pushVertex: function(vertex) {
        this.savedWorkplanes.push(this.vertex.workplane);
        this.vertex.workplane = vertex.workplane;
      },

      popVertex: function() {
        this.vertex.workplane = this.savedWorkplanes.pop();
      },

      vertexAdded: function(vertex) {
        if (vertex.category === 'geometry') {
          this.trigger('change');
        }
      },

      vertexRemoved: function() {
        this.trigger('change');
      },

      // Push and pop the editing node's workplane
      // when it's being editied
      vertexReplaced: function(original, replacement) {
        if (replacement.category !== 'geometry') {
          this.trigger('change');
          return;
        }
        if (!replacement.proto && replacement.editing && !replacement.implicit) {
          this.pushVertex(replacement);
        } else if(!original.proto && original.editing && !original.implicit) {
          this.popVertex(replacement);
        }
        this.trigger('change');
      },

      // If selected and it's the only one - push the workplane
      // Otherwise pop the workplane again for multiple selected
      vertexSelected: function(selectedIds) {
        var allSelected = selection.getSelected();
        if ((allSelected.length === 1) && (selectedIds.length === 1)) {
          var vertex = geometryGraph.vertexById(selectedIds[0]);
          if (vertex.category === 'geometry') {
            this.selectedVertex = vertex;
            this.pushVertex(this.selectedVertex);
          }
        } else if (this.selectedVertex) {
          this.popVertex(this.selectedVertex);
          this.selectedVertex = undefined;
        }
        this.trigger('change');
      },

      vertexDeselected: function() {
        if (this.selectedVertex) {
          this.popVertex(this.selectedVertex);
          this.selectedVertex = undefined;
        }
        this.trigger('change');
      },

      gridSizeChanged: function() {
        this.trigger('change');
      },

    });

    var DisplayDOMView = VertexMV.DisplayDOMView.extend({

      render: function() {
        this.$el.html(Mustache.render(
          '
{{{icon}}}
',
          {
            icon: icons.workplane,
          }));
        $('#workplane-settings').append(this.$el);
      },

      events: {
        'click' : 'click',
      },

      click: function(event) {
        event.stopPropagation();
        selection.deselectAll();
        if (!geometryGraph.isEditing()) {
          AsyncAPI.edit(this.model.vertex);
        }
      },

    });

    var EditingDOMView = VertexMV.EditingDOMView.extend({

      render: function() {
        var template =
          '
' +
            '<input type="button" name="xy" value="XY"/>' +
            '<input type="button" name="yz" value="YZ"/>' +
            '<input type="button" name="zx" value="ZX"/>' +
          '
' +
          '
grid size:<input class="field gridsize" type="text"/>
' +
          '
origin
' +
          '
' +
            'x <input class="field originx" type="text" value="{{origin.x}}"></input>' +
            'y <input class="field originy" type="text" value="{{origin.y}}"></input>' +
            'z <input class="field originz" type="text" value="{{origin.z}}"></input>' +
          '
' +
          '
axis
' +
          '
' +
            'x <input class="field axisx" type="text" value="{{axis.x}}"></input>' +
            'y <input class="field axisy" type="text" value="{{axis.y}}"></input>' +
            'z <input class="field axisz" type="text" value="{{axis.z}}"></input>' +
          '
' +
          '
angle <input class="field angle" type="text" value="{{angle}}"></input>
';
        var workplane = this.model.vertex.workplane;
        var view = {
          gridsize: this.model.vertex.parameters.gridsize,
          origin : workplane.origin,
          axis: workplane.axis,
          angle: workplane.angle,
        };
        this.$el.html(Mustache.render(template, view));
        $('#workplane-settings').append(this.$el);
        return this;
      },

      events: function() {
        var vertexEvents = VertexMV.EditingDOMView.prototype.events.call(this);
        return _.extend(vertexEvents, {
          'click [name=xy]' : 'xy',
          'click [name=yz]' : 'yz',
          'click [name=zx]' : 'zx',
        });
      },

      xy: function() {
        // This convulted setting is because the origin object is referenced
        // in the origin view and z anchor.
        this.model.vertex.workplane.origin.x = 0;
        this.model.vertex.workplane.origin.y = 0;
        this.model.vertex.workplane.origin.z = 0;
        this.model.vertex.workplane.axis.x = 0;
        this.model.vertex.workplane.axis.y = 0;
        this.model.vertex.workplane.axis.z = 1;
        this.model.vertex.workplane.angle = 0;
        this.model.vertex.trigger('change', this.model.vertex);
      },

      yz: function() {
        var tanpi6 = parseFloat(Math.tan(Math.PI/6).toFixed(4));
        this.model.vertex.workplane.origin.x = 0;
        this.model.vertex.workplane.origin.y = 0;
        this.model.vertex.workplane.origin.z = 0;
        this.model.vertex.workplane.axis.x = tanpi6;
        this.model.vertex.workplane.axis.y = tanpi6;
        this.model.vertex.workplane.axis.z = tanpi6;
        this.model.vertex.workplane.angle = 120;

        this.model.vertex.trigger('change', this.model.vertex);
      },

      zx: function() {
        var mintanpi6 = parseFloat(-Math.tan(Math.PI/6).toFixed(4));
        this.model.vertex.workplane.origin.x = 0;
        this.model.vertex.workplane.origin.y = 0;
        this.model.vertex.workplane.origin.z = 0;
        this.model.vertex.workplane.axis.x = mintanpi6;
        this.model.vertex.workplane.axis.y = mintanpi6;
        this.model.vertex.workplane.axis.z = mintanpi6;
        this.model.vertex.workplane.angle = 120;
        this.model.vertex.trigger('change', this.model.vertex);
      },

      update: function() {
        var parameters = this.model.vertex.parameters;
        var workplane = this.model.vertex.workplane;
        ['x', 'y', 'z'].forEach(function(key) {
          this.$el.find('.origin' + key).val(workplane.origin[key]);
          this.$el.find('.axis' + key).val(workplane.axis[key]);
        }, this);
        this.$el.find('.angle').val(workplane.angle);
        this.$el.find('.gridsize').val(parameters.gridsize);
      },

      updateFromDOM: function() {
        var parameters = this.model.vertex.parameters;
        var workplane = this.model.vertex.workplane;
        var field;
        ['x', 'y', 'z'].forEach(function(key) {
          field = this.$el.find('.field.origin' + key);
          this.updateFromField(field, workplane.origin, key);

          field = this.$el.find('.field.axis' + key);
          this.updateFromField(field, workplane.axis, key);
        }, this);

        field = this.$el.find('.field.angle');
        this.updateFromField(field, workplane, 'angle');

        field = this.$el.find('.field.gridsize');
        this.updateFromField(field, parameters, 'gridsize');
      },

    });

    var GridView = VertexMV.SceneView.extend({

      initialize: function() {
        VertexMV.SceneView.prototype.initialize.call(this);
        this.model.on('change', this.render, this);
        this.model.vertex.on('change', this.render, this);
      },

      remove: function() {
        VertexMV.SceneView.prototype.remove.call(this);
        this.model.off('change', this.render, this);
        this.model.vertex.off('change', this.render, this);
      },

      render: function() {
        VertexMV.SceneView.prototype.render.call(this);

        var grid = this.model.vertex.parameters.gridsize;
        var boundary = Math.floor(grid*10)*10;

        var majorGridLineGeometry = new THREE.Geometry();
        var majorMaterialInside = new THREE.LineBasicMaterial({
          opacity: 0.5,
          color: colors.workplane.majorGridLine
        });
        majorGridLineGeometry.vertices.push(new THREE.Vector3(-Math.floor(boundary/grid)*grid, 0, 0));
        majorGridLineGeometry.vertices.push(new THREE.Vector3(Math.ceil(boundary/grid)*grid, 0, 0));

        var x,y,line;
        for (x = -Math.floor(boundary/grid); x <= Math.ceil(boundary/grid); ++x) {
          if ((x % 10 === 0) && (x !== 0)) {
            line = new THREE.Line(majorGridLineGeometry, majorMaterialInside);
            line.position.x = x*grid;
            line.rotation.z = 90 * Math.PI / 180;
            this.sceneObject.add(line);
          }
        }

        for (y = -Math.floor(boundary/grid); y <= Math.ceil(boundary/grid); ++y) {
          if ((y % 10 === 0) && (y !== 0)) {
            line = new THREE.Line(majorGridLineGeometry, majorMaterialInside);
            line.position.y = y*grid;
            this.sceneObject.add(line);
          }
        }

        if (geometryGraph.isEditing()) {
          var minorGridLineGeometry = new THREE.Geometry();
          var minorMaterialInside = new THREE.LineBasicMaterial({
            color: colors.workplane.minorGridLine,
            opacity: 0.1,
            transparent: true
          });

          minorGridLineGeometry.vertices.push(new THREE.Vector3(-Math.floor(boundary/grid)*grid, 0, 0));
          minorGridLineGeometry.vertices.push(new THREE.Vector3(Math.ceil(boundary/grid)*grid, 0, 0));

          for (x = -Math.floor(boundary/grid); x <= Math.ceil(boundary/grid); ++x) {
            if (x % 10 !== 0) {
              line = new THREE.Line(minorGridLineGeometry, minorMaterialInside);
              line.position.x = x*grid;
              line.rotation.z = 90 * Math.PI / 180;
              this.sceneObject.add(line);
            }
          }

          for (y = -Math.floor(boundary/grid); y <= Math.ceil(boundary/grid); ++y) {
            if (y % 10 !== 0) {
              line = new THREE.Line(minorGridLineGeometry, minorMaterialInside);
              line.position.y = y*grid;
              this.sceneObject.add(line);
            }
          }
        }

        this.addAxes();

        var quaternion = new THREE.Quaternion();
        var axis = calc.objToVector(
            this.model.vertex.workplane.axis,
            geometryGraph,
            THREE.Vector3);
        var angle = geometryGraph.evaluate(
          this.model.vertex.workplane.angle)/180*Math.PI;

        quaternion.setFromAxisAngle(axis, angle);
        this.sceneObject.useQuaternion = true;
        this.sceneObject.quaternion = quaternion;

        this.sceneObject.position =
          calc.objToVector(
            this.model.vertex.workplane.origin,
            geometryGraph,
            THREE.Vector3);

      },

      addAxes: function() {

        var axes = [new THREE.Geometry(), new THREE.Geometry(), new THREE.Geometry(),
                    new THREE.Geometry(), new THREE.Geometry(), new THREE.Geometry()];
        axes[0].vertices.push(new THREE.Vector3(0, 0, 0));
        axes[0].vertices.push(new THREE.Vector3(5000, 0, 0));

        axes[1].vertices.push(new THREE.Vector3(0, 0, 0));
        axes[1].vertices.push(new THREE.Vector3(0, 5000, 0));

        axes[2].vertices.push(new THREE.Vector3(0, 0, 0));
        axes[2].vertices.push(new THREE.Vector3(0, 0, 5000));

        axes[3].vertices.push(new THREE.Vector3(0, 0, 0));
        axes[3].vertices.push(new THREE.Vector3(-5000, 0, 0));

        axes[4].vertices.push(new THREE.Vector3(0, 0, 0));
        axes[4].vertices.push(new THREE.Vector3(0, -5000, 0));

        axes[5].vertices.push(new THREE.Vector3(0, 0, 0));
        axes[5].vertices.push(new THREE.Vector3(0, 0, -5000));

        this.sceneObject.add(new THREE.Line(axes[0],
            new THREE.LineBasicMaterial({ color: 0x0000ff })));
        this.sceneObject.add(new THREE.Line(axes[1],
            new THREE.LineBasicMaterial({ color: 0x00ff00 })));
        this.sceneObject.add(new THREE.Line(axes[2],
            new THREE.LineBasicMaterial({ color: 0xff0000 })));
        this.sceneObject.add(new THREE.Line(axes[3],
            new THREE.LineBasicMaterial({ color: 0x6666cc })));
        this.sceneObject.add(new THREE.Line(axes[4],
            new THREE.LineBasicMaterial({ color: 0x66cc66 })));
        this.sceneObject.add(new THREE.Line(axes[5],
            new THREE.LineBasicMaterial({ color: 0xcc6666 })));

      },

    });

    return {
      EditingModel: EditingModel,
      DisplayModel: DisplayModel,
    };

  });


text:
/**
 * The FormParser will parse a form XML document to create
 * a fully populated IFormComponent into a container composite
 */
qx.Class.define("qookery.internal.FormParser", {

	extend: qx.core.Object,
	implement: [ qookery.IFormParser ],

	statics: {

		__REGISTRY: qookery.internal.Registry.getInstance()
	},

	construct: function(variables, serviceResolver) {
		this.base(arguments);
		if(qx.core.Environment.get("qx.debug")) {
			this.assertMap(variables);
			this.assertFunction(serviceResolver);
		}
		this.__variables = variables;
		this.__serviceResolver = serviceResolver;
	},

	members: {

		__variables: null,
		__serviceResolver: null,

		// IFormParser implementation

		parseXmlDocument: function(xmlDocument, parentComponent) {
			if(xmlDocument == null)
				throw new Error("An XML form must be supplied");
			var component = this.__parseStatementBlock(xmlDocument, parentComponent);
			if(component == null)
				throw new Error("No Qookery component found within XML document");
			return component;
		},

		// Internal methods

		__parseStatementBlock: function(blockElement, component) {
			if(!qx.dom.Element.hasChildren(blockElement)) return null;
			var selectionMade = false;
			return qx.dom.Hierarchy.getChildElements(blockElement).reduce(function(previousResult, statementElement) {
				var elementQName = qx.dom.Node.getName(statementElement);
				if(elementQName === "parsererror")
					throw new Error(qx.lang.String.format("Parser error in statement block: %1", [ qx.dom.Node.getText(statementElement) ]));

				var namespaces = qookery.util.Xml.getNamespaceDeclarations(statementElement);
				elementQName = qx.dom.Node.getName(statementElement);
				var elementName = qookery.util.Xml.resolveQName(function(prefix) {
					if(namespaces != null) {
						var namespaceUri = namespaces[prefix];
						if(namespaceUri != null)
							return namespaceUri;
					}
					if(component != null) {
						return component.resolveNamespacePrefix(prefix);
					}
					return null;
				}, elementQName);

				// First consult the component registry
				if(this.constructor.__REGISTRY.isComponentTypeAvailable(elementName)) {
					return this.__parseComponent(statementElement, component, elementName, namespaces);
				}

				// Assert that we are within the context of a component
				if(component == null)
					throw new Error("Flow control and other non-component statements must appear with the context of a component");

				// Then check a number of special elements known by parser
				switch(elementName) {
				case "{http://www.qookery.org/ns/Form}else":
					if(selectionMade)
						return previousResult;
					/* fall through */
				case "{http://www.qookery.org/ns/Form}if":
					selectionMade = this.__parseIfElse(statementElement, component);
					return previousResult;
				case "{http://www.qookery.org/ns/Form}for-each":
					this.__parseForEach(statementElement, component);
					return previousResult;
				case "{http://www.qookery.org/ns/Form}script":
					this.__parseScript(statementElement, component);
					return previousResult;
				case "{http://www.qookery.org/ns/Form}switch":
					this.__parseSwitch(statementElement, component);
					return previousResult;
				case "{http://www.w3.org/2001/XInclude}include":
					this.__parseXInclude(statementElement, component);
					return previousResult;
				}

				// Lastly, attempt to delegate element parsing to current component
				if(component.parseXmlElement(elementName, statementElement))
					return previousResult;

				// Tough luck with this element, interrupt parser progress here
				throw new Error(qx.lang.String.format("Unexpected element '%1' encountered in statement block", [ elementName ]));
			}.bind(this), null);
		},

		__parseComponent: function(componentElement, parentComponent, componentName, namespaces) {
			// Instantiate and initialize new component

			var component = this.constructor.__REGISTRY.createComponent(componentName, parentComponent);
			try {
				// Set component attributes

				var componentId = qookery.util.Xml.getAttribute(componentElement, "id");
				if(componentId != null)
					component.setAttribute(qookery.IComponent.A_ID, componentId);
				if(namespaces != null)
					component.setAttribute(qookery.IComponent.A_NAMESPACES, namespaces);

				// Additional attributes applicable exclusively to forms

				if(qx.Class.implementsInterface(component.constructor, qookery.IFormComponent)) {
					component.setAttribute(qookery.IFormComponent.A_SERVICE_RESOLVER, this.__serviceResolver);
					component.setAttribute(qookery.IFormComponent.A_VARIABLES, this.__variables);
					var translationPrefix = qookery.util.Xml.getAttribute(componentElement, "translation-prefix") || componentId;
					if(translationPrefix != null)
						component.setAttribute(qookery.IFormComponent.A_TRANSLATION_PREFIX, translationPrefix);
				}

				// Register component into its form

				if(componentId != null && parentComponent != null)
					parentComponent.getForm().putComponent(componentId, component);

				// Attribute parsing

				var attributes = qookery.util.Xml.parseAllAttributes(component, componentElement);
				var useAttributes = qookery.util.Xml.getAttribute(componentElement, "use-attributes");
				if(useAttributes != null) useAttributes.split(/\s+/).forEach(function(variableName) {
					var useAttributes = component.getForm().getVariable(variableName);
					if(!qx.lang.Type.isObject(useAttributes))
						throw new Error("Variable specified in use-attributes not found or of incorrect type");
					qx.lang.Object.mergeWith(attributes, useAttributes);
				});

				// Component creation

				component.create(attributes);

				// Children parsing

				this.__parseStatementBlock(componentElement, component);

				// Component setup

				component.setup();

				// Attach to container

				if(parentComponent != null) {
					var display = qookery.util.Xml.getAttribute(componentElement, "display", "inline");
					switch(display) {
					case "inline":
						if(!qx.Class.hasInterface(parentComponent.constructor, qookery.IContainerComponent))
							throw new Error("Attempted to add a component to a non-container component");
						parentComponent.add(component);
						break;
					case "none":
						// Do nothing
						break;
					default:
						throw new Error("Unsupported display attribute value");
					}
				}

				// Return new component
				var c = component;
				component = null;
				return c;
			}
			finally {
				// Prevent memory leaks in case component creation failed midway
				if(component != null)
					component.dispose();
			}
		},

		__parseXInclude: function(xIncludeElement, parentComponent) {
			var formUrl = qookery.util.Xml.getAttribute(xIncludeElement, "href", Error);
			formUrl = qookery.util.Xml.parseValue(parentComponent, "ReplaceableString", formUrl);
			var xmlString = qookery.Qookery.getService("qookery.IResourceLoader", true).loadResource(formUrl);
			var xmlDocument = qx.xml.Document.fromString(xmlString);
			var formParser = new qookery.internal.FormParser(this.__variables, this.__serviceResolver);
			try {
				var component = formParser.parseXmlDocument(xmlDocument, parentComponent);
				var xmlIdAttribute = xIncludeElement.attributes["xml:id"];
				if(xmlIdAttribute != null)
					parentComponent.getForm().putComponent(xmlIdAttribute.value, component);
				return component;
			}
			catch(e) {
				this.error("Error creating form editor", e);
			}
			finally {
				formParser.dispose();
			}
		},

		__parseForEach: function(forEachElement, component) {
			var expression = qookery.util.Xml.getAttribute(forEachElement, "expression");
			if(expression == null)
				throw new Error("For-each expression is required");
			var result = component.evaluateExpression(expression);
			if(result == null)
				return;
			var scriptingContext = component.getForm().getScriptingContext();
			var keyVariable = qookery.util.Xml.getAttribute(forEachElement, "key-variable");
			var valueVariable = qookery.util.Xml.getAttribute(forEachElement, "value-variable");
			if(qx.lang.Type.isArray(result)) {
				for(var i = 0; i < result.length; i++) {
					if(keyVariable != null)
						scriptingContext[keyVariable] = i;
					if(valueVariable != null)
						scriptingContext[valueVariable] = result[i];
					this.__parseStatementBlock(forEachElement, component);
				}
			}
			else if(qx.lang.Type.isObject(result)) {
				for(var key in result) {
					if(keyVariable != null)
						scriptingContext[keyVariable] = key;
					if(valueVariable != null)
						scriptingContext[valueVariable] = result[key];
					this.__parseStatementBlock(forEachElement, component);
				}
			}
			else throw new Error("For-each expression must evaluate to a map or array");
		},

		__parseIfElse: function(selectionElement, component) {
			var expression = qookery.util.Xml.getAttribute(selectionElement, "expression");
			if(expression != null) {
				var result = component.evaluateExpression(expression);
				if(!result)
					return false;
			}
			var mediaQuery = qookery.util.Xml.getAttribute(selectionElement, "media-query");
			if(mediaQuery != null) {
				var query = this.__getMediaQuery(mediaQuery);
				if(!query.isMatching())
					return false;
			}
			var language = qookery.util.Xml.getAttribute(selectionElement, "{http://www.w3.org/XML/1998/namespace}lang");
			if(language != null) {
				if(qx.locale.Manager.getInstance().getLanguage() != language)
					return false;
			}
			this.__parseStatementBlock(selectionElement, component);
			return true;
		},

		__parseScript: function(scriptElement, component) {
			// Load source code
			var sourceCode = qookery.util.Xml.getNodeText(scriptElement);
			var scriptUrl = qookery.util.Xml.getAttribute(scriptElement, "source");
			if(scriptUrl != null)
				sourceCode = qookery.Qookery.getService("qookery.IResourceLoader", true).loadResource(scriptUrl);
			if(sourceCode == null)
				throw new Error("Empty <script> element");

			// Compile script function
			var functionConstructorArgs = [ "$" ];
			var argumentNames = qookery.util.Xml.getAttribute(scriptElement, "arguments");
			if(argumentNames != null) {
				Array.prototype.push.apply(functionConstructorArgs, argumentNames.split(/\s+/));
			}
			else if(qookery.util.Xml.getAttribute(scriptElement, "event") != null) {
				// For backward compatibility, add the implied "event" argument
				functionConstructorArgs.push("event");
			}
			functionConstructorArgs.push(sourceCode);
			var scriptFunction; try {
				scriptFunction = Function.apply(null, functionConstructorArgs);
			}
			catch(e) {
				throw new Error("Error compiling script '" + sourceCode.truncate(50) + "': " + e.message);
			}

			// Preload some XML attributes
			var actionNames = qookery.util.Xml.getAttribute(scriptElement, "action");
			var functionNames = qookery.util.Xml.getAttribute(scriptElement, "name");
			var eventNames = qookery.util.Xml.getAttribute(scriptElement, "event");
			var mediaQuery = qookery.util.Xml.getAttribute(scriptElement, "media-query");
			var onlyOnce = qookery.util.Xml.getAttribute(scriptElement, "once") === "true";
			var preventRecursion = qookery.util.Xml.getAttribute(scriptElement, "recursion") === "prevent";
			var debounceMillis = parseInt(qookery.util.Xml.getAttribute(scriptElement, "debounce"), 10) || 0;
			var execute = qookery.util.Xml.getAttribute(scriptElement, "execute") === "true";
			if(!execute && (actionNames == null && functionNames == null && eventNames == null && mediaQuery == null)) execute = true;

			// Create list of target components
			var componentIds = qookery.util.Xml.getAttribute(scriptElement, "component");
			var components = componentIds == null ? [ component ] :
				componentIds.split(/\s+/).map(function(componentId) {
					return component.getForm().getComponent(componentId, true);
				});

			// Apply requested operations to all target components
			components.forEach(function(component) {
				var componentFunction = function() {
					if(component.isDisposed()) return;
					if(preventRecursion && componentFunction.__isRunning === true) return;
					var scriptArguments = Array.prototype.slice.call(arguments);
					scriptArguments.unshift(component.getForm().getScriptingContext());
					try {
						componentFunction.__isRunning = true;
						return scriptFunction.apply(component, scriptArguments);
					}
					catch(error) {
						qookery.util.Debug.logScriptError(component, scriptFunction.toString(), error);
						throw error;
					}
					finally {
						componentFunction.__isRunning = false;
					}
				};
				if(debounceMillis > 0) {
					var debounceFunction = componentFunction;
					componentFunction = function() {
						var timerId = debounceFunction.__timerId;
						if(timerId != null) {
							debounceFunction.__timerId = null;
							clearTimeout(timerId);
						}
						var bindArguments = [ this ];
						Array.prototype.push.apply(bindArguments, arguments);
						var setTimoutFunction = Function.prototype.bind.apply(debounceFunction, bindArguments);
						debounceFunction.__timerId = setTimeout(setTimoutFunction, debounceMillis);
					};
				}
				if(mediaQuery != null) {
					var query = this.__getMediaQuery(mediaQuery);
					if(!(execute && onlyOnce)) {
						var methodName = onlyOnce ? "addListenerOnce" : "addListener";
						var listenerId = query[methodName]("change", function(data) {
							componentFunction(data["matches"], data["query"]);
						});
						component.addToDisposeList({ dispose: function() {
							query.removeListenerById(listenerId);
						} });
					}
					if(execute) componentFunction(query.isMatching(), mediaQuery);
				}
				else {
					if(functionNames != null) functionNames.split(/\s+/).forEach(function(functionName) {
						component.getForm().getScriptingContext()[functionName] = componentFunction;
					});
					if(actionNames != null) actionNames.split(/\s+/).forEach(function(actionName) {
						component.setAction(actionName, componentFunction);
					});
					if(eventNames != null) eventNames.split(/\s+/).forEach(function(eventName) {
						// Event handlers are wrapped into try-catch blocks in order to ensure subsequent handlers will be called
						component.addEventHandler(eventName, function(varargs) {
							try {
								componentFunction.apply(component, arguments);
							}
							catch(error) {
								qx.log.Logger.error(component, "Event handler ", eventName, " error:", error);
							}
						}, onlyOnce);
					});
					if(execute) componentFunction();
				}
			}, this);
		},

		__parseSwitch: function(switchElement, component) {
			if(!qx.dom.Element.hasChildren(switchElement)) return;
			var switchExpression = qookery.util.Xml.getAttribute(switchElement, "expression", Error);
			var switchResult = component.evaluateExpression(switchExpression);
			var children = qx.dom.Hierarchy.getChildElements(switchElement);
			for(var i = 0; i < children.length; i++) {
				var caseElement = children[i];
				var elementName = qx.dom.Node.getName(caseElement);
				if(elementName !== "case")
					throw new Error(qx.lang.String.format("Unexpected element in switch block: %1", [ qx.dom.Node.getText(switchElement) ]));
				var caseExpression = qookery.util.Xml.getAttribute(caseElement, "expression");
				if(caseExpression != null) {
					var caseResult = component.evaluateExpression(caseExpression);
					if(caseResult != switchResult) continue;
				}
				this.__parseStatementBlock(caseElement, component);
				return true;
			}
			return false;
		},

		__getMediaQuery: function(mediaQuery) {
			var query = this.constructor.__REGISTRY.getMediaQuery(mediaQuery);
			if(query != null)
				return query;
			return new qx.bom.MediaQuery(mediaQuery);
		}
	}
});


text:
package com.yang.dsl.calculator;

import com.yang.dsl.singleline.ExpressionLexer;
import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangyongli on 10/10/16.
 */
public class MyCalculatorVisitor extends AbstractParseTreeVisitor<BigDecimal> implements CalculatorVisitor<BigDecimal> {
    Map<String, BigDecimal> memory = new HashMap<String, BigDecimal>();

    /**
     * Visit a parse tree produced by {@link CalculatorParser#root}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitRoot(CalculatorParser.RootContext ctx) {
        return visitChildren(ctx);
    }

    /**
     * Visit a parse tree produced by the {@code assignVariable}
     * labeled alternative in {@link CalculatorParser#assign}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitAssignVariable(CalculatorParser.AssignVariableContext ctx) {
        CalculatorParser.VariableContext variable = ctx.variable();
        String variableText = variable.getText();
        CalculatorParser.ExpressionContext expression = ctx.expression();
        BigDecimal value = visit(expression);
        memory.put(variableText, value);
        return null;
    }

    /**
     * Visit a parse tree produced by the {@code singlePlusOrMinus}
     * labeled alternative in {@link CalculatorParser#expression}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitSinglePlusOrMinus(CalculatorParser.SinglePlusOrMinusContext ctx) {
        return visitChildren(ctx);
    }

    /**
     * Visit a parse tree produced by the {@code plusOrMinus}
     * labeled alternative in {@link CalculatorParser#expression}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitPlusOrMinus(CalculatorParser.PlusOrMinusContext ctx) {
        BigDecimal leftValue = visit(ctx.left);
        BigDecimal rightValue = visit(ctx.right);
        if (ctx.op.getType() == CalculatorLexer.PLUS) {
            return leftValue.add(rightValue);
        } else {
            return leftValue.subtract(rightValue);
        }
    }

    /**
     * Visit a parse tree produced by the {@code singleTimesOrDiv}
     * labeled alternative in {@link CalculatorParser#multiplyingExpression}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitSingleTimesOrDiv(CalculatorParser.SingleTimesOrDivContext ctx) {
        return visitChildren(ctx);
    }

    /**
     * Visit a parse tree produced by the {@code timesOrDiv}
     * labeled alternative in {@link CalculatorParser#multiplyingExpression}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitTimesOrDiv(CalculatorParser.TimesOrDivContext ctx) {
        BigDecimal leftValue = visit(ctx.left);
        BigDecimal rightValue = visit(ctx.right);
        if(ctx.op.getType() == CalculatorLexer.TIMES){
            return leftValue.multiply(rightValue);
        }else{
            return leftValue.divide(rightValue);
        }
    }

    /**
     * Visit a parse tree produced by the {@code atomNumber}
     * labeled alternative in {@link CalculatorParser#atomExpression}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitAtomNumber(CalculatorParser.AtomNumberContext ctx) {
        String text = ctx.getText();
        return new BigDecimal(text);
    }

    /**
     * Visit a parse tree produced by the {@code atomVariable}
     * labeled alternative in {@link CalculatorParser#atomExpression}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitAtomVariable(CalculatorParser.AtomVariableContext ctx) {
        CalculatorParser.VariableContext variable = ctx.variable();
        return visit(variable);
    }

    /**
     * Visit a parse tree produced by the {@code paren}
     * labeled alternative in {@link CalculatorParser#atomExpression}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitParen(CalculatorParser.ParenContext ctx) {
        return visit(ctx.expression());
    }

    /**
     * Visit a parse tree produced by the {@code atomFunction}
     * labeled alternative in {@link CalculatorParser#atomExpression}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitAtomFunction(CalculatorParser.AtomFunctionContext ctx) {
        CalculatorParser.FuncExpressionContext funcExpressionContext = ctx.funcExpression();
        return visit(funcExpressionContext);
    }

    /**
     * Visit a parse tree produced by {@link CalculatorParser#funcExpression}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitFuncExpression(CalculatorParser.FuncExpressionContext ctx) {
        CalculatorParser.FuncnameContext funcname = ctx.funcname();
        String funcnameText = funcname.getText();
        if (funcnameText.equals("SUM")) {
            BigDecimal sum = BigDecimal.ZERO;
            List<CalculatorParser.ExpressionContext> expressionList = ctx.expression();
            for (CalculatorParser.ExpressionContext expressionContext : expressionList) {
                BigDecimal decimal = visit(expressionContext);
                sum = sum.add(decimal);
            }
            return sum;
        }
        return BigDecimal.ZERO;
    }

    /**
     * Visit a parse tree produced by {@link CalculatorParser#funcname}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitFuncname(CalculatorParser.FuncnameContext ctx) {
        return null;
    }

    /**
     * Visit a parse tree produced by {@link CalculatorParser#number}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitNumber(CalculatorParser.NumberContext ctx) {
        String text = ctx.getText();
        return new BigDecimal(text);
    }

    /**
     * Visit a parse tree produced by {@link CalculatorParser#variable}.
     *
     * @param ctx the parse tree
     * @return the visitor result
     */
    public BigDecimal visitVariable(CalculatorParser.VariableContext ctx) {
        if (memory.containsKey(ctx.getText())) {
            return memory.get(ctx.getText());
        }
        //TODO throw exception
        return BigDecimal.ZERO;
    }
}


text:
package com.gtcgroup.justify.jpa.rule;

import java.util.HashMap;
import java.util.Map;

import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.junit.Rule;
import org.junit.jupiter.api.Test;

import com.gtcgroup.justify.core.rulechain.JstRuleChain;
import com.gtcgroup.justify.jpa.de.dependency.NoteDE;
import com.gtcgroup.justify.jpa.extension.JstConfigureJpaExtension;
import com.gtcgroup.justify.jpa.helper.dependency.ConstantsTestJPA;
import com.gtcgroup.justify.jpa.po.JstFindJpaPO;
import com.gtcgroup.justify.jpa.populator.dependency.NoteAdditionalDataPopulator;
import com.gtcgroup.justify.jpa.populator.dependency.NoteDataPopulator;
import com.gtcgroup.justify.jpa.rm.JstFindJpaRM;

/**
 * Test Class
 *
 *

 * Copyright (c) 2006 - 2017 by Global Technology Consulting Group, Inc. at
 * gtcGroup.com .
 *

 *
 * @author Marvin Toll
 * @since v3.0
 */
@SuppressWarnings("all")
public class JstConfigureJpaRuleTest {

    private static final Map<String, Object> PERSISTENCE_PROPERTY_ADDITIONAL_MAP = new HashMap<>();

    static {
        JstConfigureJpaRuleTest.PERSISTENCE_PROPERTY_ADDITIONAL_MAP.put(PersistenceUnitProperties.JDBC_URL,
            "jdbc:h2:mem:justify-additional;MODE=MSSQLServer");
        JstConfigureJpaRuleTest.PERSISTENCE_PROPERTY_ADDITIONAL_MAP.put(PersistenceUnitProperties.JDBC_USER, "additional");
        JstConfigureJpaRuleTest.PERSISTENCE_PROPERTY_ADDITIONAL_MAP.put(PersistenceUnitProperties.JDBC_PASSWORD,
            "additional");
    }

    private static final Map<String, Object> PERSISTENCE_PROPERTY_MAP2 = new HashMap<>();

    static {

        JstConfigureJpaRuleTest.PERSISTENCE_PROPERTY_MAP2.put("key", "value");
    }

    @Rule
    public JstRuleChain ruleChain = JstRuleChain.outerRule(false)
        .around(JstConfigureJpaExtension
            .withPersistenceUnit(ConstantsTestJPA.JUSTIFY_PU, JstConfigureJpaRuleTest.PERSISTENCE_PROPERTY_ADDITIONAL_MAP)
            .withDataPopulators(
                NoteDataPopulator.class, NoteDataPopulator.class, NoteAdditionalDataPopulator.class))
        .around(JstConfigureJpaExtension
            .withPersistenceUnit(ConstantsTestJPA.JUSTIFY_PU, JstConfigureJpaRuleTest.PERSISTENCE_PROPERTY_MAP2)
            .withDataPopulators(
                NoteDataPopulator.class, NoteDataPopulator.class, NoteAdditionalDataPopulator.class))
        .around(JstConfigureJpaExtension.withPersistenceUnit(ConstantsTestJPA.JUSTIFY_SECOND_PU)
            .withDataPopulators(NoteDataPopulator.class, NoteDataPopulator.class, NoteAdditionalDataPopulator.class))
        .around(JstConfigureJpaExtension
            .withPersistenceUnit(ConstantsTestJPA.JUSTIFY_PU)
            .withDataPopulators(
                NoteDataPopulator.class, NoteDataPopulator.class, NoteAdditionalDataPopulator.class));

    @Test
    public void testForPopulator_additional() {

        JstFindJpaRM.findSingle(JstFindJpaPO.withFind(false)
            .withPersistenceUnitName(ConstantsTestJPA.JUSTIFY_PU)
            .withEntityClass(NoteDE.class)
            .withEntityIdentity(NoteAdditionalDataPopulator.ADDITIONAL_UUID)
            .withPersistencePropertyMap(PERSISTENCE_PROPERTY_ADDITIONAL_MAP));
    }

    @Test
    public void testForPopulator_note_readonly() {

        JstFindJpaRM.findSingle(JstFindJpaPO.withFind(false)
            .withPersistenceUnitName(ConstantsTestJPA.JUSTIFY_PU)
            .withEntityClass(NoteDE.class)
            .withEntityIdentity(ConstantsTestJPA.NOTE_UUID_TWO));
    }
}


text:
/**
 * @file hightlight.js
 * @author Lu Yuan(luyuan.china@gmail.com)
 */

let getTextNodes = function (node) {
    let textNodes = [];
    if (node.nodeType === Node.TEXT_NODE) {
        textNodes.push(node);
    }
    else {
        let children = node.childNodes;
        for (let i = 0, len = children.length; i < len; ++i) {
            textNodes.push.apply(textNodes, getTextNodes(children[i]));
        }
    }
    return textNodes;
};

let setSelectionRange = function (el, start, end) {
    if (document.createRange && window.getSelection) {
        let range = document.createRange();
        range.selectNodeContents(el);
        let textNodes = getTextNodes(el);
        let foundStart = false;
        let charCount = 0;
        let endCharCount;

        for (let i = 0, textNode; textNode = textNodes[i++];) {
            endCharCount = charCount + textNode.length;
            if (!foundStart && start >= charCount && (start < endCharCount
                || (start === endCharCount && i <= textNodes.length))) {
                range.setStart(textNode, start - charCount);
                foundStart = true;
            }
            if (foundStart && end <= endCharCount) {
                range.setEnd(textNode, end - charCount);
                break;
            }
            charCount = endCharCount;
        }

        let sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
    else if (document.selection && document.body.createTextRange) {
        let textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(true);
        textRange.moveEnd('character', end);
        textRange.moveStart('character', start);
        textRange.select();
    }
};

let makeEditableAndHighlight = function (backColor, foreColor) {
    let sel = window.getSelection();
    let range;
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = 'on';
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    if (!document.execCommand('HiliteColor', false, backColor)) {
        document.execCommand('BackColor', false, backColor);
    }
    document.execCommand('ForeColor', false, foreColor);
    document.designMode = 'off';
    sel.removeAllRanges();
};

let makeEditableAndUnhighlight = function () {
    let sel = window.getSelection();
    let range;
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = 'on';
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    document.execCommand('removeFormat', false);
    document.designMode = 'off';
    if (range && range.startContainer && (range.startContainer instanceof HTMLElement)) {
        range.startContainer.normalize();
    }
    sel.removeAllRanges();
};

let doHighlight = function (backColor, foreColor) {
    let range;
    if (window.getSelection) {
        try {
            if (!document.execCommand('BackColor', false, backColor)) {
                makeEditableAndHighlight(backColor, foreColor);
            }
        }
        catch (ex) {
            makeEditableAndHighlight(backColor, foreColor);
        }
    }
    else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.execCommand('BackColor', false, backColor);
    }
};

let doUnhighlight = function () {
    let range;
    if (window.getSelection) {
        try {
            if (!document.execCommand('BackColor', false)) {
                makeEditableAndUnhighlight();
            }
        }
        catch (ex) {
            makeEditableAndUnhighlight();
        }
    }
    else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.execCommand('removeFormat', false);
    }
};

let highlightFunc = function (el, keyword, input, backColor, foreColor) {
    if (!el || !el.innerText || !keyword) {
        return;
    }
    let text = el.innerText.toLowerCase();
    keyword = keyword.toLowerCase();

    let len = keyword.length;
    let start = text.indexOf(keyword);
    while (start > -1) {
        let end = start + len;
        setSelectionRange(el, start, end);
        doHighlight(backColor, foreColor);
        start = text.indexOf(keyword, start + 1);
    }
    input && input.focus();
};

let unhighlightFunc = function (el, input) {
    if (!el || !el.innerText) {
        return;
    }
    setSelectionRange(el, 0, el.innerText.length);
    doUnhighlight();
    input && input.focus();
};

export const Highlight = {
    highlight: highlightFunc,
    unhighlight: unhighlightFunc
};


text:
package org.openkoala.organisation.core;

public class OrganizationHasEmployee extends OrganisationException {

	private static final long serialVersionUID = 2813449496205272197L;

	public OrganizationHasEmployee() {
	}

	public OrganizationHasEmployee(String message) {
		super(message);
	}

	public OrganizationHasEmployee(Throwable cause) {
		super(cause);
	}

	public OrganizationHasEmployee(String message,
			Throwable cause) {
		super(message, cause);
	}

}


text:
Given two strings `s` and `p`, return an array of all the start indices of `p`'s anagrams in `s`. You may return the answer in **any order**.

An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

### Example 1:

```
Input:
s: "cbaebabacd" p: "abc"

Output:
[0, 6]

Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
```

### Example 2:

```
Input:
s: "abab" p: "ab"

Output:
[0, 1, 2]

Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
```

### Constraints:

- `1 <= s.length, p.length <= 3 * 10^4`
- `s` and `p` consist of lowercase English letters.

## Solution

Create target p's signature which is a letter-to-occurence lookup array. We are now trying to cancel the occurence from the lookup when sliding the window.

## Template

There is [template](https://leetcode.com/problems/minimum-window-substring/discuss/26808/here-is-a-10-line-template-that-can-solve-most-substring-problems) for a few similar substring problem:

1. Use two pointers: start and end to represent a window.
2. Move end to find a valid window.
3. When a valid window is found, move start to find a smaller window.

#Hash Table

#FB #ORCL #GOOGL

#Similar Questions [#438](../p438m/README.md) [#567](../p567m/README.md)


text:
package org.apache.shindig.social.opensocial.jpa.spi;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.Inject;

import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.common.util.ImmediateFuture;
import org.apache.shindig.protocol.DataCollection;
import org.apache.shindig.protocol.ProtocolException;
import org.apache.shindig.social.opensocial.jpa.ApplicationDataMapDb;
import org.apache.shindig.social.opensocial.spi.AppDataService;
import org.apache.shindig.social.opensocial.spi.GroupId;
import org.apache.shindig.social.opensocial.spi.UserId;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;

import javax.persistence.EntityManager;

/**
 *
 */
public class AppDataServiceDb implements AppDataService {

  private EntityManager entityManager;

  @Inject
  public AppDataServiceDb(EntityManager entityManager) {
    this.entityManager = entityManager;
  }

  /**
   * {@inheritDoc}
   */
  public Future<Void> deletePersonData(UserId userId, GroupId groupId, String appId,
      Set<String> fields, SecurityToken token) throws ProtocolException {

    List<ApplicationDataMapDb> dataMaps = getDataMap(userId, groupId, appId, token);
    for (ApplicationDataMapDb adm : dataMaps) {
      for (String f : fields) {
        adm.getValues().remove(f);
      }
    }
     // TODO How should transactions be managed? Should samples be using warp-persist instead?
     if (!entityManager.getTransaction().isActive()) {
       entityManager.getTransaction().begin();
     }

    entityManager.flush();
    entityManager.getTransaction().commit();

    return ImmediateFuture.newInstance(null);
  }

  /**
   * @param userId
   * @param groupId
   * @param appId
   * @param token
   * @return
   */
  private List<ApplicationDataMapDb> getDataMap(UserId userId, GroupId groupId, String appId,
      SecurityToken token) {
    List<String> paramList = Lists.newArrayList();
    paramList.add(SPIUtils.getUserList(userId, token));
    int lastParam = 1;
    StringBuilder sb = new StringBuilder();

    switch (groupId.getType()) {
    case all:
      // userId translates into all contacts
      sb.append(ApplicationDataMapDb.FINDBY_ALL_GROUP);
      sb.append(" and am.personId = ?").append(lastParam);
      lastParam++;
      break;
    case deleted:
      // ignored
      break;
    case friends:
      sb.append(ApplicationDataMapDb.FINDBY_FRIENDS_GROUP);
      sb.append(" and am.personId = ?").append(lastParam);
      lastParam++;
      // userId translates into all friends
      break;
    case groupId:
      sb.append(ApplicationDataMapDb.FINDBY_GROUP_GROUP);
      sb.append(" and am.personId = ?").append(lastParam);
      lastParam++;
      sb.append(" and g.id = ?").append(lastParam);
      paramList.add(groupId.getGroupId());
      lastParam++;
      // userId translates into friends within a group
      break;
    default: // including self
      // userId is the user Id
      sb.append(ApplicationDataMapDb.FINDBY_SELF_GROUP);
      sb.append(" am.personId = ?").append(lastParam);
      lastParam++;
      break;

    }
    sb.append(" and am.application.id = ?").append(lastParam);
    lastParam++;
    paramList.add(appId);
    return JPQLUtils.getListQuery(entityManager, sb.toString(), paramList, null);

  }

  /**
   * {@inheritDoc}
   */
  public Future<DataCollection> getPersonData(Set<UserId> userIds, GroupId groupId, String appId,
      Set<String> fields, SecurityToken token) throws ProtocolException {
    List<String> paramList = SPIUtils.getUserList(userIds, token);
    int lastParam = 1;
    StringBuilder sb = new StringBuilder();

    switch (groupId.getType()) {
    case all:
      // userId translates into all contacts
      sb.append(ApplicationDataMapDb.FINDBY_ALL_GROUP);
      lastParam = JPQLUtils.addInClause(sb, "am", "personId", lastParam, paramList.size());
      break;
    case deleted:
      // ignored
      break;
    case friends:
      sb.append(ApplicationDataMapDb.FINDBY_FRIENDS_GROUP);
      lastParam = JPQLUtils.addInClause(sb, "p", "id", lastParam, paramList.size());
      sb.append(')');
      // userId translates into all friends
      break;
    case groupId:
      sb.append(ApplicationDataMapDb.FINDBY_GROUP_GROUP);
      lastParam = JPQLUtils.addInClause(sb, "am", "personId", lastParam, paramList.size());
      sb.append(" and g.id = ?").append(lastParam);
      paramList.add(groupId.getGroupId());
      lastParam++;
      // userId translates into friends within a group
      break;
    default: // including self
      // userId is the user Id
      sb.append(ApplicationDataMapDb.FINDBY_SELF_GROUP);
      lastParam = JPQLUtils.addInClause(sb, "am", "personId", lastParam, paramList.size());
      break;

    }
    sb.append(" and am.application.id = ?").append(lastParam);
    lastParam++;
    paramList.add(appId);

    // load the map up
    List<ApplicationDataMapDb> dataMaps = JPQLUtils.getListQuery(entityManager, sb.toString(),
        paramList, null);
    Map<String, Map<String, String>> results = new HashMap<String, Map<String, String>>();

    // only add in the fields
    if (fields == null || fields.isEmpty()) {
      for (ApplicationDataMapDb adm : dataMaps) {
        results.put(adm.getPersonId(), adm.getValues());
      }
    } else {
      for (ApplicationDataMapDb adm : dataMaps) {
        Map<String, String> m = Maps.newHashMap();
        for (String f : fields) {
          String value = adm.getValues().get(f);
          if (null != value) {
            m.put(f, value);
          }
        }
        results.put(adm.getPersonId(), m);
      }
    }
    DataCollection dc = new DataCollection(results);
    return ImmediateFuture.newInstance(dc);
  }

  /**
   * {@inheritDoc}
   */
  public Future<Void> updatePersonData(UserId userId, GroupId groupId, String appId,
      Set<String> fields, Map<String, String> values, SecurityToken token)
      throws ProtocolException {
    List<ApplicationDataMapDb> dataMaps = getDataMap(userId, groupId, appId, token);
    for (ApplicationDataMapDb adm : dataMaps) {
      for (String f : fields) {
        adm.getValues().put(f, values.get(f));
      }
    }

    // TODO How should transactions be managed? Should samples be using warp-persist instead?
    if (!entityManager.getTransaction().isActive()) {
      entityManager.getTransaction().begin();
    }
    entityManager.flush();
    entityManager.getTransaction().commit();

    return ImmediateFuture.newInstance(null);
  }

}


text:
import React from 'react';
import FormEdit, {ItemEdit, Column } from 'components/FormMobx';
import { mode, itemType } from 'components/FormMobx/utils';
import { observer, inject } from 'mobx-react';

@inject("categoryForm")
@observer
export default class CategoryForm extends React.Component {
	render() {
		const { categoryForm, onSubmit, mode } = this.props;
		return (
			<FormEdit
				mode={mode}
				title="Category Infomation"
				form={categoryForm}
				onSubmit={onSubmit}
			>
				<Column>
					<ItemEdit
						field={categoryForm.$('name')}
					/>
					<ItemEdit
						field={categoryForm.$('description')}
					/>
					<ItemEdit
						type={itemType.NUMBER}
						field={categoryForm.$('priceTypeI')}
					/>
					<ItemEdit
						type={itemType.NUMBER}
						field={categoryForm.$('priceTypeII')}
					/>
				</Column>
			</FormEdit>
		);
	}
};

CategoryForm.defaultProps = {
	onSubmit: () => {},
	mode: mode.VIEW,
};