text:
.class Landroid/hardware/Camera$EventHandler;
.super Landroid/os/Handler;
.source "Camera.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/hardware/Camera;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "EventHandler"
.end annotation

# instance fields
.field private mCamera:Landroid/hardware/Camera;

.field final synthetic this$0:Landroid/hardware/Camera;

# direct methods
.method public constructor <init>(Landroid/hardware/Camera;Landroid/hardware/Camera;Landroid/os/Looper;)V
    .locals 0
    .parameter
    .parameter "c"
    .parameter "looper"

    .prologue
    .line 780
    iput-object p1, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    .line 781
    invoke-direct {p0, p3}, Landroid/os/Handler;-><init>(Landroid/os/Looper;)V

    .line 782
    iput-object p2, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    .line 783
    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 7
    .parameter "msg"

    .prologue
    const/4 v3, 0x1

    const/4 v2, 0x0

    .line 787
    iget v4, p1, Landroid/os/Message;->what:I

    sparse-switch v4, :sswitch_data_0

    .line 874
    const-string v3, "Camera"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Unknown message type "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget v5, p1, Landroid/os/Message;->what:I

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 875
    :cond_0
    :goto_0
    return-void

    .line 789
    :sswitch_0
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mShutterCallback:Landroid/hardware/Camera$ShutterCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$000(Landroid/hardware/Camera;)Landroid/hardware/Camera$ShutterCallback;

    move-result-object v3

    if-eqz v3, :cond_0

    .line 790
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mShutterCallback:Landroid/hardware/Camera$ShutterCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$000(Landroid/hardware/Camera;)Landroid/hardware/Camera$ShutterCallback;

    move-result-object v3

    invoke-interface {v3}, Landroid/hardware/Camera$ShutterCallback;->onShutter()V

    goto :goto_0

    .line 795
    :sswitch_1
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mRawImageCallback:Landroid/hardware/Camera$PictureCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$100(Landroid/hardware/Camera;)Landroid/hardware/Camera$PictureCallback;

    move-result-object v3

    if-eqz v3, :cond_0

    .line 796
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mRawImageCallback:Landroid/hardware/Camera$PictureCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$100(Landroid/hardware/Camera;)Landroid/hardware/Camera$PictureCallback;

    move-result-object v4

    iget-object v3, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v3, [B

    check-cast v3, [B

    iget-object v5, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v4, v3, v5}, Landroid/hardware/Camera$PictureCallback;->onPictureTaken([BLandroid/hardware/Camera;)V

    goto :goto_0

    .line 801
    :sswitch_2
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mJpegCallback:Landroid/hardware/Camera$PictureCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$200(Landroid/hardware/Camera;)Landroid/hardware/Camera$PictureCallback;

    move-result-object v3

    if-eqz v3, :cond_0

    .line 802
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mJpegCallback:Landroid/hardware/Camera$PictureCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$200(Landroid/hardware/Camera;)Landroid/hardware/Camera$PictureCallback;

    move-result-object v4

    iget-object v3, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v3, [B

    check-cast v3, [B

    iget-object v5, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v4, v3, v5}, Landroid/hardware/Camera$PictureCallback;->onPictureTaken([BLandroid/hardware/Camera;)V

    goto :goto_0

    .line 807
    :sswitch_3
    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mPreviewCallback:Landroid/hardware/Camera$PreviewCallback;
    invoke-static {v4}, Landroid/hardware/Camera;->access$300(Landroid/hardware/Camera;)Landroid/hardware/Camera$PreviewCallback;

    move-result-object v1

    .line 808
    .local v1, pCb:Landroid/hardware/Camera$PreviewCallback;
    if-eqz v1, :cond_0

    .line 809
    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mOneShot:Z
    invoke-static {v4}, Landroid/hardware/Camera;->access$400(Landroid/hardware/Camera;)Z

    move-result v4

    if-eqz v4, :cond_2

    .line 813
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    const/4 v4, 0x0

    #setter for: Landroid/hardware/Camera;->mPreviewCallback:Landroid/hardware/Camera$PreviewCallback;
    invoke-static {v3, v4}, Landroid/hardware/Camera;->access$302(Landroid/hardware/Camera;Landroid/hardware/Camera$PreviewCallback;)Landroid/hardware/Camera$PreviewCallback;

    .line 820
    :cond_1
    :goto_1
    iget-object v3, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v3, [B

    check-cast v3, [B

    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v1, v3, v4}, Landroid/hardware/Camera$PreviewCallback;->onPreviewFrame([BLandroid/hardware/Camera;)V

    goto :goto_0

    .line 814
    :cond_2
    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mWithBuffer:Z
    invoke-static {v4}, Landroid/hardware/Camera;->access$500(Landroid/hardware/Camera;)Z

    move-result v4

    if-nez v4, :cond_1

    .line 818
    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #calls: Landroid/hardware/Camera;->setHasPreviewCallback(ZZ)V
    invoke-static {v4, v3, v2}, Landroid/hardware/Camera;->access$600(Landroid/hardware/Camera;ZZ)V

    goto :goto_1

    .line 825
    .end local v1           #pCb:Landroid/hardware/Camera$PreviewCallback;
    :sswitch_4
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mPostviewCallback:Landroid/hardware/Camera$PictureCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$700(Landroid/hardware/Camera;)Landroid/hardware/Camera$PictureCallback;

    move-result-object v3

    if-eqz v3, :cond_0

    .line 826
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mPostviewCallback:Landroid/hardware/Camera$PictureCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$700(Landroid/hardware/Camera;)Landroid/hardware/Camera$PictureCallback;

    move-result-object v4

    iget-object v3, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v3, [B

    check-cast v3, [B

    iget-object v5, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v4, v3, v5}, Landroid/hardware/Camera$PictureCallback;->onPictureTaken([BLandroid/hardware/Camera;)V

    goto/16 :goto_0

    .line 831
    :sswitch_5
    const/4 v0, 0x0

    .line 832
    .local v0, cb:Landroid/hardware/Camera$AutoFocusCallback;
    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mAutoFocusCallbackLock:Ljava/lang/Object;
    invoke-static {v4}, Landroid/hardware/Camera;->access$800(Landroid/hardware/Camera;)Ljava/lang/Object;

    move-result-object v4

    monitor-enter v4

    .line 833
    :try_start_0
    iget-object v5, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mAutoFocusCallback:Landroid/hardware/Camera$AutoFocusCallback;
    invoke-static {v5}, Landroid/hardware/Camera;->access$900(Landroid/hardware/Camera;)Landroid/hardware/Camera$AutoFocusCallback;

    move-result-object v0

    .line 834
    monitor-exit v4
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    .line 835
    if-eqz v0, :cond_0

    .line 836
    iget v4, p1, Landroid/os/Message;->arg1:I

    if-nez v4, :cond_3

    .line 837
    .local v2, success:Z
    :goto_2
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v0, v2, v3}, Landroid/hardware/Camera$AutoFocusCallback;->onAutoFocus(ZLandroid/hardware/Camera;)V

    goto/16 :goto_0

    .line 834
    .end local v2           #success:Z
    :catchall_0
    move-exception v3

    :try_start_1
    monitor-exit v4
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    throw v3

    :cond_3
    move v2, v3

    .line 836
    goto :goto_2

    .line 842
    .end local v0           #cb:Landroid/hardware/Camera$AutoFocusCallback;
    :sswitch_6
    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mZoomListener:Landroid/hardware/Camera$OnZoomChangeListener;
    invoke-static {v4}, Landroid/hardware/Camera;->access$1000(Landroid/hardware/Camera;)Landroid/hardware/Camera$OnZoomChangeListener;

    move-result-object v4

    if-eqz v4, :cond_0

    .line 843
    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mZoomListener:Landroid/hardware/Camera$OnZoomChangeListener;
    invoke-static {v4}, Landroid/hardware/Camera;->access$1000(Landroid/hardware/Camera;)Landroid/hardware/Camera$OnZoomChangeListener;

    move-result-object v4

    iget v5, p1, Landroid/os/Message;->arg1:I

    iget v6, p1, Landroid/os/Message;->arg2:I

    if-eqz v6, :cond_4

    :goto_3
    iget-object v6, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v4, v5, v3, v6}, Landroid/hardware/Camera$OnZoomChangeListener;->onZoomChange(IZLandroid/hardware/Camera;)V

    goto/16 :goto_0

    :cond_4
    move v3, v2

    goto :goto_3

    .line 848
    :sswitch_7
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mFaceListener:Landroid/hardware/Camera$FaceDetectionListener;
    invoke-static {v3}, Landroid/hardware/Camera;->access$1100(Landroid/hardware/Camera;)Landroid/hardware/Camera$FaceDetectionListener;

    move-result-object v3

    if-eqz v3, :cond_0

    .line 849
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mFaceListener:Landroid/hardware/Camera$FaceDetectionListener;
    invoke-static {v3}, Landroid/hardware/Camera;->access$1100(Landroid/hardware/Camera;)Landroid/hardware/Camera$FaceDetectionListener;

    move-result-object v4

    iget-object v3, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v3, [Landroid/hardware/Camera$Face;

    check-cast v3, [Landroid/hardware/Camera$Face;

    iget-object v5, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v4, v3, v5}, Landroid/hardware/Camera$FaceDetectionListener;->onFaceDetection([Landroid/hardware/Camera$Face;Landroid/hardware/Camera;)V

    goto/16 :goto_0

    .line 854
    :sswitch_8
    const-string v3, "Camera"

    new-instance v4, Ljava/lang/StringBuilder;

    invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V

    const-string v5, "Error "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget v5, p1, Landroid/os/Message;->arg1:I

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-static {v3, v4}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 855
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mErrorCallback:Landroid/hardware/Camera$ErrorCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$1200(Landroid/hardware/Camera;)Landroid/hardware/Camera$ErrorCallback;

    move-result-object v3

    if-eqz v3, :cond_0

    .line 856
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mErrorCallback:Landroid/hardware/Camera$ErrorCallback;
    invoke-static {v3}, Landroid/hardware/Camera;->access$1200(Landroid/hardware/Camera;)Landroid/hardware/Camera$ErrorCallback;

    move-result-object v3

    iget v4, p1, Landroid/os/Message;->arg1:I

    iget-object v5, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v3, v4, v5}, Landroid/hardware/Camera$ErrorCallback;->onError(ILandroid/hardware/Camera;)V

    goto/16 :goto_0

    .line 861
    :sswitch_9
    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mAutoFocusMoveCallback:Landroid/hardware/Camera$AutoFocusMoveCallback;
    invoke-static {v4}, Landroid/hardware/Camera;->access$1300(Landroid/hardware/Camera;)Landroid/hardware/Camera$AutoFocusMoveCallback;

    move-result-object v4

    if-eqz v4, :cond_0

    .line 862
    iget-object v4, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mAutoFocusMoveCallback:Landroid/hardware/Camera$AutoFocusMoveCallback;
    invoke-static {v4}, Landroid/hardware/Camera;->access$1300(Landroid/hardware/Camera;)Landroid/hardware/Camera$AutoFocusMoveCallback;

    move-result-object v4

    iget v5, p1, Landroid/os/Message;->arg1:I

    if-nez v5, :cond_5

    :goto_4
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v4, v2, v3}, Landroid/hardware/Camera$AutoFocusMoveCallback;->onAutoFocusMoving(ZLandroid/hardware/Camera;)V

    goto/16 :goto_0

    :cond_5
    move v2, v3

    goto :goto_4

    .line 867
    :sswitch_a
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mSceneListener:Landroid/hardware/Camera$SceneDetectionListener;
    invoke-static {v3}, Landroid/hardware/Camera;->access$1400(Landroid/hardware/Camera;)Landroid/hardware/Camera$SceneDetectionListener;

    move-result-object v3

    if-eqz v3, :cond_0

    .line 868
    iget-object v3, p0, Landroid/hardware/Camera$EventHandler;->this$0:Landroid/hardware/Camera;

    #getter for: Landroid/hardware/Camera;->mSceneListener:Landroid/hardware/Camera$SceneDetectionListener;
    invoke-static {v3}, Landroid/hardware/Camera;->access$1400(Landroid/hardware/Camera;)Landroid/hardware/Camera$SceneDetectionListener;

    move-result-object v4

    iget-object v3, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v3, Ljava/lang/String;

    iget-object v5, p0, Landroid/hardware/Camera$EventHandler;->mCamera:Landroid/hardware/Camera;

    invoke-interface {v4, v3, v5}, Landroid/hardware/Camera$SceneDetectionListener;->onSceneDetection(Ljava/lang/String;Landroid/hardware/Camera;)V

    goto/16 :goto_0

    .line 787
    nop

    :sswitch_data_0
    .sparse-switch
        0x1 -> :sswitch_8
        0x2 -> :sswitch_0
        0x4 -> :sswitch_5
        0x8 -> :sswitch_6
        0x10 -> :sswitch_3
        0x40 -> :sswitch_4
        0x80 -> :sswitch_1
        0x100 -> :sswitch_2
        0x400 -> :sswitch_7
        0x800 -> :sswitch_9
        0x1000 -> :sswitch_a
    .end sparse-switch
.end method


text:
package org.apache.geode.security;

import static org.apache.geode.security.SecurityTestUtils.*;
import static org.apache.geode.test.dunit.Assert.*;
import static org.apache.geode.test.dunit.IgnoredException.*;
import static org.apache.geode.test.dunit.LogWriterUtils.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.DeltaTestImpl;
import org.apache.geode.cache.operations.OperationContext.OperationCode;
import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.internal.cache.PartitionedRegionLocalMaxMemoryDUnitTest;
import org.apache.geode.security.generator.AuthzCredentialGenerator;
import org.apache.geode.security.generator.CredentialGenerator;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.FlakyTest;
import org.apache.geode.test.junit.categories.SecurityTest;

/**
 * @since GemFire 6.1
 */
@Category({DistributedTest.class, SecurityTest.class})
public class DeltaClientPostAuthorizationDUnitTest extends ClientAuthorizationTestCase {

  private static final int PAUSE = 5 * 1000; // TODO: replace with Awaitility

  private DeltaTestImpl[] deltas = new DeltaTestImpl[8];

  @Override
  public final void preSetUpClientAuthorizationTestBase() throws Exception {
    setUpDeltas();
    addIgnoredException("Unexpected IOException");
    addIgnoredException("SocketException");
  }

  @Override
  public final void preTearDownClientAuthorizationTestBase() throws Exception {
    closeCache();
  }

  @Category(FlakyTest.class) // GEODE-1502
  @Test
  public void testPutPostOpNotifications() throws Exception {
    OperationWithAction[] allOps = allOps();

    AuthzCredentialGenerator gen = this.getXmlAuthzGenerator();
    CredentialGenerator cGen = gen.getCredentialGenerator();
    Properties extraAuthProps = cGen.getSystemProperties();
    Properties javaProps = cGen.getJavaProperties();
    Properties extraAuthzProps = gen.getSystemProperties();
    String authenticator = cGen.getAuthenticator();
    String authInit = cGen.getAuthInit();
    String accessor = gen.getAuthorizationCallback();
    TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(gen);

    getLogWriter().info("testAllOpsNotifications: Using authinit: " + authInit);
    getLogWriter().info("testAllOpsNotifications: Using authenticator: " + authenticator);
    getLogWriter().info("testAllOpsNotifications: Using accessor: " + accessor);

    // Start servers with all required properties
    Properties serverProps =
        buildProperties(authenticator, accessor, true, extraAuthProps, extraAuthzProps);

    // Get ports for the servers
    int[] randomAvailableTCPPorts = AvailablePortHelper.getRandomAvailableTCPPorts(2);
    int port1 = randomAvailableTCPPorts[0];
    int port2 = randomAvailableTCPPorts[1];

    // Perform all the ops on the clients
    List opBlock = new ArrayList();
    Random rnd = new Random();

    for (int opNum = 0; opNum < allOps.length; ++opNum) {
      // Start client with valid credentials as specified in OperationWithAction
      OperationWithAction currentOp = allOps[opNum];
      if (currentOp.equals(OperationWithAction.OPBLOCK_END)
          || currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {

        // End of current operation block; execute all the operations on the servers with failover
        if (opBlock.size() > 0) {
          // Start the first server and execute the operation block
          server1.invoke(() -> ClientAuthorizationTestCase.createCacheServer(getLocatorPort(),
              port1, serverProps, javaProps));
          server2.invoke(() -> closeCache());

          executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps, extraAuthzProps, tgen,
              rnd);

          if (!currentOp.equals(OperationWithAction.OPBLOCK_NO_FAILOVER)) {
            // Failover to the second server and run the block again
            server2.invoke(() -> ClientAuthorizationTestCase.createCacheServer(getLocatorPort(),
                port2, serverProps, javaProps));
            server1.invoke(() -> closeCache());

            executeOpBlock(opBlock, port1, port2, authInit, extraAuthProps, extraAuthzProps, tgen,
                rnd);
          }

          opBlock.clear();
        }

      } else {
        currentOp.setOpNum(opNum);
        opBlock.add(currentOp);
      }
    }
  }

  @Override
  protected final void executeOpBlock(final List<OperationWithAction> opBlock, final int port1,
      final int port2, final String authInit, final Properties extraAuthProps,
      final Properties extraAuthzProps, final TestCredentialGenerator credentialGenerator,
      final Random random) throws InterruptedException {
    for (Iterator<OperationWithAction> opIter = opBlock.iterator(); opIter.hasNext();) {
      // Start client with valid credentials as specified in OperationWithAction
      OperationWithAction currentOp = opIter.next();
      OperationCode opCode = currentOp.getOperationCode();
      int opFlags = currentOp.getFlags();
      int clientNum = currentOp.getClientNum();
      VM clientVM = null;
      boolean useThisVM = false;

      switch (clientNum) {
        case 1:
          clientVM = client1;
          break;
        case 2:
          clientVM = client2;
          break;
        case 3:
          useThisVM = true;
          break;
        default:
          fail("executeOpBlock: Unknown client number " + clientNum);
          break;
      }

      getLogWriter().info("executeOpBlock: performing operation number [" + currentOp.getOpNum()
          + "]: " + currentOp);

      if ((opFlags & OpFlags.USE_OLDCONN) == 0) {
        Properties opCredentials;
        int newRnd = random.nextInt(100) + 1;
        String currentRegionName = '/' + regionName;
        if ((opFlags & OpFlags.USE_SUBREGION) > 0) {
          currentRegionName += ('/' + SUBREGION_NAME);
        }

        String credentialsTypeStr;
        OperationCode authOpCode = currentOp.getAuthzOperationCode();
        int[] indices = currentOp.getIndices();
        CredentialGenerator cGen = credentialGenerator.getCredentialGenerator();
        final Properties javaProps = cGen == null ? null : cGen.getJavaProperties();

        if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0 || (opFlags & OpFlags.USE_NOTAUTHZ) > 0) {
          opCredentials = credentialGenerator.getDisallowedCredentials(
              new OperationCode[] {authOpCode}, new String[] {currentRegionName}, indices, newRnd);
          credentialsTypeStr = " unauthorized " + authOpCode;

        } else {
          opCredentials =
              credentialGenerator.getAllowedCredentials(new OperationCode[] {opCode, authOpCode},
                  new String[] {currentRegionName}, indices, newRnd);
          credentialsTypeStr = " authorized " + authOpCode;
        }

        Properties clientProps =
            concatProperties(new Properties[] {opCredentials, extraAuthProps, extraAuthzProps});

        // Start the client with valid credentials but allowed or disallowed to perform an operation
        getLogWriter().info("executeOpBlock: For client" + clientNum + credentialsTypeStr
            + " credentials: " + opCredentials);
        boolean setupDynamicRegionFactory = (opFlags & OpFlags.ENABLE_DRF) > 0;
        if (useThisVM) {
          createCacheClient(authInit, clientProps, javaProps, new int[] {port1, port2}, 0,
              setupDynamicRegionFactory, NO_EXCEPTION);

        } else {
          clientVM.invoke(() -> createCacheClient(authInit, clientProps, javaProps,
              new int[] {port1, port2}, 0, setupDynamicRegionFactory, NO_EXCEPTION));
        }
      }

      int expectedResult;
      if ((opFlags & OpFlags.CHECK_NOTAUTHZ) > 0) {
        expectedResult = NOTAUTHZ_EXCEPTION;
      } else if ((opFlags & OpFlags.CHECK_EXCEPTION) > 0) {
        expectedResult = OTHER_EXCEPTION;
      } else {
        expectedResult = NO_EXCEPTION;
      }

      // Perform the operation from selected client
      if (useThisVM) {
        doOp(opCode, currentOp.getIndices(), new Integer(opFlags), new Integer(expectedResult));
      } else {
        int[] indices = currentOp.getIndices();
        clientVM.invoke(() -> DeltaClientPostAuthorizationDUnitTest.doOp(opCode, indices,
            new Integer(opFlags), new Integer(expectedResult)));
      }
    }
  }

  private void setUpDeltas() {
    for (int i = 0; i < 8; i++) {
      deltas[i] = new DeltaTestImpl(0, "0", new Double(0), new byte[0],
          new PartitionedRegionLocalMaxMemoryDUnitTest.TestObject1("0", 0));
    }
    deltas[1].setIntVar(5);
    deltas[2].setIntVar(5);
    deltas[3].setIntVar(5);
    deltas[4].setIntVar(5);
    deltas[5].setIntVar(5);
    deltas[6].setIntVar(5);
    deltas[7].setIntVar(5);

    deltas[2].resetDeltaStatus();
    deltas[2].setByteArr(new byte[] {1, 2, 3, 4, 5});
    deltas[3].setByteArr(new byte[] {1, 2, 3, 4, 5});
    deltas[4].setByteArr(new byte[] {1, 2, 3, 4, 5});
    deltas[5].setByteArr(new byte[] {1, 2, 3, 4, 5});
    // deltas[6].setByteArr(new byte[] { 1, 2, 3, 4, 5 });
    // deltas[7].setByteArr(new byte[] { 1, 2, 3, 4, 5 });

    deltas[3].resetDeltaStatus();
    deltas[3].setDoubleVar(new Double(5));
    deltas[4].setDoubleVar(new Double(5));
    deltas[5].setDoubleVar(new Double(5));
    deltas[6].setDoubleVar(new Double(5));
    deltas[7].setDoubleVar(new Double(5));

    deltas[4].resetDeltaStatus();
    deltas[4].setStr("str changed");
    deltas[5].setStr("str changed");
    deltas[6].setStr("str changed");
    // deltas[7].setStr("str changed");

    deltas[5].resetDeltaStatus();
    deltas[5].setIntVar(100);
    deltas[5].setTestObj(new PartitionedRegionLocalMaxMemoryDUnitTest.TestObject1("CHANGED", 100));
    deltas[6].setTestObj(new PartitionedRegionLocalMaxMemoryDUnitTest.TestObject1("CHANGED", 100));
    deltas[7].setTestObj(new PartitionedRegionLocalMaxMemoryDUnitTest.TestObject1("CHANGED", 100));

    deltas[6].resetDeltaStatus();
    deltas[6].setByteArr(new byte[] {1, 2, 3});
    deltas[7].setByteArr(new byte[] {1, 2, 3});

    deltas[7].resetDeltaStatus();
    deltas[7].setStr("delta string");
  }

  private OperationWithAction[] allOps() {
    return new OperationWithAction[] {
        // Test CREATE and verify with a GET
        new OperationWithAction(OperationCode.REGISTER_INTEREST, OperationCode.GET, 2,
            OpFlags.USE_REGEX | OpFlags.REGISTER_POLICY_NONE, 8),
        new OperationWithAction(OperationCode.REGISTER_INTEREST, OperationCode.GET, 3,
            OpFlags.USE_REGEX | OpFlags.REGISTER_POLICY_NONE | OpFlags.USE_NOTAUTHZ, 8),
        new OperationWithAction(OperationCode.PUT),
        new OperationWithAction(OperationCode.GET, 2, OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP, 4),
        new OperationWithAction(OperationCode.GET, 3,
            OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.CHECK_FAIL, 4),

        // OPBLOCK_END indicates end of an operation block that needs to be executed on each server
        // when doing failover
        OperationWithAction.OPBLOCK_END,

        // Test UPDATE and verify with a GET
        new OperationWithAction(OperationCode.REGISTER_INTEREST, OperationCode.GET, 2,
            OpFlags.USE_REGEX | OpFlags.REGISTER_POLICY_NONE, 8),
        new OperationWithAction(OperationCode.REGISTER_INTEREST, OperationCode.GET, 3,
            OpFlags.USE_REGEX | OpFlags.REGISTER_POLICY_NONE | OpFlags.USE_NOTAUTHZ, 8),
        new OperationWithAction(OperationCode.PUT, 1, OpFlags.USE_OLDCONN | OpFlags.USE_NEWVAL, 4),
        new OperationWithAction(OperationCode.GET, 2,
            OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.USE_NEWVAL, 4),
        new OperationWithAction(OperationCode.GET, 3,
            OpFlags.USE_OLDCONN | OpFlags.LOCAL_OP | OpFlags.USE_NEWVAL | OpFlags.CHECK_FAIL, 4),

        OperationWithAction.OPBLOCK_END};
  }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react'
import TextField from 'material-ui/TextField'
import RaisedButton from 'material-ui/RaisedButton'
import { Card, CardTitle, CardText, CardActions } from 'material-ui/Card'

import CircularProgress from 'material-ui/CircularProgress'

export default class MeshPoint extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      address: ''
    }
  }

  componentWillReceiveProps(nextProps) {
    if (this.state.address === '' && this.props.meshPoint.defaultAddress) {
      this.state = {
        address: this.props.meshPoint.defaultAddress
      }
    }
  }

  handleSendWei = () => {
    this.props.onSendWeiFormSubmit(this.props.meshPoint.selected.address, this.state.address, this.props.meshPoint.defaultAddress)
  }

  handleRequestAccess = () => {
    this.props.onRequestFaucetAccess(this.props.meshPoint.selected.address, this.state.address, this.props.meshPoint.defaultAddress)
  }

  handleNavigateToAdmin = () => {
    let path = '/node/' + this.props.meshPoint.selected.name + '/authorize-users'
    this.props.onNavigateToPath(path)
  }

  onInputChange(event) {
    this.setState({
      address: event.target.value
    })
  }

  render() {
    const { selected } = this.props.meshPoint

    const isLoaded = () => {
      return selected !== null;
    }

    if (!isLoaded()) {
      return (

          <CircularProgress mode='indeterminate' size={80} />

      );
    } else {

      return (
        <Card>
          {selected &&
            <CardTitle
              title={selected.name + ' MeshPoint Node'} style={{ 'textTransform': 'capitalize' }}
              subtitle={'Balance: ' + selected.balance + ' Ether'}
            />
          }
          <CardText>
            <TextField
              style={{ width: '100%' }}
              id='text-field-controlled'
              floatingLabelText='Address'
              value={this.state.address}
              errorText={this.state.error}
              onChange={e => this.onInputChange(e)}
            />

          </CardText>
          <CardActions style={{ textAlign: 'right' }}>

            <RaisedButton
            primary
            onClick={this.handleNavigateToAdmin}
            label='Admin' />
            <RaisedButton
              primary
              onClick={this.handleRequestAccess}
              label='Request Access' />
            <RaisedButton
              secondary
              style={{ marginRight: '0px' }}
              onClick={this.handleSendWei}
              label='Request 1 Ether' />
          </CardActions>
        </Card>
      )
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.macro.mall.dao.PmsSkuStockDao">
    <insert id="insertList">
        INSERT INTO pms_sku_stock (product_id, sku_code, price, stock, low_stock, pic, sale, sp_data) VALUES
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.productId,jdbcType=BIGINT},
            #{item.skuCode,jdbcType=VARCHAR},
            #{item.price,jdbcType=DECIMAL},
            #{item.stock,jdbcType=INTEGER},
            #{item.lowStock,jdbcType=INTEGER},
            #{item.pic,jdbcType=VARCHAR},
            #{item.sale,jdbcType=INTEGER},
            #{item.spData,jdbcType=VARCHAR})
        </foreach>
    </insert>
    <insert id="replaceList">
        REPLACE INTO pms_sku_stock (id,product_id, sku_code, price, stock, low_stock,pic, sale, sp_data) VALUES
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.id,jdbcType=BIGINT},
            #{item.productId,jdbcType=BIGINT},
            #{item.skuCode,jdbcType=VARCHAR},
            #{item.price,jdbcType=DECIMAL},
            #{item.stock,jdbcType=INTEGER},
            #{item.lowStock,jdbcType=INTEGER},
            #{item.pic,jdbcType=VARCHAR},
            #{item.sale,jdbcType=INTEGER},
            #{item.spData,jdbcType=VARCHAR})
        </foreach>
    </insert>
</mapper>


text:
package com.netflix.spinnaker.orca.pipelinetemplate.v1schema.model;

public interface NamedContent<T extends NamedContent> {

  String getName();
  boolean isRemove();
  boolean isMerge();
  T merge(T overlay);
}


text:
import Player
import logging
class TableManager:
	def __init__( self,game_logic):
		self._waiting_table = -1
		self._current_max_table_id = 0
		#空闲table的数组
		self._free_table_id = []
		self._table_mapping = dict()
		self._game_logic = game_logic
		self._user_table_map = dict()
		self._log = logging.getLogger('TableManager')
		self._log.setLevel(logging.DEBUG)
	def get_waiting_table( self ):
		return self._waiting_table
	def assign_user( self , uid ):
		tid = None
		if self._waiting_table > 0 :
			#当前有桌子等待人员加入
			tid = self._waiting_table
		elif len(self._free_table_id) > 0 :
			#当前没有桌子等待,但是有空余的table id
			tid = self._free_table_id.pop()
			#把这个id作为waiting
			self._waiting_table = tid
		else :
			tid = self._current_max_table_id + 1
			self._current_max_table_id += 1
			self._waiting_table = tid
		if tid in self._table_mapping:
			self._table_mapping[ tid ].add_player( uid )
		else:
			new_table = Table( tid )
			new_table.add_player( uid )
			self._table_mapping[ tid ] = new_table
		self._user_table_map[ uid ] =  self._table_mapping[ tid ]
		self._log.debug( "assign user: [%s] to table : [%d] , table player [%d]" %( uid , tid , self._table_mapping[ tid ].player_count()) )
		if self._table_mapping[ tid ].player_full():
			self._waiting_table = -1
			self._log.debug('table full , start game ' )
			self.start_game( tid )
	def start_game( self , table_id ):
		self._game_logic.notify_game_start( self._table_mapping[ table_id ].get_players() )

	def player_out_pokes( self , uid , out_pokes ):
		if uid not in self._user_table_map:
			print "user: %s not in mapping table" %(uid)
			return
		#通过user id 找table id
		table_id = self._user_table_map[ uid ]
		table_ins = self._table_mapping[ table_id ]
		table_ins.player_out_pokes( uid , out_pokes )
		self._game_logic.send_out_pokes_result( uid , table_ins.get_players() , out_pokes )

	def remove_user( self , uid ):
		if uid in self._user_table_map:
			table_ins = self._user_table_map[ uid ]
			player_list = table_ins.get_players()
			table_ins.remove_all_player()
			table_id = table_ins.get_table_id()
			if table_id in self._table_mapping:
				self._table_mapping.pop( table_id )
				self._free_table_id.append( table_id )
			return player_list
		else:
			self._log.debug('no this user table map relation [%s]' %( uid ))
			return None

	def finish_game( self , table_id ):
		pass

class Table:
	def __init__(self , table_id):
		self._players = []
		self._id = table_id
	def get_table_id( self ):
		return self._id
	def add_player( self , user_id ):
		self._players.append( Player.Player(user_id) )
	def remove_player( self , uid ):
		index = 0
		do_remove = False
		for player in self._players:
			if player.get_id() == uid:
				do_remove = True
				self._players.pop( index )
				break
			++ index
		return do_remove
	def remove_all_player( self ):
		self._players = []
	def player_full( self ):
		return len(self._players) == 3
	def table_is_empty( self ) :
		return len( self._players ) == 0
	def get_players( self ):
		return self._players
	def player_out_pokes( self , uid , pokes ):
		for player in self._players:
			if  player.get_id() == uid :
				player.out_pokes( pokes )
				break
	def player_count( self ):
		return len(self._players)
if __name__ == '__main__':
	tm = None
	if tm is None:
		print "none"
	else:
		print "dd"


text:
using System;
using System.IO;
using SupaCharge.Core.ThreadingAbstractions;

namespace SupaCharge.Core.IOAbstractions {
  public class DotNetDirectory : IDirectory {
    public string[] GetFiles(string path, string searchPattern) {
      return Directory.GetFiles(path, searchPattern);
    }

    public string GetCurrentDirectory() {
      return Directory.GetCurrentDirectory();
    }

    public DirectoryInfo CreateDirectory(string path) {
      return Directory.CreateDirectory(path);
    }

    public bool Exists(string path) {
      return Directory.Exists(path);
    }

    public string[] GetDirectories(string path) {
      return Directory.GetDirectories(path);
    }

    public void Delete(string path) {
      Directory.Delete(path);
    }

    public void Delete(string path, bool recursive) {
      Directory.Delete(path, recursive);
    }

    public string[] GetFiles(string path, string searchPattern, SearchOption searchOption) {
      return Directory.GetFiles(path, searchPattern, searchOption);
    }

    public void Delete(string path, int waitMilliseconds) {
      new Retry((int)Math.Ceiling(waitMilliseconds / 15d) + 1, 15)
        .WithWork(x => {
                    if (Exists(path))
                      Delete(path, true);
                  })
        .Start();
    }
  }
}


text:
- Haskell 99 problems
- more?


text:
import { Inject, Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { CustomComputeOfferingParameters, ServiceOffering } from '../../../../app/shared/models';

@Injectable()
export class MockCustomServiceOfferingService {
  constructor(
    @Inject('mockCustomServiceOfferingServiceConfig')
    public config: {
      customOffering: ServiceOffering;
      customOfferingRestrictionsByZone: CustomComputeOfferingParameters;
    },
  ) {}

  public getCustomOfferingWithSetParams(): Observable<ServiceOffering> {
    return of(this.config.customOffering);
  }

  public getCustomOfferingWithSetParamsSync(): ServiceOffering {
    return this.config.customOffering;
  }

  public getCustomOfferingRestrictionsByZone(): Observable<CustomComputeOfferingParameters> {
    return of(this.config.customOfferingRestrictionsByZone);
  }

  public getCustomOfferingRestrictionsByZoneSync(): CustomComputeOfferingParameters {
    return this.config.customOfferingRestrictionsByZone;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cosmos.IL2CPU.Plugs;

namespace Cosmos.IL2CPU.IL.CustomImplementations.System {
	[Plug(TargetName = "System.SR, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", IsMicrosoftdotNETOnly = true)]
	public static class SRImpl {
		public static string GetString(string aString) {
			return aString;
		}

		public static string GetString(string aString, params object[] aArgs) {
			return aString;
		}
	}
}


text:
<?php

namespace App\Containers\Event\Data\Repositories;

use App\Ship\Parents\Repositories\Repository;

class EventRepository extends Repository
{
    protected $fieldSearchable = [
        'id'    => '=',
        'title'  => 'like',
        'description' => 'like',
        'event_date' => '='
    ];

    public function boot()
    {
        // probably do some stuff here ...
    }
}


text:
using System.Web.Mvc;

namespace CS.Web.Mvc.Extension
{
    public static class HtmlHelperExt
    {

        /// <summary>
        /// 属性增加
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="express"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static MvcHtmlString SetProperty(this HtmlHelper helper, bool express, string key, string value)
        {
            return express && !string.IsNullOrWhiteSpace(value) ? new MvcHtmlString($" {key}=\"{value}\"") : null;
        }

        /// <summary>
        /// 设置一个class属性的键值对
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static MvcHtmlString SetClass(this HtmlHelper helper, string value)
        {
            return helper.SetProperty(true, "class", value);
        }

        /// <summary>
        /// 设置一个class属性的键值对
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="express"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static MvcHtmlString SetClass(this HtmlHelper helper, bool express, string value)
        {
            return helper.SetProperty(express, "class", value);
        }

        /// <summary>
        /// 增加css名字的引用
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="classNames"></param>
        /// <returns></returns>
        public static MvcHtmlString ToClassNames(this HtmlHelper helper, string classNames = null)
        {
            classNames = string.IsNullOrWhiteSpace(classNames) ? helper.ViewBag.BodyCssNames : classNames;
            return helper.SetProperty(true, "class", classNames);
            //string.IsNullOrWhiteSpace(classNames) ? null : new MvcHtmlString($" class=\"{classNames}\"");
        }

        /// <summary>
        /// 获了路由路径中的某一值
        /// </summary>
        /// <param name="html"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetRouteData(this HtmlHelper html, string name)
        {
            return html.ViewContext.RouteData.GetRouteValue(name);
        }

        /// <summary>
        /// 获取控制器名称
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string GetControllerName(this HtmlHelper html)
        {
            return html.ViewContext.RouteData.GetControllerName();
        }

        /// <summary>
        /// 获取Action名称
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string GetActionName(this HtmlHelper html)
        {
            return html.ViewContext.RouteData.GetActionName();
        }

        /// <summary>
        /// 获取area名称
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string GetAreaName(this HtmlHelper html)
        {
            return html.ViewContext.RouteData.GetAreaName();
        }

    }
}


text:
CASSANDRA_CONF=/etc/cassandra

# The java classpath (required)
CLASSPATH=$CASSANDRA_CONF

for jar in /usr/share/cassandra/*.jar; do
    CLASSPATH=$CLASSPATH:$jar
done


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

using ServiceInterfaces;

namespace ServiceImplementations.Generic
{
    public class ApplicationSettings : ISettings
    {
        public string GetSetting(string key)
        {
            if(!ConfigurationManager.AppSettings.AllKeys.Contains(key))
            {
                throw new ApplicationException(string.Format("The key could not be found: {0}", key));
            }
            return ConfigurationManager.AppSettings[key];
        }
    }
}


text:
package eu.seaclouds.platform.planner.core.utils;

import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;

public class YamlParser {

    private static Yaml getYamlParser() {
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        return new Yaml(options);
    }

    public static Map<String, Object> load(String value) {
        return (Map<String, Object>) getYamlParser().load(value);
    }

    public static String dump(Map<String, Object> yaml) {
        return getYamlParser().dump(yaml);
    }

}


text:
class FunctionCall
  attr_accessor :prerequisites, :body, :return_value
  def initialize(body, prerequisites="", rvalue=body)
    @prerequisites = prerequisites
    @body = body
    @return_value = rvalue
  end
end

module Tree

  @@token_functions = {}
  @@token_predicates = []
  @@stacks = [[]]

  ### A DSL for matching against certain tokens. ###

  def self.match(token, &block)
    if token.respond_to? :call
      @@token_predicates << [token, block]
    else
      @@token_functions[token] = block
    end
  end

  def self.alias_symbol(hzl_symbol, go_symbol)
    match hzl_symbol do |tree|
      fn = call_normal_function(tree)
      fn.body.sub!  hzl_symbol.to_s, go_symbol.to_s # this might be terrible
      fn
    end
  end

  # alias_symbol :".=", :set_struct_member
  # alias_symbol :".", :get_struct_member

  match :if do |tree|
    raise "argument error: if takes one argument" if tree.arguments.length != 1
    raise "argument error: if takes a block" if tree.block.nil?

    enter_stack

    fn = call(tree.arguments[0])
    fn.body = [
      "if from_bool(",
      fn.body,
      "){",
      generate_calls(tree.block.forest, false),
      "}",
    ].join

    exit_stack

    self.if_statement = fn
  end

  match :else do |tree|
    # TODO: This can be refactored to be better.
    raise "syntax error: else must follow an if" unless self.if_statement
    enter_stack
    if tree.arguments.length == 0
      previous_if = self.if_statement
      self.if_statement = nil
      previous_if.body << [
        "else ",
        "{",
        generate_calls(tree.block.forest, false),
        "}",
      ].join
    else
      unless tree.arguments[0].symbol == :if
        raise "syntax error: else can only be followed by if or {"
      end
      tree.name = tree.arguments.shift.name
      self.if_statement.body << "else "
      fn = call(tree)
      self.if_statement.prerequisites << fn.prerequisites
      self.if_statement.body << fn.body
      self.if_statement.return_value = fn.return_value
    end
    self.if_statement = nil
    exit_stack
    FunctionCall.new('into_any(NIL, nil)') # Should be a no-op because we added it to the if.
  end

  match :"=" do |tree|
    raise "= does not take a block" if tree.block
    raise "= takes two arguments" unless tree.arguments.length == 2
    value, assignee = tree.arguments

    if assignee.is_ident?
      if @@stacks.flatten.include?(assignee.symbol)
        equals = "="
      else
        equals = ":="
        stack_push assignee
      end

      name = hzl_namespace(assignee.symbol)

      fn = call(value)
      preceeding = fn.prerequisites
      body = [name, equals, fn.body, "\n"].join
      FunctionCall.new(body, preceeding, name)
    elsif assignee.symbol == :"."
      raise "cannot assign to function call" unless assignee.arguments.length == 2
      assignee.arguments.push value
      assignee.name.symbol = :".="
      call_normal_function(assignee)
    else
      binding.pry
      raise "'=' needs a valid identifier to assign to"
    end
  end

  match :return do |tree|
    raise "return does not take a block" if tree.block
    raise "return takes at least one argument" if tree.arguments.empty?

    name = tree.arguments[0]
    # tree.name = tree.arguments.shift

    fn = call(name)
    temp = temp_var

    # should this be body?
    prerequisites = fn.prerequisites + "\n#{temp} :=" + fn.body

    # puts name.inspect
    # binding.pry

    FunctionCall.new(
      "\nreturn #{temp}",
      prerequisites,
      fn.return_value,
    )
  end

  match :char do |tree|
    raise "char does not take a block" if tree.block
    raise "char takes one argument" if tree.arguments.length != 1
    name = tree.arguments[0].symbol.to_s

    if name[0] != "'"
      name = "'" + name + "'"
    end

    temp = temp_var
    preceeding = "#{temp} := #{name}\n"

    body = "into_any(CHAR, unsafe.Pointer(&#{temp}))"

    FunctionCall.new(
      body,
      preceeding,
    )
  end

  match :new do |tree|
    raise "new does not take a block" if tree.block
    raise "new takes one argument" if tree.arguments.length != 1
    name = tree.arguments[0].symbol
    fields, i = @struct_definitions[name]

    raise "No such struct defined #{name}" unless fields

    temp = temp_var
    preceeding = [
      temp,
      ":= []*any{",
      fields.map { |_| "into_any(NIL, nil)" }.join(","),
      "}\n"
    ].join

    body = "into_any(#{i}, unsafe.Pointer(&#{temp}))"

    FunctionCall.new(
      body,
      preceeding,
    )
  end

  match :lambda do |tree|
    if tree.block
      raise "lambda takes no arguments" unless tree.arguments.empty?
      body = block(tree)
      temp = temp_var
      preceeding = "\n#{temp} := #{body}\n"
      FunctionCall.new(
        "into_any(LAMBDA, unsafe.Pointer(&#{temp}))",
        preceeding,
      )
    else
      raise "lambda without a block takes one argument" unless tree.arguments.length == 1
      raise "argument to lambda should be an ident" unless tree.arguments[0].is_ident?
      name = tree.arguments[0].symbol
      FunctionCall.new(
        "into_any(LAMBDA, unsafe.Pointer(&#{hzl_namespace(name)}))",
      )
    end
  end

  match :array do |tree|
    raise "array does not take a block" if tree.block
    preceeding = ''
    body = '[]*any{'
    seperator = ''
    tree.arguments.map do |item|
      fn = call(item)

      preceeding += fn.prerequisites
      body += seperator
      body += fn.body
      seperator = ', '
    end
    body += '}'
    temp = temp_var
    preceeding += "\n#{temp} := #{body}\n"
    FunctionCall.new(
      "into_any(ARRAY, unsafe.Pointer(&#{temp}))",
      preceeding,
    )
  end

  # Integer and Float constants.
  match lambda { |symbol| symbol.to_s[0].numeric? } do |tree|
    raise "Numbers do not take a block" if tree.block
    raise "Numbers do not take any arguments" if tree.arguments.length != 0
    if tree.symbol.to_s.include? "."
      type = 'FLOAT'
    else
      type = 'INT'
    end
    tmp = temp_var
    definition = "#{tmp} := #{tree.symbol}\n"
    body= "into_any(#{type}, unsafe.Pointer(&#{tmp}))"
    FunctionCall.new(body, definition)
  end

  # String constants
  match lambda { |symbol| symbol.to_s[0].quote? } do |tree|
    raise "Strings do not take a block" if tree.block
    raise "Strings do not take any arguments" if tree.arguments.length != 0
    tmp = temp_var
    content = tree.symbol.to_s[1..-2]
    FunctionCall.new(
      "into_any(STRING, unsafe.Pointer(&#{tmp}))", # body
      "#{tmp} := \"#{content}\"\n" # preceeding
    )
  end

  ### Other Functions that are key to generating function calls ###

  def call(tree)
    function = @@token_functions[tree.symbol]
    return self.instance_exec(tree, &function) if function

    @@token_predicates.each do |predicate, function|
      if predicate.call(tree.symbol)
        fn = self.instance_exec(tree, &function)
        return fn
      end
    end

    call_normal_function(tree)
  end

  def call_normal_function(tree)
    self.if_statement = nil

    if tree.is_ident? and @@stacks.flatten.include? tree.symbol
      return FunctionCall.new(hzl_namespace(tree.symbol))
    end
    fn = arguments(tree)
    fn.body = [
             hzl_namespace(tree.symbol),
             "(",
             fn.body,
             ",",
             block(tree),
             ")",
           ].join
     fn.return_value = fn.body
     fn
  end

  def stack_push(expression)
    @@stacks.last << expression.symbol
  end

  def arguments(tree)
    fn_acc = tree.arguments.reduce(FunctionCall.new("")) do |fn_acc, argument|
        fn = call(argument)
        fn_acc.prerequisites += fn.prerequisites
        fn_acc.return_value = fn.return_value

        fn_acc.body += fn.body
        fn_acc.body += ","
        fn_acc
    end
    fn_acc.body = "[]*any{#{fn_acc.body}}"
    fn_acc
  end

  def block(tree, extra="", stack_name=nil)
    return 'nil' if not tree.block

    enter_stack
    output = generate_function("", tree.block.arguments, tree.block.forest, true, extra, stack_name)
    exit_stack
    return output
  end

  def enter_stack
    @@stacks << []
  end

  def exit_stack
    @@stacks.pop
  end

  def temp_var
    @i ||= 0
    @i += 1
   "hazelnut_#{@i}"
  end

end


text:
from google.cloud import aiplatform_v1beta1

async def sample_get_index_endpoint():
    # Create a client
    client = aiplatform_v1beta1.IndexEndpointServiceAsyncClient()

    # Initialize request argument(s)
    request = aiplatform_v1beta1.GetIndexEndpointRequest(
        name="name_value",
    )

    # Make the request
    response = await client.get_index_endpoint(request=request)

    # Handle the response
    print(response)

# [END aiplatform_v1beta1_generated_IndexEndpointService_GetIndexEndpoint_async]


text:
using Microsoft.Win32.SafeHandles;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

internal static partial class Interop
{
    internal const int EFail = unchecked((int)0x80004005);

    public static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);

    public const int STARTF_USESTDHANDLES = 0x00000100;

    public const int STD_INPUT_HANDLE = -10;
    public const int STD_OUTPUT_HANDLE = -11;
    public const int STD_ERROR_HANDLE = -12;

    public const int STILL_ACTIVE = 0x00000103;

    public const int WAIT_TIMEOUT = 0x00000102;

    public const int ERROR_BAD_EXE_FORMAT = 193;
    public const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216;
    public const int ERROR_NOT_READY = 21;
    public const int ERROR_LOCK_FAILED = 167;
    public const int ERROR_BUSY = 170;
    public const int ERROR_INVALID_HANDLE = 6;
    public const int ERROR_INVALID_PARAMETER = 87;
    public const int ERROR_PARTIAL_COPY = 299;
    public const int ERROR_SUCCESS = 0;

    public const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;

    public const uint STATUS_INFO_LENGTH_MISMATCH = 0xC0000004;

    public const int NtPerfCounterSizeLarge = 0x00000100;

    public const int NtQueryProcessBasicInfo = 0;
    public const int NtQuerySystemProcessInformation = 5;

    public const int PROCESS_TERMINATE = 0x0001;
    public const int PROCESS_VM_READ = 0x0010;
    public const int PROCESS_SET_QUOTA = 0x0100;
    public const int PROCESS_SET_INFORMATION = 0x0200;
    public const int PROCESS_QUERY_INFORMATION = 0x0400;
    public const int PROCESS_QUERY_LIMITED_INFORMATION = 0x1000;
    public const int PROCESS_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | 0xFFF;

    public const int STANDARD_RIGHTS_REQUIRED = 0x000F0000;
    public const int SYNCHRONIZE = 0x00100000;

    public const int THREAD_SET_INFORMATION = 0x0020;
    public const int THREAD_QUERY_INFORMATION = 0x0040;

    public const int DUPLICATE_SAME_ACCESS = 2;

    public const int RPC_S_SERVER_UNAVAILABLE = 1722;
    public const int RPC_S_CALL_FAILED = 1726;

    public const int SE_PRIVILEGE_ENABLED = 2;
    public const string SeDebugPrivilege = "SeDebugPrivilege";

    public const int TOKEN_ADJUST_PRIVILEGES = 0x20;

    public const int CREATE_NO_WINDOW = 0x08000000;

    public const int SMTO_ABORTIFHUNG = 0x0002;

    public const int GWL_STYLE = (-16);

    public const int WS_DISABLED = 0x08000000;
    public const int WM_NULL = 0x0000;
    public const int WM_CLOSE = 0x0010;

    [StructLayout(LayoutKind.Sequential)]
    internal class STARTUPINFO : IDisposable
    {
        public int cb;
        public IntPtr lpReserved = IntPtr.Zero;
        public IntPtr lpDesktop = IntPtr.Zero;
        public IntPtr lpTitle = IntPtr.Zero;
        public int dwX = 0;
        public int dwY = 0;
        public int dwXSize = 0;
        public int dwYSize = 0;
        public int dwXCountChars = 0;
        public int dwYCountChars = 0;
        public int dwFillAttribute = 0;
        public int dwFlags = 0;
        public short wShowWindow = 0;
        public short cbReserved2 = 0;
        public IntPtr lpReserved2 = IntPtr.Zero;
        public SafeFileHandle hStdInput = new SafeFileHandle(IntPtr.Zero, false);
        public SafeFileHandle hStdOutput = new SafeFileHandle(IntPtr.Zero, false);
        public SafeFileHandle hStdError = new SafeFileHandle(IntPtr.Zero, false);

        public STARTUPINFO()
        {
            cb = Marshal.SizeOf(this);
        }

        public void Dispose()
        {
            // close the handles created for child process
            if (hStdInput != null && !hStdInput.IsInvalid)
            {
                hStdInput.Dispose();
                hStdInput = null;
            }

            if (hStdOutput != null && !hStdOutput.IsInvalid)
            {
                hStdOutput.Dispose();
                hStdOutput = null;
            }

            if (hStdError != null && !hStdError.IsInvalid)
            {
                hStdError.Dispose();
                hStdError = null;
            }
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class PERF_COUNTER_BLOCK
    {
        public int ByteLength = 0;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class PERF_COUNTER_DEFINITION
    {
        public int ByteLength = 0;
        public int CounterNameTitleIndex = 0;

        // this one is kind of weird. It is defined as in SDK:
        // #ifdef _WIN64
        //  DWORD           CounterNameTitle;
        // #else
        //  LPWSTR          CounterNameTitle;
        // #endif
        // so we can't use IntPtr here.

        public int CounterNameTitlePtr = 0;
        public int CounterHelpTitleIndex = 0;
        public int CounterHelpTitlePtr = 0;
        public int DefaultScale = 0;
        public int DetailLevel = 0;
        public int CounterType = 0;
        public int CounterSize = 0;
        public int CounterOffset = 0;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class PERF_DATA_BLOCK
    {
        public int Signature1 = 0;
        public int Signature2 = 0;
        public int LittleEndian = 0;
        public int Version = 0;
        public int Revision = 0;
        public int TotalByteLength = 0;
        public int HeaderLength = 0;
        public int NumObjectTypes = 0;
        public int DefaultObject = 0;
        public SYSTEMTIME SystemTime = null;
        public int pad1 = 0;  // Need to pad the struct to get quadword alignment for the 'long' after SystemTime
        public long PerfTime = 0;
        public long PerfFreq = 0;
        public long PerfTime100nSec = 0;
        public int SystemNameLength = 0;
        public int SystemNameOffset = 0;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class PERF_INSTANCE_DEFINITION
    {
        public int ByteLength = 0;
        public int ParentObjectTitleIndex = 0;
        public int ParentObjectInstance = 0;
        public int UniqueID = 0;
        public int NameOffset = 0;
        public int NameLength = 0;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class PERF_OBJECT_TYPE
    {
        public int TotalByteLength = 0;
        public int DefinitionLength = 0;
        public int HeaderLength = 0;
        public int ObjectNameTitleIndex = 0;
        public int ObjectNameTitlePtr = 0;
        public int ObjectHelpTitleIndex = 0;
        public int ObjectHelpTitlePtr = 0;
        public int DetailLevel = 0;
        public int NumCounters = 0;
        public int DefaultCounter = 0;
        public int NumInstances = 0;
        public int CodePage = 0;
        public long PerfTime = 0;
        public long PerfFreq = 0;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class NtProcessBasicInfo
    {
        public int ExitStatus = 0;
        public IntPtr PebBaseAddress = (IntPtr)0;
        public IntPtr AffinityMask = (IntPtr)0;
        public int BasePriority = 0;
        public IntPtr UniqueProcessId = (IntPtr)0;
        public IntPtr InheritedFromUniqueProcessId = (IntPtr)0;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class NtModuleInfo
    {
        public IntPtr BaseOfDll = (IntPtr)0;
        public int SizeOfImage = 0;
        public IntPtr EntryPoint = (IntPtr)0;
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")]
    [StructLayout(LayoutKind.Sequential)]
    internal class SYSTEMTIME
    {
        public short wYear;
        public short wMonth;
        public short wDayOfWeek;
        public short wDay;
        public short wHour;
        public short wMinute;
        public short wSecond;
        public short wMilliseconds;

        public override string ToString()
        {
            return "[SYSTEMTIME: "
            + wDay.ToString(CultureInfo.CurrentCulture) + "/" + wMonth.ToString(CultureInfo.CurrentCulture) + "/" + wYear.ToString(CultureInfo.CurrentCulture)
            + " " + wHour.ToString(CultureInfo.CurrentCulture) + ":" + wMinute.ToString(CultureInfo.CurrentCulture) + ":" + wSecond.ToString(CultureInfo.CurrentCulture)
            + "]";
        }
    }

    internal static partial class mincore
    {
        [DllImport("api-ms-win-core-wow64-l1-1-0", SetLastError = true)]
        public static extern bool IsWow64Process(SafeProcessHandle hProcess, ref bool Wow64Process);

        [SecurityCritical]
        [DllImport("api-ms-win-core-handle-l1-1-0", ExactSpelling = true, CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool CloseHandle(IntPtr handle);

        public static string GetComputerName()
        {
            char[] buffer = new char[256];
            uint length = (uint)buffer.Length;

            Interop.mincore.GetComputerName(buffer, ref length);
            return new string(buffer, 0, (int)length);
        }

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool GetExitCodeProcess(SafeProcessHandle processHandle, out int exitCode);

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool GetProcessTimes(SafeProcessHandle handle, out long creation, out long exit, out long kernel, out long user);

        [DllImport("api-ms-win-core-processthreads-l1-1-1", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool GetThreadTimes(SafeThreadHandle handle, out long creation, out long exit, out long kernel, out long user);

        [DllImport("api-ms-win-core-processenvironment-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Ansi, SetLastError = true)]
        public static extern IntPtr GetStdHandle(int whichHandle);

        [DllImport("api-ms-win-core-namedpipe-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool CreatePipe(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true, BestFitMapping = false, EntryPoint = "CreateProcessW")]
        public static extern bool CreateProcess(
            [MarshalAs(UnmanagedType.LPTStr)]
            string lpApplicationName,                   // LPCTSTR
            StringBuilder lpCommandLine,                // LPTSTR - note: CreateProcess might insert a null somewhere in this string
            SECURITY_ATTRIBUTES procSecAttrs,          // LPSECURITY_ATTRIBUTES
            SECURITY_ATTRIBUTES threadSecAttrs,        // LPSECURITY_ATTRIBUTES
            bool bInheritHandles,                        // BOOL
            int dwCreationFlags,                        // DWORD
            IntPtr lpEnvironment,                       // LPVOID
            [MarshalAs(UnmanagedType.LPTStr)]
            string lpCurrentDirectory,                  // LPCTSTR
            STARTUPINFO lpStartupInfo,                  // LPSTARTUPINFO
            Interop.PROCESS_INFORMATION lpProcessInformation    // LPPROCESS_INFORMATION
        );

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool TerminateProcess(SafeProcessHandle processHandle, int exitCode);

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Ansi, SetLastError = true)]
        public static extern SafeProcessHandle GetCurrentProcess();

        [DllImport("api-ms-win-core-processthreads-l1-1-1", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern SafeProcessHandle OpenProcess(int access, bool inherit, int processId);

        [DllImport("api-ms-win-core-psapi-obsolete-l1-1-0.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true, EntryPoint = "K32EnumProcessModules")]
        public static extern bool EnumProcessModules(SafeProcessHandle handle, IntPtr modules, int size, ref int needed);

        [DllImport("api-ms-win-core-psapi-l1-1-0.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true, EntryPoint = "K32EnumProcesses")]
        public static extern bool EnumProcesses(int[] processIds, int size, out int needed);

        [DllImport("api-ms-win-core-psapi-obsolete-l1-1-0.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true, EntryPoint = "K32GetModuleInformation")]
        public static extern bool GetModuleInformation(SafeProcessHandle processHandle, IntPtr moduleHandle, NtModuleInfo ntModuleInfo, int size);

        [DllImport("api-ms-win-core-psapi-obsolete-l1-1-0.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true, BestFitMapping = false, EntryPoint = "K32GetModuleBaseNameW")]
        public static extern int GetModuleBaseName(SafeProcessHandle processHandle, IntPtr moduleHandle, StringBuilder baseName, int size);

        [DllImport("api-ms-win-core-psapi-obsolete-l1-1-0.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true, BestFitMapping = false, EntryPoint = "K32GetModuleFileNameExW")]
        public static extern int GetModuleFileNameEx(SafeProcessHandle processHandle, IntPtr moduleHandle, StringBuilder baseName, int size);

        [DllImport("api-ms-win-core-memory-l1-1-1", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool SetProcessWorkingSetSizeEx(SafeProcessHandle handle, IntPtr min, IntPtr max, int flags);

        [DllImport("api-ms-win-core-memory-l1-1-1", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool GetProcessWorkingSetSizeEx(SafeProcessHandle handle, out IntPtr min, out IntPtr max, out int flags);

        // These APIs are in obsolete lib however even the mincore_fw.lib has these APIs, so it should be ok to expose it.
        [DllImport("api-ms-win-core-processtopology-obsolete-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool SetProcessAffinityMask(SafeProcessHandle handle, IntPtr mask);
        [DllImport("api-ms-win-core-processtopology-obsolete-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool GetProcessAffinityMask(SafeProcessHandle handle, out IntPtr processMask, out IntPtr systemMask);

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool GetThreadPriorityBoost(SafeThreadHandle handle, out bool disabled);
        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool SetThreadPriorityBoost(SafeThreadHandle handle, bool disabled);

        [DllImport("api-ms-win-core-processthreads-l1-1-2", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool GetProcessPriorityBoost(SafeProcessHandle handle, out bool disabled);

        [DllImport("api-ms-win-core-processthreads-l1-1-2", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool SetProcessPriorityBoost(SafeProcessHandle handle, bool disabled);

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern SafeThreadHandle OpenThread(int access, bool inherit, int threadId);

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool SetThreadPriority(SafeThreadHandle handle, int priority);

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern int GetThreadPriority(SafeThreadHandle handle);

        [DllImport("api-ms-win-core-processtopology-obsolete-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern IntPtr SetThreadAffinityMask(SafeThreadHandle handle, IntPtr mask);

        [DllImport("api-ms-win-core-kernel32-legacy-l1-1-1", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern int SetThreadIdealProcessor(SafeThreadHandle handle, int processor);

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern int GetPriorityClass(SafeProcessHandle handle);

        [DllImport("api-ms-win-core-processthreads-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool SetPriorityClass(SafeProcessHandle handle, int priorityClass);

        [DllImport("ntdll.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
        public static extern int NtQueryInformationProcess(SafeProcessHandle processHandle, int query, NtProcessBasicInfo info, int size, int[] returnedSize);

        [DllImport("ntdll.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
        public static extern int NtQuerySystemInformation(int query, IntPtr dataPtr, int size, out int returnedSize);

        [DllImport("api-ms-win-core-handle-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Ansi, SetLastError = true, BestFitMapping = false)]
        public static extern bool DuplicateHandle(
            SafeProcessHandle hSourceProcessHandle,
            SafeHandle hSourceHandle,
            SafeProcessHandle hTargetProcess,
            out SafeFileHandle targetHandle,
            int dwDesiredAccess,
            bool bInheritHandle,
            int dwOptions
        );

        [DllImport("api-ms-win-core-handle-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Ansi, SetLastError = true, BestFitMapping = false)]
        public static extern bool DuplicateHandle(
            SafeProcessHandle hSourceProcessHandle,
            SafeHandle hSourceHandle,
            SafeProcessHandle hTargetProcess,
            out SafeWaitHandle targetHandle,
            int dwDesiredAccess,
            bool bInheritHandle,
            int dwOptions
        );

        [DllImport("api-ms-win-core-processsecurity-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool OpenProcessToken(SafeProcessHandle ProcessHandle, int DesiredAccess, out SafeTokenHandle TokenHandle);

        [DllImport("api-ms-win-security-lsalookup-l2-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
        public static extern bool LookupPrivilegeValue([MarshalAs(UnmanagedType.LPTStr)] string lpSystemName, [MarshalAs(UnmanagedType.LPTStr)] string lpName, out LUID lpLuid);

        [DllImport("api-ms-win-security-base-l1-1-0", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
        public static extern bool AdjustTokenPrivileges(
            SafeTokenHandle TokenHandle,
            bool DisableAllPrivileges,
            TokenPrivileges NewState,
            int BufferLength,
            IntPtr PreviousState,
            IntPtr ReturnLength
        );

        [DllImport("api-ms-win-core-kernel32-legacy-l1-1-0.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, EntryPoint = "GetComputerNameW")]
        internal extern static int GetComputerName(
                    char[] lpBuffer,
                    ref uint nSize);

        [DllImport("api-ms-win-core-processthreads-l1-1-0.dll")]
        internal extern static uint GetCurrentProcessId();

        [DllImport("api-ms-win-core-console-l1-1-0.dll")]
        internal extern static uint GetConsoleCP();

        [DllImport("api-ms-win-core-console-l1-1-0.dll")]
        internal extern static uint GetConsoleOutputCP();

        [DllImport("api-ms-win-core-localization-l1-2-0.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, EntryPoint = "FormatMessageW")]
        internal extern static uint FormatMessage(
                    uint dwFlags,
                    IntPtr lpSource,
                    uint dwMessageId,
                    uint dwLanguageId,
                    char[] lpBuffer,
                    uint nSize,
                    IntPtr Arguments);
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class PROCESS_INFORMATION
    {
        public IntPtr hProcess = IntPtr.Zero;
        public IntPtr hThread = IntPtr.Zero;
        public int dwProcessId = 0;
        public int dwThreadId = 0;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class SECURITY_ATTRIBUTES
    {
        public int nLength = 12;
        public IntPtr lpSecurityDescriptor = IntPtr.Zero;
        public bool bInheritHandle = false;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal class TokenPrivileges
    {
        public int PrivilegeCount = 1;
        public LUID Luid;
        public int Attributes = 0;
    }

    [StructLayout(LayoutKind.Sequential)]
    internal struct LUID
    {
        public int LowPart;
        public int HighPart;
    }
}


text:
bosshp = 58
spellcost = [53,73,113,173,229]
bossdam = 9

best = 99999

def play(bosshp, playerhp, mana, cost, spellshield, spellpoison, spellrecharge, spell):
    global spellcost, best, bossdam

    # Player
    if spell == 0:
        bosshp -= 4

    if spell == 1:
        playerhp+=2
        bosshp -=2

    if spell == 2:
        if spellshield == 0:
            spellshield = 6
        else:
            return False

    if spell == 3:
        if spellpoison == 0:
            spellpoison = 6
        else:
            return False

    if spell == 4:
        if (spellrecharge == 0):
            spellrecharge = 5
        else:
            return False

    mana -= spellcost[spell]
    cost += spellcost[spell]

    if bosshp <= 0:
        if cost < best:
            best = cost
        return True

    #Boss
    if spellrecharge > 0:
        mana += 101
        spellrecharge-=1

    if spellpoison > 0:
        bosshp -= 3
        spellpoison-=1

    if spellshield > 0:
        spellshield -= 1
        armor = 7
    else:
        armor = 0

    if bosshp > 0:
        if ((bossdam - armor ) < 1):
            playerhp -= 1
        else:
            playerhp -= (bossdam - armor)
    else:
        if (cost < best):
            best = cost
        return True

    playerhp-=1  # hard mode bleed effect
    if playerhp <= 0:
        return False

    # player turn begin
    if (spellshield > 0):
        spellshield -= 1

    if (spellrecharge > 0):
        mana += 101
        spellrecharge -= 1

    if (spellpoison > 0):
        bosshp -= 3
        spellpoison -= 1

    if (bosshp <= 0):
        if (cost < best):
            best = cost
        return True

    for nextspell in range(0, 5):
        if (mana >= spellcost[nextspell]):
            play(bosshp, playerhp, mana, cost, spellshield, spellpoison, spellrecharge, nextspell)

    return False

for firstspell in reversed(range(4)): # From part 1 the best score was in the third node so we search from there right aways.
    print ("(%d) " % (firstspell))
    play(bosshp, 49, 500, 0, 0, 0, 0, firstspell)
    print best


text:
<?php
require 'metaphone.php';

use Metaphone\Metaphone;

echo Metaphone::getPhraseMetaphone('é um testi super legal') . PHP_EOL;
echo Metaphone::getPhraseMetaphone('chocolate e farinha faquir') . PHP_EOL;
echo Metaphone::getPhraseMetaphone('acerola asserola aserola') . PHP_EOL;
echo Metaphone::getPhraseMetaphone('calça calsa calssa') . PHP_EOL;


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>net.sansa-stack</groupId>
        <artifactId>sansa-parent_2.12</artifactId>
        <version>0.8.0-RC3-SNAPSHOT</version>
    </parent>

    <artifactId>sansa-debian-spark-cli</artifactId>
    <packaging>jar</packaging>

    <properties>
        <deb.packageName>sansa-spark-cli</deb.packageName>
        <!-- <deb.jarFile>${project.artifactId}-${project.version}.jar</deb.jarFile> -->
        <!-- 		<deb.jarFile>${project.artifactId}-${project.version}-jar-with-dependencies.jar</deb.jarFile> -->
        <deb.jarFile>${project.artifactId}-${project.version}.jar</deb.jarFile>
    </properties>

    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>sansa-spark-cli_2.12</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-deploy-plugin</artifactId>
                <configuration>
                    <skip>true</skip>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.sonatype.plugins</groupId>
                <artifactId>nexus-staging-maven-plugin</artifactId>
                <configuration>
                    <skipNexusStagingDeployMojo>true</skipNexusStagingDeployMojo>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>deb</id>
            <activation>
                <property>
                    <name>deb</name>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-dependency-plugin</artifactId>
                    </plugin>

                    <plugin>
                        <artifactId>jdeb</artifactId>
                        <groupId>org.vafer</groupId>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>jdeb</goal>
                                </goals>
                                <configuration>
                                    <deb>${project.build.directory}/${deb.packageName}_[[version]]_all.deb</deb>
                                    <changesOut>${project.build.directory}/${deb.packageName}_[[version]]_all.changes
                                    </changesOut>

                                    <!-- <timestamped>true</timestamped> -->
                                    <snapshotExpand>true</snapshotExpand>
                                    <snapshotEnv/>

                                    <signPackage>${jdeb.signPackage}</signPackage>
                                    <signMethod>dpkg-sig</signMethod>
                                    <signRole>builder</signRole>
                                    <keyring>${jdeb.keyring}</keyring>
                                    <key>${jdeb.key}</key>
                                    <passphrase>${jdeb.passphrase}</passphrase>

                                    <dataSet>

                                        <!-- Uncomment for including an existing etc folder -->
                                        <!-- 								<data> -->
                                        <!-- 									<type>directory</type> -->
                                        <!-- 									<src>${basedir}/src/deb/resources/etc</src> -->
                                        <!-- 									<mapper> -->
                                        <!-- 										<type>perm</type> -->
                                        <!-- 										<prefix>/etc</prefix> -->
                                        <!-- 									</mapper> -->
                                        <!-- 								</data> -->

                                        <data>
                                            <type>directory</type>
                                            <src>${basedir}/src/deb/resources/usr/bin</src>
                                            <mapper>
                                                <type>perm</type>
                                                <prefix>/usr/bin</prefix>
                                                <filemode>755</filemode>
                                            </mapper>
                                        </data>

                                        <data>
                                            <type>file</type>
                                            <src>${project.build.directory}/${deb.jarFile}</src>
                                            <mapper>
                                                <type>perm</type>
                                                <prefix>/usr/share/lib/${deb.packageName}</prefix>
                                            </mapper>
                                        </data>

                                        <data>
                                            <type>directory</type>
                                            <src>${project.build.directory}/lib</src>
                                            <mapper>
                                                <type>perm</type>
                                                <prefix>/usr/share/lib/${deb.packageName}/lib</prefix>
                                                <filemode>755</filemode>
                                            </mapper>
                                        </data>

                                        <data>
                                            <type>link</type>
                                            <symlink>true</symlink>
                                            <linkName>/usr/share/lib/${deb.packageName}/${deb.packageName}.jar
                                            </linkName>
                                            <linkTarget>/usr/share/lib/${deb.packageName}/${deb.jarFile}</linkTarget>
                                        </data>

                                        <!-- <data> <type>file</type> <src>${basedir}/../sparqlify-core/target/sparqlify-core-${version}.jar</src>
                                            <mapper> <type>perm</type> <prefix>/usr/share/lib/${deb.packageName}</prefix>
                                            </mapper> </data> -->
                                        <!-- <data> <type>file</type> <src>${project.build.directory}/${project.build.finalName}.jar</src>
                                            <mapper> <type>perm</type> <prefix>/usr/share/lib/${deb.packageName}</prefix>
                                            </mapper> </data> -->
                                    </dataSet>

                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
#ifndef ANDROID_IMEDIAMETADATARETRIEVER_H
#define ANDROID_IMEDIAMETADATARETRIEVER_H

#include <utils/RefBase.h>
#include <binder/IInterface.h>
#include <binder/Parcel.h>
#include <binder/IMemory.h>

namespace android {

class IMediaMetadataRetriever: public IInterface
{
public:
    DECLARE_META_INTERFACE(MediaMetadataRetriever);
    virtual void            disconnect() = 0;
    virtual status_t        setDataSource(const char* srcUrl) = 0;
    virtual status_t        setDataSource(int fd, int64_t offset, int64_t length) = 0;
    virtual sp<IMemory>     getFrameAtTime(int64_t timeUs, int option) = 0;
    virtual sp<IMemory>     extractAlbumArt() = 0;
    virtual const char*     extractMetadata(int keyCode) = 0;
};

// ----------------------------------------------------------------------------

class BnMediaMetadataRetriever: public BnInterface<IMediaMetadataRetriever>
{
public:
    virtual status_t    onTransact(uint32_t code,
                                   const Parcel& data,
                                   Parcel* reply,
                                   uint32_t flags = 0);
};

}; // namespace android

#endif // ANDROID_IMEDIAMETADATARETRIEVER_H


text:
process.env.NODE_ENV="test"; // environment test

let mongoose = require("mongoose");
let Schema = mongoose.Schema;

let chai = require('chai');
let chaiHttp = require('chai-http');
let should = chai.should();
chai.use(chaiHttp);

let server = require('../bin/buda-front');
let api_home = "localhost:" + server.config.port;

let testCollection = "tests";
let testCollectionSize = 50;
let validDocId;

describe("BUDA API FRONT TESTS", function(){

	before(function(done){
		let testSchema = new Schema({
			name: { type: String, required: true },
			description: { type: String, required: false },
			data: [
				{
					alphabet: [{value: String, anotherValue: [Number]}],
				}
			],
			meta: {
				tags: [String]
			}
		});

		let testModel = mongoose.model(testCollection, testSchema);

		var schema;
		var tagsOptions = ["apple", "banana", "grape", "orange", "avocado", "strawberry", "peaches"]
		for(let i = 0; i < testCollectionSize; i++){
			schema = {
				name: "test_" + i,
				description: String(i%2),
				data: [],
				meta: {
					tags: []
				}
			}

			for( let j = 0; j < parseInt(Math.random()*10); j++){
				schema.data.push({
					alphabet: []
				});

				for( let k = 0; k < parseInt(Math.random()*10); k++){
					schema.data[j].alphabet.push({value: String(k), anotherValue: [j, k, i]});
				}
			}

			for( let j = 0; j < parseInt(Math.random()*3); j++){
				schema.meta.tags.push( tagsOptions[parseInt(Math.random()*tagsOptions.length)] );
			}

			new testModel(schema).save(function(err, doc){
				if(!validDocId){
					validDocId = String(doc["_id"]);
				}
			});
		}

		done();
	});

	afterEach(function(){console.log("");});

	describe("CRUD OPERATIONS", function(){
		this.timeout(10000);

		// get all
		describe('/GET ', function(){
			it('it should GET a list of records with length of ' + testCollectionSize, function(done){
				chai.request(api_home)
					.get('/v1/' + testCollection)
					.end(function(err, res){
						res.should.have.status(200);
						res.body.should.be.a('object').have.property("results").be.a("array");
						res.body.results.should.have.lengthOf(testCollectionSize);

						done();
					});
			});
		});

		// get one
		describe('/GET/:docId ', function(){
			it('it should GET one record', function(done){
				chai.request(api_home)
					.get('/v1/' + testCollection + '/' + validDocId )
					.end(function(err, res){
						res.should.have.status(200);
						res.body.should.be.a('object').have.property("_id").eql(validDocId);

						done();
					});
			});
		});

		// insert
		describe('/POST ', function() {
			it('it should return error code 403 - Forbidden', function(done) {
				chai.request(api_home)
					.post('/v1/' + testCollection).send({name:"value"})
					.end(function(err, res){
						res.should.have.status(403);
						res.body.should.have.property("error").eql("Forbidden");

						done();
					});
			});
		});

		// update PUT
		describe('/PUT/:docId ', function(){
			it('it should return error code 403 - Forbidden', function(done){

				chai.request(api_home)
					.put('/v1/' + testCollection + '/' + validDocId)
					.send({another_value:"put_value"})
					.end(function(err, res){
						res.should.have.status(403);
						res.body.should.have.property("error").eql("Forbidden");

						done();
					});
			});
		});

		// update PATCH
		describe('/PATCH/:docId ', function(){
			it('it should return error code 403 - Forbidden', function(done){

				chai.request(api_home)
					.patch('/v1/' + testCollection + '/' + validDocId)
					.send({another_value:"patch_value"})
					.end(function(err, res){
						res.should.have.status(403);
						res.body.should.have.property("error").eql("Forbidden");
						done();
					});
			});
		});

		describe('/DELETE/:docId ', function(){
			it('it should return error code 403 - Forbidden', function(done) {

				chai.request(api_home)
					.delete('/v1/' + testCollection + '/' + validDocId)
					.end(function(err, res){
						res.should.have.status(403);
						res.body.should.have.property("error").eql("Forbidden");

						done();
					});
			});
		});
	});

	describe("FILTERS", function(){
		this.timeout(10000);

		describe("/GET recursive search key=[x, value, y, z]", function(){
			it('it should GET a list of records with at the array defined by key containing at least one time the value', function(done){

				let valueToFind = "peaches";
				chai.request(api_home)
					.get('/v1/' + testCollection)
					.query({"tags": valueToFind, "recursiveSearch": 1})
					.end(function(err, res){
						res.should.have.status(200);
						res.body.should.be.a('object').have.property("results").be.a("array");

						for(var i = 0; i < res.body.results.length; i++){
							res.body.results[i].meta.tags.should.contains(valueToFind);
						}

						done();
					});
			});
		});

		describe('/GET key=[x, value, y, z]', function() {
			it('it should GET a list of records with at the array defined by key containing at least one time the value', function(done) {

				let valueToFind = "peaches";
				chai.request(api_home)
					.get('/v1/' + testCollection)
					.query({"meta.tags": valueToFind})
					.end(function(err, res){
						res.should.have.status(200);
						res.body.should.be.a('object').have.property("results").be.a("array");

						for(var i = 0; i < res.body.results.length; i++){
							res.body.results[i].meta.tags.should.contains(valueToFind);
						}

						done();
					});
			});
		});

		describe('/GET nested search obj[key]=value', function() {
			it('it should GET a list of records with at least one pair key=value', function(done){

				let valueToFind = "3";
				chai.request(api_home)
				.get('/v1/' + testCollection)
				.query({value: valueToFind, recursiveSearch: 1})
				.end(function(err, res){
					res.should.have.status(200);
					res.body.should.be.a('object').have.property("results").be.a("array");

					var isValid;
					resultsLoop:
					for(var i = 0; i < res.body.results.length; i++){
						isValid = false;

						dataLoop:
						for(var j = 0; j < res.body.results[i].data.length; j++){
							valueLoop:
							for(var k = 0; k < res.body.results[i].data[j].alphabet.length; k++){
								if(res.body.results[i].data[j].alphabet[k].value == valueToFind){
									isValid = true;
									break dataLoop;
								}
							}
						}

						isValid.should.be.ok;
					}

					done();
				});
			});
		});

	});

	describe("CRUD OPERATIONS WITH WRONG PARAMS", function(){
		this.timeout(10000);

		// bad collection
		describe('/GET notValidCollection', function() {
			it('it should GET a empty list of records', function(done){

				chai.request(api_home)
					.get('/v1/notValidCollection')
					.end(function(err, res) {
						res.should.have.status(200);
						res.body.should.be.a('object').have.property("results");
						res.body.results.length.should.be.eql(0);

						done();
					});
			});
		});

		// bad document
		describe('/GET/:docId notValidCollection', function() {
			it('it should return an INVALID_DOCUMENT_ID error', function(done) {

				chai.request(api_home)
					.get('/v1/notValidCollection/notValidDocument')
					.end(function(err, res) {
						res.should.have.status(400);
						res.body.should.have.property("error").eql("INVALID_DOCUMENT_ID");

						done();
					});
			});
		});

		// insert without data
		describe('/POST notValidCollection', function(){
			it('it should return error code 403 - Forbidden', function(done) {
				chai.request(api_home)
					.post('/v1/notValidCollection')
					.end(function(err, res){
						res.should.have.status(403);
						res.body.should.have.property("error").eql("Forbidden");

						done();
					});
			});
		});

		// update with wrong id
		describe('/PUT/:docId notValidCollection', function() {
			it('it should return error code 403 - Forbidden', function(done) {

				chai.request(api_home)
					.put('/v1/notValidCollection/notValidDocument').send({"name":"put_value"})
					.end(function(err, res) {
						res.should.have.status(403);
						res.body.should.have.property("error").eql("Forbidden");
						done();
					});
			});
		});

		// update without id
		describe('/PUT notValidCollection', function() {
			it('it should return an INVALID_PATH error and status code 404', function(done) {

				chai.request(api_home)
					.put('/v1/notValidCollection/').send({"name":"put_value"})
					.end(function(err, res) {
						res.should.have.status(404);
						res.body.should.have.property("error").eql("INVALID_PATH");
						done();
					});
			});
		});

		describe('/PATCH/:docId notValidCollection', function() {
			it('it should return error code 403 - Forbidden', function(done) {

				chai.request(api_home)
					.patch('/v1/notValidCollection/notValidDocument').send({"name":"put_value"})
					.end(function(err, res) {
						res.should.have.status(403);
						res.body.should.have.property("error").eql("Forbidden");
						done();
					});
			});
		});

		describe('/PATCH notValidCollection', function() {
			it('it should return an INVALID_PATH error and status code 404', function(done) {

				chai.request(api_home)
					.patch('/v1/notValidCollection/').send({"name":"put_value"})
					.end(function(err, res) {
						res.should.have.status(404);
						res.body.should.have.property("error").eql("INVALID_PATH");
						done();
					});
			});
		});

		describe('/DELETE/:docId notValidCollection', function() {
			it('it should return error code 403 - Forbidden', function(done) {

				chai.request(api_home)
					.delete('/v1/notValidCollection/notValidDocument')
					.end(function(err, res) {
						res.should.have.status(403);
						res.body.should.have.property("error").eql("Forbidden");
						done();
					});
			});
		});

		describe('/DELETE notValidCollection', function() {
			it('it should return an INVALID_PATH error and status code 404', function(done) {

				chai.request(api_home)
					.delete('/v1/notValidCollection')
					.end(function(err, res) {
						res.should.have.status(404);
						res.body.should.have.property("error");
						done();
					});
			});
		});

	});

	after(function(){
		mongoose.connection.db.dropCollection(testCollection);
	});
});


text:
package org.jmemcached.network;

public class DataException extends NetworkException {
	private static final long serialVersionUID = -1951325934693587672L;

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

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

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


text:
<?php

namespace Torchbox\Thankq\Api;

class doGiftAidUpdate
{

    /**
     * @var esitWSdoGiftAidUpdateArgument $doGiftAidUpdateArgument
     */
    protected $doGiftAidUpdateArgument = null;

    /**
     * @param esitWSdoGiftAidUpdateArgument $doGiftAidUpdateArgument
     */
    public function __construct($doGiftAidUpdateArgument)
    {
      $this->doGiftAidUpdateArgument = $doGiftAidUpdateArgument;
    }

    /**
     * @return esitWSdoGiftAidUpdateArgument
     */
    public function getDoGiftAidUpdateArgument()
    {
      return $this->doGiftAidUpdateArgument;
    }

    /**
     * @param esitWSdoGiftAidUpdateArgument $doGiftAidUpdateArgument
     * @return \Torchbox\Thankq\Api\doGiftAidUpdate
     */
    public function setDoGiftAidUpdateArgument($doGiftAidUpdateArgument)
    {
      $this->doGiftAidUpdateArgument = $doGiftAidUpdateArgument;
      return $this;
    }

}


text:
define([
  'app',
  'framework',
  './view'
],
function(App, Framework, Views) {
  var Widget = Framework.BaseWidget.extend({
    initialize: function(options) {
      return new Views.MenuView(options);
    }
  });
  return Widget;
});