text:
package com.vmware.xenon.services.common;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicInteger;

import com.google.gson.JsonObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.vmware.xenon.common.CommandLineArgumentParser;
import com.vmware.xenon.common.FileUtils;
import com.vmware.xenon.common.Operation;
import com.vmware.xenon.common.ServiceDocument;
import com.vmware.xenon.common.ServiceDocumentDescription;
import com.vmware.xenon.common.ServiceHost.Arguments;
import com.vmware.xenon.common.UriUtils;
import com.vmware.xenon.common.Utils;
import com.vmware.xenon.common.test.TestContext;
import com.vmware.xenon.common.test.TestNodeGroupManager;
import com.vmware.xenon.common.test.VerificationHost;
import com.vmware.xenon.services.common.ExampleService.ExampleServiceState;

/**
 * This test will not run unless xenon.sandboxRoot is defined. It is meant to be run from CI or manually when making
 * changes to the low level aspects like serialization, file management, configuration, etc.
 *
 */
public class TestSandboxCompatibility {

    /** Store case files. One json file in this directory stores a single case. */
    private Path casesDir;

    private List<VerificationHost> hosts;

    private final AtomicInteger caseCounter = new AtomicInteger();

    /** Links needed to be available before tests proceed. */
    private List<String> services;

    public static class FindForLink {
        public String selfLink;
        public JsonObject json;
        public String documentClass;

        private transient ServiceDocument document;

        FindForLink() {
            // serialization constructor
        }

        public FindForLink(ServiceDocument document) {
            this.selfLink = document.documentSelfLink;
            String s = Utils.toJson(document);
            this.json = Utils.fromJson(s, JsonObject.class);
            this.documentClass = document.getClass().getName();
        }

        @SuppressWarnings("unchecked")
        public Class<ServiceDocument> getDocumentClass() throws ClassNotFoundException {
            return (Class<ServiceDocument>) Thread.currentThread().getContextClassLoader()
                    .loadClass(this.documentClass);
        }

        public ServiceDocument getDocument() throws ClassNotFoundException {
            if (this.document == null) {
                Class<ServiceDocument> cls = getDocumentClass();
                this.document = Utils.fromJson(this.json, cls);
            }

            return this.document;
        }
    }

    /** Workdir for all in-process hosts. If not set test will exit immediately with success. */
    public Path sandboxRoot;

    public int nodeCount = 3;

    public int requestCount = 50;

    @Before
    public void setup() throws Throwable {
        CommandLineArgumentParser.parseFromProperties(this);
        this.hosts = new ArrayList<>();

        // add links to services we are interested in in order to wait for them to start
        this.services = new ArrayList<>();
        this.services.add(ExampleService.FACTORY_LINK);
    }

    @After
    public void tearDown() {
        for (VerificationHost host : this.hosts) {
            host.stop();
        }
    }

    private void startHosts() throws Throwable {
        for (int i = 0; i < this.nodeCount; i++) {
            Arguments args = new Arguments();
            args.port = 0;
            args.id = "node-" + i;
            args.sandbox = this.sandboxRoot.resolve(args.id);

            VerificationHost h = VerificationHost.create(args);
            h.start();

            startServicesOnHost(h);
            this.hosts.add(h);
        }

        joinNodesAndVerifyConvergence();

        for (VerificationHost host : this.hosts) {
            TestContext ctx = host.testCreate(this.services.size());
            host.registerForServiceAvailability(ctx.getCompletion(), true, this.services.toArray(new String[] {}));
            ctx.await();
        }
    }

    private void startServicesOnHost(VerificationHost h) throws IOException {
        // TODO start services that go through edge cases in json/kryo/etc.
    }

    private void joinNodesAndVerifyConvergence() throws Throwable {
        TestNodeGroupManager manager = new TestNodeGroupManager(ServiceUriPaths.DEFAULT_NODE_GROUP_NAME);
        manager.addHosts(new ArrayList<>(this.hosts));
        manager.joinNodeGroupAndWaitForConvergence();
    }

    private void createSandboxDirectories() throws IOException {
        Files.createDirectories(this.sandboxRoot);
        this.casesDir = this.sandboxRoot.resolve("cases");
        Files.createDirectories(this.casesDir);
    }

    private VerificationHost getHost() {
        return this.hosts.get(ThreadLocalRandom.current().nextInt(this.hosts.size()));
    }

    private void saveCase(FindForLink obj) throws IOException {
        Path p = this.casesDir.resolve("case-" + this.caseCounter.incrementAndGet() + ".json");
        Files.write(p, Utils.toJsonHtml(obj).getBytes(Utils.CHARSET));
    }

    private void checkSavedCases() throws Exception {
        File[] caseFiles = this.casesDir.toFile().listFiles(f -> f.getName().endsWith(".json"));
        if (caseFiles == null) {
            return;
        }

        for (File json : caseFiles) {
            byte[] contents = Files.readAllBytes(json.toPath());
            FindForLink ffl = Utils.fromJson(new String(contents, Utils.CHARSET), FindForLink.class);
            assertSavedStateMatchesFetched(ffl);
        }
    }

    private void assertSavedStateMatchesFetched(FindForLink ffl) throws Exception {
        VerificationHost host = getHost();

        Operation op = Operation.createGet(host, ffl.selfLink);

        host.log("Checking service %s", ffl.selfLink);
        op = host.waitForResponse(op);
        assertEquals(Operation.STATUS_CODE_OK, op.getStatusCode());

        ServiceDocument fetchedDoc = op.getBody(ffl.getDocumentClass());
        ServiceDocument originalDoc = ffl.getDocument();

        ServiceDocumentDescription desc = host.buildDescription(originalDoc.getClass());

        String s1 = Utils.computeSignature(fetchedDoc, desc);
        String s2 = Utils.computeSignature(originalDoc, desc);

        if (!s1.equals(s2)) {
            String msg = "A document from the sandbox has different signature after upgrade" + ffl.selfLink;
            host.log("Expected: %s, got %s", Utils.toJson(originalDoc), Utils.toJson(fetchedDoc));
            fail(msg);
        }
    }

    private void createServicesAndSaveCases() throws IOException {
        for (int i = 0; i < this.requestCount; i++) {
            VerificationHost host = getHost();
            ExampleServiceState state = new ExampleServiceState();
            state.name = UUID.randomUUID().toString();
            state.id = UUID.randomUUID().toString();
            state.counter = System.currentTimeMillis();
            state.sortedCounter = state.counter + 1;
            state.keyValues = new HashMap<>();
            state.keyValues.put(state.name, state.name);
            state.keyValues.put(state.id, state.id);
            Operation op = Operation.createPost(UriUtils.buildFactoryUri(host, ExampleService.class))
                    .setBody(state);

            op = host.waitForResponse(op);

            saveCase(new FindForLink(op.getBody(ExampleServiceState.class)));
        }
    }

    /**
     * Given a correct {@link #sandboxRoot} this method will start the hosts again and check the retrieved
     * services' state match the saved state.
     * @throws Throwable
     */
    @Test
    public void resumeFromSandbox() throws Throwable {
        if (this.sandboxRoot == null) {
            return;
        }

        createSandboxDirectories();

        startHosts();

        checkSavedCases();
    }

    /**
     * When run this methods creates {@link #nodeCount} local in-process nodes and put their sandboxes in
     * {@link #sandboxRoot}. Several services are created and their contents written to a separate json file each in
     * sandboxRoot/cases
     *
     * @throws Throwable
     */
    @Test
    public void createSandbox() throws Throwable {
        if (this.sandboxRoot == null) {
            return;
        }
        try {
            FileUtils.deleteFiles(this.sandboxRoot.toFile());
        } catch (Exception ignore) {

        }

        createSandboxDirectories();

        startHosts();

        createServicesAndSaveCases();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package manifest1

import (
	"fmt"
	"strings"
)

func (m *Manifest) Push(template, app, build string, stream Stream) error {
	services, err := m.runOrder("")
	if err != nil {
		return err
	}

	for _, s := range services {
		local := fmt.Sprintf("%s/%s", app, s.Name)

		remote := template
		remote = strings.Replace(remote, "{service}", s.Name, -1)
		remote = strings.Replace(remote, "{build}", build, -1)

		if err := DefaultRunner.Run(stream, Docker("tag", local, remote), RunnerOptions{Verbose: true}); err != nil {
			return err
		}

		if err := DefaultRunner.Run(stream, Docker("push", remote), RunnerOptions{Verbose: true}); err != nil {
			return err
		}
	}

	return nil
}


text:
package org.apache.activemq.artemis.tests.integration.vertx;

import java.util.HashMap;

import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.client.ClientConsumer;
import org.apache.activemq.artemis.api.core.client.ClientMessage;
import org.apache.activemq.artemis.api.core.client.ClientSession;
import org.apache.activemq.artemis.api.core.client.ClientSessionFactory;
import org.apache.activemq.artemis.api.core.client.ServerLocator;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.config.ConnectorServiceConfiguration;
import org.apache.activemq.artemis.core.config.CoreQueueConfiguration;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.integration.vertx.VertxConstants;
import org.apache.activemq.artemis.integration.vertx.VertxIncomingConnectorServiceFactory;
import org.apache.activemq.artemis.integration.vertx.VertxOutgoingConnectorServiceFactory;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.eventbus.impl.BaseMessage;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import org.vertx.java.platform.PlatformLocator;
import org.vertx.java.platform.PlatformManager;
import org.vertx.java.spi.cluster.impl.hazelcast.HazelcastClusterManagerFactory;

/**
 * This class tests the basics of ActiveMQ
 * vertx integration
 */
public class ActiveMQVertxUnitTest extends ActiveMQTestBase
{
   protected PlatformManager vertxManager;
   protected ActiveMQServer server;

   protected String host = "localhost";
   protected String port = "0";

   protected String incomingQueue1 = "vertxTestIncomingQueue1";
   protected String incomingVertxAddress1 = "org.apache.activemq.test.incoming1";

   //outgoing using send
   protected String inOutQueue1 = "vertxTestInOutQueue1";
   protected String incomingVertxAddress2 = "org.apache.activemq.test.incoming2";
   protected String outgoingVertxAddress1 = "org.apache.activemq.test.outgoing1";

   //outgoing using publish
   protected String inOutQueue2 = "vertxTestInOutQueue2";
   protected String incomingVertxAddress3 = "org.apache.activemq.test.incoming3";
   protected String outgoingVertxAddress2 = "org.apache.activemq.test.outgoing2";

   // Vertx is changing the classLoader to null.. this will preserve the original classloader
   ClassLoader contextClassLoader;

   //subclasses may override this method
   //in order to get a server with different connector services
   @Before @Override
   public void setUp() throws Exception
   {
      contextClassLoader = Thread.currentThread().getContextClassLoader();
      createVertxService();

      super.setUp();
      //all queues
      CoreQueueConfiguration qc1 = new CoreQueueConfiguration()
         .setAddress(incomingQueue1)
         .setName(incomingQueue1);
      CoreQueueConfiguration qc2 = new CoreQueueConfiguration()
         .setAddress(inOutQueue1)
         .setName(inOutQueue1);
      CoreQueueConfiguration qc3 = new CoreQueueConfiguration()
         .setAddress(inOutQueue2)
         .setName(inOutQueue2);

      //incoming
      HashMap<String, Object> config1 = new HashMap<String, Object>();
      config1.put(VertxConstants.HOST, host);
      config1.put(VertxConstants.PORT, port);
      config1.put(VertxConstants.QUEUE_NAME, incomingQueue1);
      config1.put(VertxConstants.VERTX_ADDRESS, incomingVertxAddress1);

      ConnectorServiceConfiguration inconf1 = new ConnectorServiceConfiguration()
         .setFactoryClassName(VertxIncomingConnectorServiceFactory.class.getName())
         .setParams(config1)
         .setName("test-vertx-incoming-connector1");

      //outgoing send style
      HashMap<String, Object> config2 = new HashMap<String, Object>();
      config2.put(VertxConstants.HOST, host);
      config2.put(VertxConstants.PORT, port);
      config2.put(VertxConstants.QUEUE_NAME, inOutQueue1);
      config2.put(VertxConstants.VERTX_ADDRESS, incomingVertxAddress2);

      ConnectorServiceConfiguration inconf2 = new ConnectorServiceConfiguration()
         .setFactoryClassName(VertxIncomingConnectorServiceFactory.class.getName())
         .setParams(config2)
         .setName("test-vertx-incoming-connector2");

      HashMap<String, Object> config3 = new HashMap<String, Object>();
      config3.put(VertxConstants.HOST, host);
      config3.put(VertxConstants.PORT, port);
      config3.put(VertxConstants.QUEUE_NAME, inOutQueue1);
      config3.put(VertxConstants.VERTX_ADDRESS, outgoingVertxAddress1);

      ConnectorServiceConfiguration outconf1 = new ConnectorServiceConfiguration()
         .setFactoryClassName(VertxOutgoingConnectorServiceFactory.class.getName())
         .setParams(config3)
         .setName("test-vertx-outgoing-connector1");

      //outgoing publish style
      HashMap<String, Object> config4 = new HashMap<String, Object>();
      config4.put(VertxConstants.HOST, host);
      config4.put(VertxConstants.PORT, port);
      config4.put(VertxConstants.QUEUE_NAME, inOutQueue2);
      config4.put(VertxConstants.VERTX_ADDRESS, incomingVertxAddress3);

      ConnectorServiceConfiguration inconf3 = new ConnectorServiceConfiguration()
         .setFactoryClassName(VertxIncomingConnectorServiceFactory.class.getName())
         .setParams(config4)
         .setName("test-vertx-incoming-connector3");

      HashMap<String, Object> config5 = new HashMap<String, Object>();
      config5.put(VertxConstants.HOST, host);
      config5.put(VertxConstants.PORT, port);
      config5.put(VertxConstants.QUEUE_NAME, inOutQueue2);
      config5.put(VertxConstants.VERTX_ADDRESS, outgoingVertxAddress2);
      config5.put(VertxConstants.VERTX_PUBLISH, "true");

      ConnectorServiceConfiguration outconf2 = new ConnectorServiceConfiguration()
         .setFactoryClassName(VertxOutgoingConnectorServiceFactory.class.getName())
         .setParams(config5)
         .setName("test-vertx-outgoing-connector2");

      Configuration configuration = createDefaultInVMConfig()
         .addQueueConfiguration(qc1)
         .addQueueConfiguration(qc2)
         .addQueueConfiguration(qc3)
         .addConnectorServiceConfiguration(inconf1)
         .addConnectorServiceConfiguration(inconf2)
         .addConnectorServiceConfiguration(outconf1)
         .addConnectorServiceConfiguration(inconf3)
         .addConnectorServiceConfiguration(outconf2);

      server = createServer(false, configuration);
      server.start();
   }

   /**
    * (vertx events) ===> (incomingQueue1) ===> (activemq consumer)
    * @throws Exception
    */
   @Test
   public void testIncomingEvents() throws Exception
   {
      Vertx vertx = vertxManager.vertx();

      //send a string message
      String greeting = "Hello World!";
      vertx.eventBus().send(incomingVertxAddress1, greeting);

      ClientMessage msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      System.out.println("==== received msg: " + msg);

      int vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_STRING, vertxType);

      String body = msg.getBodyBuffer().readString();
      System.out.println("==== body: " + body);

      assertEquals(greeting, body);

      //send a Buffer message
      final byte[] content = greeting.getBytes("UTF-8");
      Buffer buffer = new Buffer(content);
      vertx.eventBus().send(incomingVertxAddress1, buffer);

      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_BUFFER, vertxType);

      ActiveMQBuffer activeMQBuffer = msg.getBodyBuffer();
      int len = activeMQBuffer.readInt();
      System.out.println("==== len is: " + len);
      assertEquals(content.length, len);
      byte[] bytes = new byte[len];
      activeMQBuffer.readBytes(bytes);

      //bytes must match
      for (int i = 0; i < len; i++)
      {
         assertEquals(content[i], bytes[i]);
      }

      //send a boolean
      vertx.eventBus().send(incomingVertxAddress1, Boolean.TRUE);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_BOOLEAN, vertxType);

      Boolean booleanValue = msg.getBodyBuffer().readBoolean();
      assertEquals(Boolean.TRUE, booleanValue);

      //send a byte array
      vertx.eventBus().send(incomingVertxAddress1, content);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_BYTEARRAY, vertxType);

      len = msg.getBodyBuffer().readInt();
      byte[] recvBytes = new byte[len];
      msg.getBodyBuffer().readBytes(recvBytes);
      //bytes must match
      for (int i = 0; i < len; i++)
      {
         assertEquals(content[i], recvBytes[i]);
      }

      //send a byte
      Byte aByte = new Byte((byte)15);
      vertx.eventBus().send(incomingVertxAddress1, aByte);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_BYTE, vertxType);

      Byte recvByte = msg.getBodyBuffer().readByte();
      assertEquals(aByte, recvByte);

      //send a Character
      Character aChar = new Character('a');
      vertx.eventBus().send(incomingVertxAddress1, aChar);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_CHARACTER, vertxType);
      Character recvChar = msg.getBodyBuffer().readChar();
      assertEquals(aChar, recvChar);

      //send a Double
      Double aDouble = new Double(1234.56d);
      vertx.eventBus().send(incomingVertxAddress1, aDouble);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_DOUBLE, vertxType);
      Double recvDouble = msg.getBodyBuffer().readDouble();
      assertEquals(aDouble, recvDouble);

      //send a Float
      Float aFloat = new Float(1234.56f);
      vertx.eventBus().send(incomingVertxAddress1, aFloat);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_FLOAT, vertxType);
      Float recvFloat = msg.getBodyBuffer().readFloat();
      assertEquals(aFloat, recvFloat);

      //send a Integer
      Integer aInt = new Integer(1234);
      vertx.eventBus().send(incomingVertxAddress1, aInt);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_INT, vertxType);
      Integer recvInt = msg.getBodyBuffer().readInt();
      assertEquals(aInt, recvInt);

      //send a Long
      Long aLong = new Long(12345678L);
      vertx.eventBus().send(incomingVertxAddress1, aLong);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_LONG, vertxType);
      Long recvLong = msg.getBodyBuffer().readLong();
      assertEquals(aLong, recvLong);

      //send a Short
      Short aShort = new Short((short)321);
      vertx.eventBus().send(incomingVertxAddress1, aShort);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_SHORT, vertxType);
      Short recvShort = msg.getBodyBuffer().readShort();
      assertEquals(aShort, recvShort);

      //send a JsonObject
      String jsonObjectString = "{\n" +
                                "\"Image\": {\n" +
                                "\"Width\":  800,\n" +
                                "\"Height\": 600,\n" +
                                "\"Title\":  \"View from 15th Floor\",\n" +
                                "\"Thumbnail\": {\n" +
                                "\"Url\":    \"http://www.example.com/image/481989943\",\n" +
                                "\"Height\": 125,\n" +
                                "\"Width\":  100\n" +
                                "},\n" +
                                "\"IDs\": [116, 943, 234, 38793]\n" +
                                "}\n" +
                                "}";
      JsonObject aJsonObj = new JsonObject(jsonObjectString);
      vertx.eventBus().send(incomingVertxAddress1, aJsonObj);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_JSON_OBJECT, vertxType);
      String recvJsonString = msg.getBodyBuffer().readString();
      System.out.println("==== received json: " + recvJsonString);
      assertEquals(aJsonObj, new JsonObject(recvJsonString));

      //send a JsonArray
      String jsonArrayString = "[\n" +
                                "{\n" +
                                "\"precision\": \"zip\",\n" +
                                "\"Latitude\":  37.7668,\n" +
                                "\"Longitude\": -122.3959,\n" +
                                "\"Address\":   \"\",\n" +
                                "\"City\":      \"SAN FRANCISCO\",\n" +
                                "\"State\":     \"CA\",\n" +
                                "\"Zip\":       \"94107\",\n" +
                                "\"Country\":   \"US\"\n" +
                                "},\n" +
                                "{\n" +
                                "\"precision\": \"zip\",\n" +
                                "\"Latitude\":  37.371991,\n" +
                                "\"Longitude\": -122.026020,\n" +
                                "\"Address\":   \"\",\n" +
                                "\"City\":      \"SUNNYVALE\",\n" +
                                "\"State\":     \"CA\",\n" +
                                "\"Zip\":       \"94085\",\n" +
                                "\"Country\":   \"US\"\n" +
                                "}\n" +
                                "]";
      JsonArray aJsonArray = new JsonArray(jsonArrayString);
      System.out.println("a json array string: " + aJsonArray);
      vertx.eventBus().send(incomingVertxAddress1, aJsonArray);

      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_JSON_ARRAY, vertxType);
      recvJsonString = msg.getBodyBuffer().readString();
      System.out.println("==== received json: " + recvJsonString);
      assertEquals(aJsonArray, new JsonArray(recvJsonString));

      //send a ReplyFailure
      /*
      ReplyFailure replyFailure = ReplyFailure.TIMEOUT;
      int fakeFailureCode = 1234;
      String failureMsg = "Test failure message";
      ReplyException aReplyEx = new ReplyException(replyFailure, fakeFailureCode, failureMsg);
      vertx.eventBus().send(incomingVertxAddress1, aReplyEx);
      msg = receiveFromQueue(incomingQueue1);
      assertNotNull(msg);
      vertxType = msg.getIntProperty(VertxConstants.VERTX_MESSAGE_TYPE);
      assertEquals(VertxConstants.TYPE_REPLY_FAILURE, vertxType);
      int recvType = msg.getBodyBuffer().readInt();
      int recvCode = msg.getBodyBuffer().readInt();
      String recvFailureMsg = msg.getBodyBuffer().readString();
      assertEquals(replyFailure.toInt(), recvType);
      assertEquals(fakeFailureCode, recvCode);
      assertEquals(failureMsg, recvFailureMsg);
      */
   }

   /**
    * vertx events (incomingVertxAddress2)
    * ===> (inOutQueue1)
    * ===> (outgoing handler)
    * ===> send to vertx (outgoingVertxAddress1)
    * @throws Exception
    */
   @Test
   public void testOutgoingEvents() throws Exception
   {
      Vertx vertx = vertxManager.vertx();

      //regiser a handler to receive outgoing messages
      VertxTestHandler handler = new VertxTestHandler();
      vertx.eventBus().registerHandler(outgoingVertxAddress1, handler);

      //send a string message
      String greeting = "Hello World!";
      vertx.eventBus().send(incomingVertxAddress2, greeting);

      //check message in handler
      handler.checkStringMessageReceived(greeting);

      //send a Buffer message
      final byte[] content = greeting.getBytes("UTF-8");
      Buffer buffer = new Buffer(content);
      vertx.eventBus().send(incomingVertxAddress2, buffer);

      handler.checkBufferMessageReceived(buffer);

      //send a boolean
      Boolean boolValue = Boolean.TRUE;
      vertx.eventBus().send(incomingVertxAddress2, boolValue);

      handler.checkBooleanMessageReceived(boolValue);

      byte[] byteArray = greeting.getBytes("UTF-8");
      vertx.eventBus().send(incomingVertxAddress2, byteArray);

      handler.checkByteArrayMessageReceived(byteArray);

      //send a byte
      Byte aByte = new Byte((byte)15);
      vertx.eventBus().send(incomingVertxAddress2, aByte);

      handler.checkByteMessageReceived(aByte);

      //send a Character
      Character aChar = new Character('a');
      vertx.eventBus().send(incomingVertxAddress2, aChar);

      handler.checkCharacterMessageReceived(aChar);

      //send a Double
      Double aDouble = new Double(1234.56d);
      vertx.eventBus().send(incomingVertxAddress2, aDouble);

      handler.checkDoubleMessageReceived(aDouble);

      //send a Float
      Float aFloat = new Float(1234.56f);
      vertx.eventBus().send(incomingVertxAddress2, aFloat);

      handler.checkFloatMessageReceived(aFloat);

      //send a Integer
      Integer aInt = new Integer(1234);
      vertx.eventBus().send(incomingVertxAddress2, aInt);

      handler.checkIntegerMessageReceived(aInt);

      //send a Long
      Long aLong = new Long(12345678L);
      vertx.eventBus().send(incomingVertxAddress2, aLong);

      handler.checkLongMessageReceived(aLong);

      //send a Short
      Short aShort = new Short((short)321);
      vertx.eventBus().send(incomingVertxAddress2, aShort);

      handler.checkShortMessageReceived(aShort);

      //send a JsonObject
      String jsonObjectString = "{\n" +
                                "\"Image\": {\n" +
                                "\"Width\":  800,\n" +
                                "\"Height\": 600,\n" +
                                "\"Title\":  \"View from 15th Floor\",\n" +
                                "\"Thumbnail\": {\n" +
                                "\"Url\":    \"http://www.example.com/image/481989943\",\n" +
                                "\"Height\": 125,\n" +
                                "\"Width\":  100\n" +
                                "},\n" +
                                "\"IDs\": [116, 943, 234, 38793]\n" +
                                "}\n" +
                                "}";
      JsonObject aJsonObj = new JsonObject(jsonObjectString);
      vertx.eventBus().send(incomingVertxAddress2, aJsonObj);

      handler.checkJsonObjectMessageReceived(aJsonObj);

      //send a JsonArray
      String jsonArrayString = "[\n" +
                                "{\n" +
                                "\"precision\": \"zip\",\n" +
                                "\"Latitude\":  37.7668,\n" +
                                "\"Longitude\": -122.3959,\n" +
                                "\"Address\":   \"\",\n" +
                                "\"City\":      \"SAN FRANCISCO\",\n" +
                                "\"State\":     \"CA\",\n" +
                                "\"Zip\":       \"94107\",\n" +
                                "\"Country\":   \"US\"\n" +
                                "},\n" +
                                "{\n" +
                                "\"precision\": \"zip\",\n" +
                                "\"Latitude\":  37.371991,\n" +
                                "\"Longitude\": -122.026020,\n" +
                                "\"Address\":   \"\",\n" +
                                "\"City\":      \"SUNNYVALE\",\n" +
                                "\"State\":     \"CA\",\n" +
                                "\"Zip\":       \"94085\",\n" +
                                "\"Country\":   \"US\"\n" +
                                "}\n" +
                                "]";
      JsonArray aJsonArray = new JsonArray(jsonArrayString);
      vertx.eventBus().send(incomingVertxAddress2, aJsonArray);

      handler.checkJsonArrayMessageReceived(aJsonArray);
   }

   /**
    * vertx events (incomingVertxAddress3)
    * ===> (inOutQueue2)
    * ===> (outgoing handler)
    * ===> public to vertx (outgoingVertxAddress2)
    * @throws Exception
    */
   @Test
   public void testOutgoingEvents2() throws Exception
   {
      Vertx vertx = vertxManager.vertx();

      //regiser two handlers to receive outgoing messages
      VertxTestHandler handler1 = new VertxTestHandler();
      vertx.eventBus().registerHandler(outgoingVertxAddress2, handler1);
      VertxTestHandler handler2 = new VertxTestHandler();
      vertx.eventBus().registerHandler(outgoingVertxAddress2, handler2);

      //send a string message
      String greeting = "Hello World!";
      vertx.eventBus().send(incomingVertxAddress3, greeting);

      //check message in handler
      handler1.checkStringMessageReceived(greeting);
      handler2.checkStringMessageReceived(greeting);

      //send a Buffer message
      final byte[] content = greeting.getBytes("UTF-8");
      Buffer buffer = new Buffer(content);
      vertx.eventBus().send(incomingVertxAddress3, buffer);

      handler1.checkBufferMessageReceived(buffer);
      handler2.checkBufferMessageReceived(buffer);

      //send a boolean
      Boolean boolValue = Boolean.TRUE;
      vertx.eventBus().send(incomingVertxAddress3, boolValue);

      handler1.checkBooleanMessageReceived(boolValue);
      handler2.checkBooleanMessageReceived(boolValue);

      byte[] byteArray = greeting.getBytes("UTF-8");
      vertx.eventBus().send(incomingVertxAddress3, byteArray);

      handler1.checkByteArrayMessageReceived(byteArray);
      handler2.checkByteArrayMessageReceived(byteArray);

      //send a byte
      Byte aByte = new Byte((byte)15);
      vertx.eventBus().send(incomingVertxAddress3, aByte);

      handler1.checkByteMessageReceived(aByte);
      handler2.checkByteMessageReceived(aByte);

      //send a Character
      Character aChar = new Character('a');
      vertx.eventBus().send(incomingVertxAddress3, aChar);

      handler1.checkCharacterMessageReceived(aChar);
      handler2.checkCharacterMessageReceived(aChar);

      //send a Double
      Double aDouble = new Double(1234.56d);
      vertx.eventBus().send(incomingVertxAddress3, aDouble);

      handler1.checkDoubleMessageReceived(aDouble);
      handler2.checkDoubleMessageReceived(aDouble);

      //send a Float
      Float aFloat = new Float(1234.56f);
      vertx.eventBus().send(incomingVertxAddress3, aFloat);

      handler1.checkFloatMessageReceived(aFloat);
      handler2.checkFloatMessageReceived(aFloat);

      //send a Integer
      Integer aInt = new Integer(1234);
      vertx.eventBus().send(incomingVertxAddress3, aInt);

      handler1.checkIntegerMessageReceived(aInt);
      handler2.checkIntegerMessageReceived(aInt);

      //send a Long
      Long aLong = new Long(12345678L);
      vertx.eventBus().send(incomingVertxAddress3, aLong);

      handler1.checkLongMessageReceived(aLong);
      handler2.checkLongMessageReceived(aLong);

      //send a Short
      Short aShort = new Short((short)321);
      vertx.eventBus().send(incomingVertxAddress3, aShort);

      handler1.checkShortMessageReceived(aShort);
      handler2.checkShortMessageReceived(aShort);

      //send a JsonObject
      String jsonObjectString = "{\n" +
                                "\"Image\": {\n" +
                                "\"Width\":  800,\n" +
                                "\"Height\": 600,\n" +
                                "\"Title\":  \"View from 15th Floor\",\n" +
                                "\"Thumbnail\": {\n" +
                                "\"Url\":    \"http://www.example.com/image/481989943\",\n" +
                                "\"Height\": 125,\n" +
                                "\"Width\":  100\n" +
                                "},\n" +
                                "\"IDs\": [116, 943, 234, 38793]\n" +
                                "}\n" +
                                "}";
      JsonObject aJsonObj = new JsonObject(jsonObjectString);
      vertx.eventBus().send(incomingVertxAddress3, aJsonObj);

      handler1.checkJsonObjectMessageReceived(aJsonObj);
      handler2.checkJsonObjectMessageReceived(aJsonObj);

      //send a JsonArray
      String jsonArrayString = "[\n" +
                                "{\n" +
                                "\"precision\": \"zip\",\n" +
                                "\"Latitude\":  37.7668,\n" +
                                "\"Longitude\": -122.3959,\n" +
                                "\"Address\":   \"\",\n" +
                                "\"City\":      \"SAN FRANCISCO\",\n" +
                                "\"State\":     \"CA\",\n" +
                                "\"Zip\":       \"94107\",\n" +
                                "\"Country\":   \"US\"\n" +
                                "},\n" +
                                "{\n" +
                                "\"precision\": \"zip\",\n" +
                                "\"Latitude\":  37.371991,\n" +
                                "\"Longitude\": -122.026020,\n" +
                                "\"Address\":   \"\",\n" +
                                "\"City\":      \"SUNNYVALE\",\n" +
                                "\"State\":     \"CA\",\n" +
                                "\"Zip\":       \"94085\",\n" +
                                "\"Country\":   \"US\"\n" +
                                "}\n" +
                                "]";
      JsonArray aJsonArray = new JsonArray(jsonArrayString);
      vertx.eventBus().send(incomingVertxAddress3, aJsonArray);

      handler1.checkJsonArrayMessageReceived(aJsonArray);
      handler2.checkJsonArrayMessageReceived(aJsonArray);

   }

   private ClientMessage receiveFromQueue(String queueName) throws Exception
   {
      ClientMessage msg = null;

      ServerLocator locator = null;
      ClientSessionFactory sf = null;
      ClientSession session = null;

      try
      {
         locator = createInVMNonHALocator();

         sf = createSessionFactory(locator);

         session = sf.createSession(false, true, true);
         ClientConsumer consumer = session.createConsumer(queueName);
         session.start();
         msg = consumer.receive(60 * 1000);
         msg.acknowledge();
      }
      finally
      {
         if (session != null)
         {
            session.commit();
            session.close();
         }
         if (sf != null) sf.close();
         if (locator != null) locator.close();
      }
      return msg;
   }

   private void createVertxService()
   {
      System.setProperty("vertx.clusterManagerFactory", HazelcastClusterManagerFactory.class.getName());
      vertxManager = PlatformLocator.factory.createPlatformManager(Integer.valueOf(port),
               host);

//      vertxManager = PlatformLocator.factory.createPlatformManager(Integer.valueOf(port),
//               host, quorumSize, haGroup + System.currentTimeMillis());
   }

   private class VertxTestHandler implements Handler<BaseMessage<?>>
   {
      private volatile BaseMessage<?> vertxMsg = null;
      private final Object lock = new Object();

      @Override
      public void handle(BaseMessage<?> arg0)
      {
         synchronized (lock)
         {
            vertxMsg = arg0;
            lock.notify();
         }
      }

      public void checkJsonArrayMessageReceived(JsonArray aJsonArray)
      {
         BaseMessage<?> msg = waitMessage();
         JsonArray body = (JsonArray)msg.body();
         assertEquals(aJsonArray, body);
      }

      public void checkJsonObjectMessageReceived(final JsonObject aJsonObj)
      {
         BaseMessage<?> msg = waitMessage();
         JsonObject body = (JsonObject)msg.body();
         assertEquals(aJsonObj, body);
      }

      public void checkShortMessageReceived(final Short aShort)
      {
         BaseMessage<?> msg = waitMessage();
         Short body = (Short)msg.body();
         assertEquals(aShort, body);
      }

      public void checkLongMessageReceived(final Long aLong)
      {
         BaseMessage<?> msg = waitMessage();
         Long body = (Long)msg.body();
         assertEquals(aLong, body);
      }

      public void checkIntegerMessageReceived(final Integer aInt)
      {
         BaseMessage<?> msg = waitMessage();
         Integer body = (Integer)msg.body();
         assertEquals(aInt, body);
      }

      public void checkFloatMessageReceived(final Float aFloat)
      {
         BaseMessage<?> msg = waitMessage();
         Float body = (Float)msg.body();
         assertEquals(aFloat, body);
      }

      public void checkDoubleMessageReceived(final Double aDouble)
      {
         BaseMessage<?> msg = waitMessage();
         Double body = (Double)msg.body();
         assertEquals(aDouble, body);
      }

      public void checkCharacterMessageReceived(final Character aChar)
      {
         BaseMessage<?> msg = waitMessage();
         Character body = (Character)msg.body();
         assertEquals(aChar, body);
      }

      public void checkByteMessageReceived(final Byte aByte)
      {
         BaseMessage<?> msg = waitMessage();
         Byte body = (Byte)msg.body();
         assertEquals(aByte, body);
      }

      public void checkByteArrayMessageReceived(final byte[] byteArray)
      {
         BaseMessage<?> msg = waitMessage();
         byte[] body = (byte[])msg.body();
         assertEquals(byteArray.length, body.length);
         for (int i = 0; i < byteArray.length; i++)
         {
            assertEquals(byteArray[i], body[i]);
         }
      }

      public void checkBooleanMessageReceived(final Boolean boolValue)
      {
         BaseMessage<?> msg = waitMessage();
         Boolean body = (Boolean)msg.body();
         assertEquals(boolValue, body);
      }

      public void checkStringMessageReceived(final String str)
      {
         BaseMessage<?> msg = waitMessage();
         String body = (String)msg.body();
         assertEquals(str, body);
      }

      public void checkBufferMessageReceived(final Buffer buffer)
      {
         byte[] source = buffer.getBytes();
         BaseMessage<?> msg = waitMessage();
         Buffer body = (Buffer)msg.body();
         byte[] bytes = body.getBytes();
         assertEquals(source.length, bytes.length);
         for (int i = 0; i < bytes.length; i++)
         {
            assertEquals(source[i], bytes[i]);
         }
      }

      private BaseMessage<?> waitMessage()
      {
         BaseMessage<?> msg = null;
         synchronized (lock)
         {
            long timeout = System.currentTimeMillis() + 10000;
            while (vertxMsg == null && timeout > System.currentTimeMillis())
            {
               try
               {
                  lock.wait(1000);
               }
               catch (InterruptedException e)
               {
               }
            }
            msg = vertxMsg;
            vertxMsg = null;
         }
         assertNotNull("Message didn't arrive after 10 seconds.", msg);
         return msg;
      }

   }

   @After @Override
   public void tearDown() throws Exception
   {
      vertxManager.stop();
      server.stop();
      server = null;

      // Something on vertx is setting the TCL to null what would break subsequent tests
      Thread.currentThread().setContextClassLoader(contextClassLoader);
      super.tearDown();
   }
}


text:
<?php

/**
 * Records invocations and provides convenience methods for checking them later
 * on.
 * This abstract class can be implemented by matchers which needs to check the
 * number of times an invocation has occured.
 *
 * @package    PHPUnit_MockObject
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @copyright  2010-2012 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.opensource.org/licenses/BSD-3-Clause  The BSD 3-Clause License
 * @version    Release: @package_version@
 * @link       http://github.com/sebastianbergmann/phpunit-mock-objects
 * @since      Class available since Release 1.0.0
 * @abstract
 */
abstract class PHPUnit_Framework_MockObject_Matcher_InvokedRecorder implements PHPUnit_Framework_MockObject_Matcher_Invocation
{
    /**
     * @var PHPUnit_Framework_MockObject_Invocation[]
     */
    protected $invocations = array();

    /**
     * @return integer
     */
    public function getInvocationCount()
    {
        return count($this->invocations);
    }

    /**
     * @return PHPUnit_Framework_MockObject_Invocation[]
     */
    public function getInvocations()
    {
        return $this->invocations;
    }

    /**
     * @return boolean
     */
    public function hasBeenInvoked()
    {
        return count($this->invocations) > 0;
    }

    /**
     * @param PHPUnit_Framework_MockObject_Invocation $invocation
     */
    public function invoked(PHPUnit_Framework_MockObject_Invocation $invocation)
    {
        $this->invocations[] = $invocation;
    }

    /**
     * @param  PHPUnit_Framework_MockObject_Invocation $invocation
     * @return boolean
     */
    public function matches(PHPUnit_Framework_MockObject_Invocation $invocation)
    {
        return TRUE;
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Sphaerella othonnopsidis Tassi

### Remarks
null


text:
require File.join(File.dirname(__FILE__), "..", "..", "lib", "merb-core")
require "rubygems"
require "rbench"

Merb::Router.prepare do |r|
  r.namespace :admin do |a|
    a.resources :users do |u|
      u.resources :comments
    end
  end

  r.resources :users do |u|
    u.resources :comments
  end

  r.match!("/:account/invitation/:token", :account => /^[a-zA-Z]{5,20}$/, :token => /^[\dA-F]{32}$/).name(:conditional)

  r.default_routes
end

RBench.run(50_000) do
  column :normal
  column :compiled

  report "resources" do
    normal   { Merb::Router.generate( :user, :id => 123) }
    compiled { Merb::Router.generate2(:user, :id => 123) }
  end

  report "nested resources" do
    normal   { Merb::Router.generate( :user_comment, :user_id => 123, :id => "456") }
    compiled { Merb::Router.generate2(:user_comment, :user_id => 123, :id => "456") }
  end

  report "namespaced nested resource" do
    normal   { Merb::Router.generate( :admin_user_comment, :user_id => 123, :id => "456") }
    compiled { Merb::Router.generate2(:admin_user_comment, :user_id => 123, :id => "456") }
  end

  report "route with conditions" do
    normal   { Merb::Router.generate( :conditional, :account => "helloworld", :token => "0987654321ABCDEF0987654321ABCDEF") }
    compiled { Merb::Router.generate2(:conditional, :account => "helloworld", :token => "0987654321ABCDEF0987654321ABCDEF") }
  end

  report "default routes" do
    normal   { Merb::Router.generate( :default, :controller => "foo", :action => "bar", :id => 5, :format => :xml) }
    compiled { Merb::Router.generate2(:default, :controller => "foo", :action => "bar", :id => 5, :format => :xml) }
  end
end

__END__

                                    NORMAL | COMPILED |
-------------------------------------------------------
resources                            1.908 |    0.771 |
nested resources                     2.481 |    1.058 |
namespaced nested resource           2.484 |    1.071 |
route with conditions                1.979 |    0.991 |
default routes                       4.059 |    1.244 |


text:
#include "global.h"

/*
* supHeapAlloc
*
* Purpose:
*
* Wrapper for RtlAllocateHeap with WinObjEx heap.
*
*/
PVOID supHeapAlloc(
    _In_ SIZE_T Size)
{
    return RtlAllocateHeap(NtCurrentPeb()->ProcessHeap, HEAP_ZERO_MEMORY, Size);
}

/*
* supHeapFree
*
* Purpose:
*
* Wrapper for RtlFreeHeap with WinObjEx heap.
*
*/
BOOL supHeapFree(
    _In_ PVOID Memory)
{
    return RtlFreeHeap(NtCurrentPeb()->ProcessHeap, 0, Memory);
}

/*
* supPurgeSystemCache
*
* Purpose:
*
* Flush file cache and memory standby list.
*
*/
VOID supPurgeSystemCache(
    VOID
)
{
    SYSTEM_FILECACHE_INFORMATION sfc;
    SYSTEM_MEMORY_LIST_COMMAND smlc;

    //flush file system cache
    if (NT_SUCCESS(supEnablePrivilege(SE_INCREASE_QUOTA_PRIVILEGE, TRUE))) {
        RtlSecureZeroMemory(&sfc, sizeof(SYSTEM_FILECACHE_INFORMATION));
        sfc.MaximumWorkingSet = (SIZE_T)-1;
        sfc.MinimumWorkingSet = (SIZE_T)-1;
        NtSetSystemInformation(SystemFileCacheInformation, &sfc, sizeof(sfc));
    }

    //flush standby list
    if (NT_SUCCESS(supEnablePrivilege(SE_PROF_SINGLE_PROCESS_PRIVILEGE, TRUE))) {
        smlc = MemoryPurgeStandbyList;
        NtSetSystemInformation(SystemMemoryListInformation, &smlc, sizeof(smlc));
    }
}

/*
* supxDeleteKeyRecursive
*
* Purpose:
*
* Delete key and all it subkeys/values.
*
*/
BOOL supxDeleteKeyRecursive(
    _In_ HKEY hKeyRoot,
    _In_ LPWSTR lpSubKey)
{
    LPWSTR lpEnd;
    LONG lResult;
    DWORD dwSize;
    WCHAR szName[MAX_PATH + 1];
    HKEY hKey;
    FILETIME ftWrite;

    //
    // Attempt to delete key as is.
    //
    lResult = RegDeleteKey(hKeyRoot, lpSubKey);
    if (lResult == ERROR_SUCCESS)
        return TRUE;

    //
    // Try to open key to check if it exist.
    //
    lResult = RegOpenKeyEx(hKeyRoot, lpSubKey, 0, KEY_READ, &hKey);
    if (lResult != ERROR_SUCCESS) {
        if (lResult == ERROR_FILE_NOT_FOUND)
            return TRUE;
        else
            return FALSE;
    }

    //
    // Add slash to the key path if not present.
    //
    lpEnd = _strend(lpSubKey);
    if (*(lpEnd - 1) != TEXT('\\')) {
        *lpEnd = TEXT('\\');
        lpEnd++;
        *lpEnd = TEXT('\0');
    }

    //
    // Enumerate subkeys and call this func for each.
    //
    dwSize = MAX_PATH;
    lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
        NULL, NULL, &ftWrite);

    if (lResult == ERROR_SUCCESS) {

        do {

            _strncpy(lpEnd, MAX_PATH, szName, MAX_PATH);

            if (!supxDeleteKeyRecursive(hKeyRoot, lpSubKey))
                break;

            dwSize = MAX_PATH;

            lResult = RegEnumKeyEx(hKey, 0, szName, &dwSize, NULL,
                NULL, NULL, &ftWrite);

        } while (lResult == ERROR_SUCCESS);
    }

    lpEnd--;
    *lpEnd = TEXT('\0');

    RegCloseKey(hKey);

    //
    // Delete current key, all it subkeys should be already removed.
    //
    lResult = RegDeleteKey(hKeyRoot, lpSubKey);
    if (lResult == ERROR_SUCCESS)
        return TRUE;

    return FALSE;
}

/*
* supRegDeleteKeyRecursive
*
* Purpose:
*
* Delete key and all it subkeys/values.
*
* Remark:
*
* SubKey should not be longer than 260 chars.
*
*/
BOOL supRegDeleteKeyRecursive(
    _In_ HKEY hKeyRoot,
    _In_ LPWSTR lpSubKey)
{
    WCHAR szKeyName[MAX_PATH * 2];
    RtlSecureZeroMemory(szKeyName, sizeof(szKeyName));
    _strncpy(szKeyName, MAX_PATH * 2, lpSubKey, MAX_PATH);
    return supxDeleteKeyRecursive(hKeyRoot, szKeyName);
}

/*
* supEnablePrivilege
*
* Purpose:
*
* Enable/Disable given privilege.
*
* Return NTSTATUS value.
*
*/
NTSTATUS supEnablePrivilege(
    _In_ DWORD Privilege,
    _In_ BOOL Enable
)
{
    ULONG Length;
    NTSTATUS Status;
    HANDLE TokenHandle;
    LUID LuidPrivilege;

    PTOKEN_PRIVILEGES NewState;
    UCHAR Buffer[sizeof(TOKEN_PRIVILEGES) + sizeof(LUID_AND_ATTRIBUTES)];

    Status = NtOpenProcessToken(
        NtCurrentProcess(),
        TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
        &TokenHandle);

    if (!NT_SUCCESS(Status)) {
        return Status;
    }

    NewState = (PTOKEN_PRIVILEGES)Buffer;

    LuidPrivilege = RtlConvertUlongToLuid(Privilege);

    NewState->PrivilegeCount = 1;
    NewState->Privileges[0].Luid = LuidPrivilege;
    NewState->Privileges[0].Attributes = Enable ? SE_PRIVILEGE_ENABLED : 0;

    Status = NtAdjustPrivilegesToken(TokenHandle,
        FALSE,
        NewState,
        sizeof(Buffer),
        NULL,
        &Length);

    if (Status == STATUS_NOT_ALL_ASSIGNED) {
        Status = STATUS_PRIVILEGE_NOT_HELD;
    }

    NtClose(TokenHandle);
    return Status;
}

/*
* supCopyMemory
*
* Purpose:
*
* Copies bytes between buffers.
*
* dest - Destination buffer
* cbdest - Destination buffer size in bytes
* src - Source buffer
* cbsrc - Source buffer size in bytes
*
*/
void supCopyMemory(
    _Inout_ void* dest,
    _In_ size_t cbdest,
    _In_ const void* src,
    _In_ size_t cbsrc
)
{
    char* d = (char*)dest;
    char* s = (char*)src;

    if ((dest == 0) || (src == 0) || (cbdest == 0))
        return;
    if (cbdest < cbsrc)
        cbsrc = cbdest;

    while (cbsrc > 0) {
        *d++ = *s++;
        cbsrc--;
    }
}

/*
* supGetSystemInfo
*
* Purpose:
*
* Wrapper for NtQuerySystemInformation.
*
*/
PVOID supGetSystemInfo(
    _In_ SYSTEM_INFORMATION_CLASS InfoClass
)
{
    INT         c = 0;
    PVOID       Buffer = NULL;
    ULONG		Size = 0x1000;
    NTSTATUS    status;
    ULONG       memIO;

    do {
        Buffer = supHeapAlloc((SIZE_T)Size);
        if (Buffer != NULL) {
            status = NtQuerySystemInformation(InfoClass, Buffer, Size, &memIO);
        }
        else {
            return NULL;
        }
        if (status == STATUS_INFO_LENGTH_MISMATCH) {
            supHeapFree(Buffer);
            Buffer = NULL;
            Size *= 2;
            c++;
            if (c > 100) {
                status = STATUS_SECRET_TOO_LONG;
                break;
            }
        }
    } while (status == STATUS_INFO_LENGTH_MISMATCH);

    if (NT_SUCCESS(status)) {
        return Buffer;
    }

    if (Buffer) {
        supHeapFree(Buffer);
    }
    return NULL;
}

/*
* supProcessExist
*
* Purpose:
*
* Return TRUE if specified process launched, FALSE otherwise or on error.
*
*/
BOOL supProcessExist(
    _In_ LPWSTR lpProcessName
)
{
    PSYSTEM_PROCESSES_INFORMATION ProcessList, pList;
    UNICODE_STRING procName;
    BOOL bResult = FALSE;

    ProcessList = (PSYSTEM_PROCESSES_INFORMATION)supGetSystemInfo(SystemProcessInformation);
    if (ProcessList == NULL) {
        return bResult;
    }

    do {
        RtlSecureZeroMemory(&procName, sizeof(procName));
        RtlInitUnicodeString(&procName, lpProcessName);
        pList = ProcessList;

        for (;;) {
            if (RtlEqualUnicodeString(&procName, &pList->ImageName, TRUE)) {
                bResult = TRUE;
                break;
            }
            if (pList->NextEntryDelta == 0) {
                break;
            }
            pList = (PSYSTEM_PROCESSES_INFORMATION)(((LPBYTE)pList) + pList->NextEntryDelta);
        }

    } while (FALSE);

    supHeapFree(ProcessList);
    return bResult;
}

/*
* supxCreateDriverEntry
*
* Purpose:
*
* Creating registry entry for driver.
*
*/
NTSTATUS supxCreateDriverEntry(
    _In_opt_ LPCWSTR DriverPath,
    _In_ LPCWSTR KeyName
)
{
    NTSTATUS status = STATUS_UNSUCCESSFUL;
    DWORD dwData, dwResult;
    HKEY keyHandle = NULL;
    UNICODE_STRING driverImagePath;

    RtlInitEmptyUnicodeString(&driverImagePath, NULL, 0);

    if (DriverPath) {
        if (!RtlDosPathNameToNtPathName_U(DriverPath,
            &driverImagePath,
            NULL,
            NULL))
        {
            return STATUS_INVALID_PARAMETER_2;
        }
    }

    if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE,
        KeyName,
        0,
        NULL,
        REG_OPTION_NON_VOLATILE,
        KEY_ALL_ACCESS,
        NULL,
        &keyHandle,
        NULL))
    {
        status = STATUS_ACCESS_DENIED;
        goto Cleanup;
    }

    dwResult = ERROR_SUCCESS;

    do {

        dwData = SERVICE_ERROR_NORMAL;
        dwResult = RegSetValueEx(keyHandle,
            TEXT("ErrorControl"),
            0,
            REG_DWORD,
            (BYTE*)&dwData,
            sizeof(dwData));
        if (dwResult != ERROR_SUCCESS)
            break;

        dwData = SERVICE_KERNEL_DRIVER;
        dwResult = RegSetValueEx(keyHandle,
            TEXT("Type"),
            0,
            REG_DWORD,
            (BYTE*)&dwData,
            sizeof(dwData));
        if (dwResult != ERROR_SUCCESS)
            break;

        dwData = SERVICE_DEMAND_START;
        dwResult = RegSetValueEx(keyHandle,
            TEXT("Start"),
            0,
            REG_DWORD,
            (BYTE*)&dwData,
            sizeof(dwData));

        if (dwResult != ERROR_SUCCESS)
            break;

        if (DriverPath) {
            dwResult = RegSetValueEx(keyHandle,
                TEXT("ImagePath"),
                0,
                REG_EXPAND_SZ,
                (BYTE*)driverImagePath.Buffer,
                (DWORD)driverImagePath.Length + sizeof(UNICODE_NULL));
        }

    } while (FALSE);

    RegCloseKey(keyHandle);

    if (dwResult != ERROR_SUCCESS) {
        status = STATUS_ACCESS_DENIED;
    }
    else
    {
        status = STATUS_SUCCESS;
    }

Cleanup:
    if (DriverPath) {
        if (driverImagePath.Buffer) {
            RtlFreeUnicodeString(&driverImagePath);
        }
    }
    return status;
}

/*
* supLoadDriver
*
* Purpose:
*
* Install driver and load it.
*
* N.B.
* SE_LOAD_DRIVER_PRIVILEGE is required to be assigned and enabled.
*
*/
NTSTATUS supLoadDriver(
    _In_ LPCWSTR DriverName,
    _In_ LPCWSTR DriverPath,
    _In_ BOOLEAN UnloadPreviousInstance
)
{
    SIZE_T keyOffset;
    NTSTATUS status = STATUS_UNSUCCESSFUL;
    UNICODE_STRING driverServiceName;

    WCHAR szBuffer[MAX_PATH + 1];

    if (DriverName == NULL)
        return STATUS_INVALID_PARAMETER_1;
    if (DriverPath == NULL)
        return STATUS_INVALID_PARAMETER_2;

    RtlSecureZeroMemory(szBuffer, sizeof(szBuffer));

    keyOffset = RTL_NUMBER_OF(NT_REG_PREP);

    if (FAILED(StringCchPrintf(szBuffer, MAX_PATH,
        DRIVER_REGKEY,
        NT_REG_PREP,
        DriverName)))
    {
        return STATUS_INVALID_PARAMETER_1;
    }

    status = supxCreateDriverEntry(DriverPath,
        &szBuffer[keyOffset]);

    if (!NT_SUCCESS(status))
        return status;

    RtlInitUnicodeString(&driverServiceName, szBuffer);
    status = NtLoadDriver(&driverServiceName);

    if (UnloadPreviousInstance) {
        if ((status == STATUS_IMAGE_ALREADY_LOADED) ||
            (status == STATUS_OBJECT_NAME_COLLISION) ||
            (status == STATUS_OBJECT_NAME_EXISTS))
        {
            status = NtUnloadDriver(&driverServiceName);
            if (NT_SUCCESS(status)) {
                status = NtLoadDriver(&driverServiceName);
            }
        }
    }
    else {
        if (status == STATUS_OBJECT_NAME_EXISTS)
            status = STATUS_SUCCESS;
    }

    return status;
}

/*
* supUnloadDriver
*
* Purpose:
*
* Call driver unload and remove corresponding registry key.
*
* N.B.
* SE_LOAD_DRIVER_PRIVILEGE is required to be assigned and enabled.
*
*/
NTSTATUS supUnloadDriver(
    _In_ LPCWSTR DriverName,
    _In_ BOOLEAN fRemove
)
{
    NTSTATUS status;
    SIZE_T keyOffset;
    UNICODE_STRING driverServiceName;

    WCHAR szBuffer[MAX_PATH + 1];

    RtlSecureZeroMemory(szBuffer, sizeof(szBuffer));

    if (FAILED(StringCchPrintf(szBuffer, MAX_PATH,
        DRIVER_REGKEY,
        NT_REG_PREP,
        DriverName)))
    {
        return STATUS_INVALID_PARAMETER_1;
    }

    keyOffset = RTL_NUMBER_OF(NT_REG_PREP);

    status = supxCreateDriverEntry(NULL,
        &szBuffer[keyOffset]);

    if (!NT_SUCCESS(status))
        return status;

    RtlInitUnicodeString(&driverServiceName, szBuffer);
    status = NtUnloadDriver(&driverServiceName);

    if (NT_SUCCESS(status)) {
        if (fRemove)
            supRegDeleteKeyRecursive(HKEY_LOCAL_MACHINE, &szBuffer[keyOffset]);
    }

    return status;
}

/*
* supOpenDriver
*
* Purpose:
*
* Open handle for helper driver.
*
*/
NTSTATUS supOpenDriver(
    _In_ LPCWSTR DriverName,
    _Out_ PHANDLE DeviceHandle
)
{
    NTSTATUS status = STATUS_UNSUCCESSFUL;

    UNICODE_STRING usDeviceLink;
    OBJECT_ATTRIBUTES obja;
    IO_STATUS_BLOCK iost;

    TCHAR szDeviceLink[MAX_PATH + 1];

    // assume failure
    if (DeviceHandle)
        *DeviceHandle = NULL;
    else
        return STATUS_INVALID_PARAMETER_2;

    if (DriverName) {

        RtlSecureZeroMemory(szDeviceLink, sizeof(szDeviceLink));

        if (FAILED(StringCchPrintf(szDeviceLink,
            MAX_PATH,
            TEXT("\\DosDevices\\%wS"),
            DriverName)))
        {
            return STATUS_INVALID_PARAMETER_1;
        }

        RtlInitUnicodeString(&usDeviceLink, szDeviceLink);
        InitializeObjectAttributes(&obja, &usDeviceLink, OBJ_CASE_INSENSITIVE, NULL, NULL);

        status = NtCreateFile(DeviceHandle,
            GENERIC_READ | GENERIC_WRITE,
            &obja,
            &iost,
            NULL,
            0,
            0,
            FILE_OPEN,
            0,
            NULL,
            0);

    }
    else {
        status = STATUS_INVALID_PARAMETER_1;
    }

    return status;
}

/*
* supGetNtOsBase
*
* Purpose:
*
* Return ntoskrnl base address.
*
*/
ULONG_PTR supGetNtOsBase(
    VOID
)
{
    PRTL_PROCESS_MODULES   miSpace;
    ULONG_PTR              NtOsBase = 0;

    miSpace = (PRTL_PROCESS_MODULES)supGetSystemInfo(SystemModuleInformation);
    if (miSpace) {
        NtOsBase = (ULONG_PTR)miSpace->Modules[0].ImageBase;
        RtlFreeHeap(NtCurrentPeb()->ProcessHeap, 0, miSpace);
    }
    return NtOsBase;
}

/*
* supQueryResourceData
*
* Purpose:
*
* Load resource by given id (win32 FindResource, SizeofResource, LockResource).
*
*/
PBYTE supQueryResourceData(
    _In_ ULONG_PTR ResourceId,
    _In_ PVOID DllHandle,
    _In_ PULONG DataSize
)
{
    NTSTATUS                    status;
    ULONG_PTR                   IdPath[3];
    IMAGE_RESOURCE_DATA_ENTRY* DataEntry;
    PBYTE                       Data = NULL;
    ULONG                       SizeOfData = 0;

    if (DllHandle != NULL) {

        IdPath[0] = (ULONG_PTR)RT_RCDATA; //type
        IdPath[1] = ResourceId;           //id
        IdPath[2] = 0;                    //lang

        status = LdrFindResource_U(DllHandle, (ULONG_PTR*)&IdPath, 3, &DataEntry);
        if (NT_SUCCESS(status)) {
            status = LdrAccessResource(DllHandle, DataEntry, (PVOID*)&Data, &SizeOfData);
            if (NT_SUCCESS(status)) {
                if (DataSize) {
                    *DataSize = SizeOfData;
                }
            }
        }
    }
    return Data;
}

/*
* supWriteBufferToFile
*
* Purpose:
*
* Create new file (or open existing) and write (append) buffer to it.
*
*/
SIZE_T supWriteBufferToFile(
    _In_ PWSTR lpFileName,
    _In_ PVOID Buffer,
    _In_ SIZE_T Size,
    _In_ BOOL Flush,
    _In_ BOOL Append,
    _Out_opt_ NTSTATUS* Result
)
{
    NTSTATUS           Status = STATUS_UNSUCCESSFUL;
    DWORD              dwFlag;
    HANDLE             hFile = NULL;
    OBJECT_ATTRIBUTES  attr;
    UNICODE_STRING     NtFileName;
    IO_STATUS_BLOCK    IoStatus;
    LARGE_INTEGER      Position;
    ACCESS_MASK        DesiredAccess;
    PLARGE_INTEGER     pPosition = NULL;
    ULONG_PTR          nBlocks, BlockIndex;
    ULONG              BlockSize, RemainingSize;
    PBYTE              ptr = (PBYTE)Buffer;
    SIZE_T             BytesWritten = 0;

    if (Result)
        *Result = STATUS_UNSUCCESSFUL;

    if (RtlDosPathNameToNtPathName_U(lpFileName, &NtFileName, NULL, NULL) == FALSE) {
        if (Result)
            *Result = STATUS_INVALID_PARAMETER_1;
        return 0;
    }

    DesiredAccess = FILE_WRITE_ACCESS | SYNCHRONIZE;
    dwFlag = FILE_OVERWRITE_IF;

    if (Append != FALSE) {
        DesiredAccess |= FILE_READ_ACCESS;
        dwFlag = FILE_OPEN_IF;
    }

    InitializeObjectAttributes(&attr, &NtFileName, OBJ_CASE_INSENSITIVE, 0, NULL);

    __try {
        Status = NtCreateFile(&hFile, DesiredAccess, &attr,
            &IoStatus, NULL, FILE_ATTRIBUTE_NORMAL, 0, dwFlag,
            FILE_SYNCHRONOUS_IO_NONALERT | FILE_NON_DIRECTORY_FILE, NULL, 0);

        if (!NT_SUCCESS(Status))
            __leave;

        pPosition = NULL;

        if (Append != FALSE) {
            Position.LowPart = FILE_WRITE_TO_END_OF_FILE;
            Position.HighPart = -1;
            pPosition = &Position;
        }

        if (Size < 0x80000000) {
            BlockSize = (ULONG)Size;
            Status = NtWriteFile(hFile, 0, NULL, NULL, &IoStatus, ptr, BlockSize, pPosition, NULL);
            if (!NT_SUCCESS(Status))
                __leave;

            BytesWritten += IoStatus.Information;
        }
        else {
            BlockSize = 0x7FFFFFFF;
            nBlocks = (Size / BlockSize);
            for (BlockIndex = 0; BlockIndex < nBlocks; BlockIndex++) {

                Status = NtWriteFile(hFile, 0, NULL, NULL, &IoStatus, ptr, BlockSize, pPosition, NULL);
                if (!NT_SUCCESS(Status))
                    __leave;

                ptr += BlockSize;
                BytesWritten += IoStatus.Information;
            }
            RemainingSize = (ULONG)(Size % BlockSize);
            if (RemainingSize != 0) {
                Status = NtWriteFile(hFile, 0, NULL, NULL, &IoStatus, ptr, RemainingSize, pPosition, NULL);
                if (!NT_SUCCESS(Status))
                    __leave;
                BytesWritten += IoStatus.Information;
            }
        }
    }
    __finally {
        if (hFile != NULL) {
            if (Flush != FALSE) NtFlushBuffersFile(hFile, &IoStatus);
            NtClose(hFile);
        }
        RtlFreeUnicodeString(&NtFileName);
        if (Result) *Result = Status;
    }
    return BytesWritten;
}

/*
* supGetProcAddress
*
* Purpose:
*
* Get NtOskrnl procedure address.
*
*/
ULONG_PTR supGetProcAddress(
    _In_ ULONG_PTR KernelBase,
    _In_ ULONG_PTR KernelImage,
    _In_ LPCSTR FunctionName
)
{
    ANSI_STRING    cStr;
    ULONG_PTR      pfn = 0;

    RtlInitString(&cStr, FunctionName);
    if (!NT_SUCCESS(LdrGetProcedureAddress((PVOID)KernelImage, &cStr, 0, (PVOID*)&pfn)))
        return 0;

    return KernelBase + (pfn - KernelImage);
}

/*
* supResolveKernelImport
*
* Purpose:
*
* Resolve import (ntoskrnl only).
*
*/
void supResolveKernelImport(
    _In_ ULONG_PTR Image,
    _In_ ULONG_PTR KernelImage,
    _In_ ULONG_PTR KernelBase
)
{
    PIMAGE_OPTIONAL_HEADER      popth;
    ULONG_PTR                   ITableVA, * nextthunk;
    PIMAGE_IMPORT_DESCRIPTOR    ITable;
    PIMAGE_THUNK_DATA           pthunk;
    PIMAGE_IMPORT_BY_NAME       pname;
    ULONG                       i;

    popth = &RtlImageNtHeader((PVOID)Image)->OptionalHeader;

    if (popth->NumberOfRvaAndSizes <= IMAGE_DIRECTORY_ENTRY_IMPORT)
        return;

    ITableVA = popth->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress;
    if (ITableVA == 0)
        return;

    ITable = (PIMAGE_IMPORT_DESCRIPTOR)(Image + ITableVA);

    if (ITable->OriginalFirstThunk == 0)
        pthunk = (PIMAGE_THUNK_DATA)(Image + ITable->FirstThunk);
    else
        pthunk = (PIMAGE_THUNK_DATA)(Image + ITable->OriginalFirstThunk);

    for (i = 0; pthunk->u1.Function != 0; i++, pthunk++) {
        nextthunk = (PULONG_PTR)(Image + ITable->FirstThunk);
        if ((pthunk->u1.Ordinal & IMAGE_ORDINAL_FLAG) == 0) {
            pname = (PIMAGE_IMPORT_BY_NAME)((PCHAR)Image + pthunk->u1.AddressOfData);
            nextthunk[i] = supGetProcAddress(KernelBase, KernelImage, pname->Name);
        }
        else
            nextthunk[i] = supGetProcAddress(KernelBase, KernelImage, (LPCSTR)(pthunk->u1.Ordinal & 0xffff));
    }
}

/*
* supDetectObjectCallback
*
* Purpose:
*
* Comparer callback routine used in objects enumeration.
*
*/
NTSTATUS NTAPI supDetectObjectCallback(
    _In_ POBJECT_DIRECTORY_INFORMATION Entry,
    _In_ PVOID CallbackParam
)
{
    POBJSCANPARAM Param = (POBJSCANPARAM)CallbackParam;

    if (Entry == NULL) {
        return STATUS_INVALID_PARAMETER_1;
    }

    if (CallbackParam == NULL) {
        return STATUS_INVALID_PARAMETER_2;
    }

    if (Param->Buffer == NULL || Param->BufferSize == 0) {
        return STATUS_MEMORY_NOT_ALLOCATED;
    }

    if (Entry->Name.Buffer) {
        if (_strcmpi_w(Entry->Name.Buffer, Param->Buffer) == 0) {
            return STATUS_SUCCESS;
        }
    }
    return STATUS_UNSUCCESSFUL;
}

/*
* supEnumSystemObjects
*
* Purpose:
*
* Lookup object by name in given directory.
*
*/
NTSTATUS NTAPI supEnumSystemObjects(
    _In_opt_ LPWSTR pwszRootDirectory,
    _In_opt_ HANDLE hRootDirectory,
    _In_ PENUMOBJECTSCALLBACK CallbackProc,
    _In_opt_ PVOID CallbackParam
)
{
    ULONG               ctx, rlen;
    HANDLE              hDirectory = NULL;
    NTSTATUS            status;
    NTSTATUS            CallbackStatus;
    OBJECT_ATTRIBUTES   attr;
    UNICODE_STRING      sname;

    POBJECT_DIRECTORY_INFORMATION    objinf;

    if (CallbackProc == NULL) {
        return STATUS_INVALID_PARAMETER_4;
    }

    status = STATUS_UNSUCCESSFUL;

    __try {

        // We can use root directory.
        if (pwszRootDirectory != NULL) {
            RtlSecureZeroMemory(&sname, sizeof(sname));
            RtlInitUnicodeString(&sname, pwszRootDirectory);
            InitializeObjectAttributes(&attr, &sname, OBJ_CASE_INSENSITIVE, NULL, NULL);
            status = NtOpenDirectoryObject(&hDirectory, DIRECTORY_QUERY, &attr);
            if (!NT_SUCCESS(status)) {
                return status;
            }
        }
        else {
            if (hRootDirectory == NULL) {
                return STATUS_INVALID_PARAMETER_2;
            }
            hDirectory = hRootDirectory;
        }

        // Enumerate objects in directory.
        ctx = 0;
        do {

            rlen = 0;
            status = NtQueryDirectoryObject(hDirectory, NULL, 0, TRUE, FALSE, &ctx, &rlen);
            if (status != STATUS_BUFFER_TOO_SMALL)
                break;

            objinf = (POBJECT_DIRECTORY_INFORMATION)supHeapAlloc(rlen);
            if (objinf == NULL)
                break;

            status = NtQueryDirectoryObject(hDirectory, objinf, rlen, TRUE, FALSE, &ctx, &rlen);
            if (!NT_SUCCESS(status)) {
                supHeapFree(objinf);
                break;
            }

            CallbackStatus = CallbackProc(objinf, CallbackParam);

            supHeapFree(objinf);

            if (NT_SUCCESS(CallbackStatus)) {
                status = STATUS_SUCCESS;
                break;
            }

        } while (TRUE);

        if (hDirectory != NULL) {
            NtClose(hDirectory);
        }

    }
    __except (EXCEPTION_EXECUTE_HANDLER) {
        status = STATUS_ACCESS_VIOLATION;
    }

    return status;
}

/*
* supIsObjectExists
*
* Purpose:
*
* Return TRUE if the given object exists, FALSE otherwise.
*
*/
BOOLEAN supIsObjectExists(
    _In_ LPWSTR RootDirectory,
    _In_ LPWSTR ObjectName
)
{
    OBJSCANPARAM Param;

    if (ObjectName == NULL) {
        return FALSE;
    }

    Param.Buffer = ObjectName;
    Param.BufferSize = (ULONG)_strlen(ObjectName);

    return NT_SUCCESS(supEnumSystemObjects(RootDirectory, NULL, supDetectObjectCallback, &Param));
}

/*
* supQueryObjectFromHandle
*
* Purpose:
*
* Return object kernel address from handle in current process handle table.
*
*/
BOOL supQueryObjectFromHandle(
    _In_ HANDLE hOject,
    _Out_ ULONG_PTR* Address
)
{
    BOOL   bFound = FALSE;
    ULONG  i;
    DWORD  CurrentProcessId = GetCurrentProcessId();

    PSYSTEM_HANDLE_INFORMATION_EX pHandles;

    if (Address)
        *Address = 0;
    else
        return FALSE;

    pHandles = (PSYSTEM_HANDLE_INFORMATION_EX)supGetSystemInfo(SystemExtendedHandleInformation);
    if (pHandles) {
        for (i = 0; i < pHandles->NumberOfHandles; i++) {
            if (pHandles->Handles[i].UniqueProcessId == CurrentProcessId) {
                if (pHandles->Handles[i].HandleValue == (USHORT)(ULONG_PTR)hOject) {
                    *Address = (ULONG_PTR)pHandles->Handles[i].Object;
                    bFound = TRUE;
                    break;
                }
            }
        }
        supHeapFree(pHandles);
    }
    return bFound;
}

/*
* supGetCommandLineOption
*
* Purpose:
*
* Parse command line options.
*
*/
BOOL supGetCommandLineOption(
    _In_ LPCTSTR OptionName,
    _In_ BOOL IsParametric,
    _Inout_opt_ LPTSTR OptionValue,
    _In_ ULONG ValueSize
)
{
    LPTSTR	cmdline = GetCommandLine();
    TCHAR   Param[MAX_PATH + 1];
    ULONG   rlen;
    int		i = 0;

    RtlSecureZeroMemory(Param, sizeof(Param));
    while (GetCommandLineParam(cmdline, i, Param, MAX_PATH, &rlen))
    {
        if (rlen == 0)
            break;

        if (_strcmp(Param, OptionName) == 0)
        {
            if (IsParametric)
                return GetCommandLineParam(cmdline, i + 1, OptionValue, ValueSize, &rlen);

            return TRUE;
        }
        ++i;
    }

    return 0;
}

/*
* supQueryHVCIState
*
* Purpose:
*
* Query HVCI/IUM state.
*
*/
BOOLEAN supQueryHVCIState(
    _Out_ PBOOLEAN pbHVCIEnabled,
    _Out_ PBOOLEAN pbHVCIStrictMode,
    _Out_ PBOOLEAN pbHVCIIUMEnabled
)
{
    BOOLEAN hvciEnabled;
    ULONG ReturnLength;
    SYSTEM_CODEINTEGRITY_INFORMATION CodeIntegrity;

    if (pbHVCIEnabled) *pbHVCIEnabled = FALSE;
    if (pbHVCIStrictMode) *pbHVCIStrictMode = FALSE;
    if (pbHVCIIUMEnabled) *pbHVCIIUMEnabled = FALSE;

    CodeIntegrity.Length = sizeof(CodeIntegrity);
    if (NT_SUCCESS(NtQuerySystemInformation(
        SystemCodeIntegrityInformation,
        &CodeIntegrity,
        sizeof(CodeIntegrity),
        &ReturnLength)))
    {
        hvciEnabled = ((CodeIntegrity.CodeIntegrityOptions & CODEINTEGRITY_OPTION_ENABLED) &&
            (CodeIntegrity.CodeIntegrityOptions & CODEINTEGRITY_OPTION_HVCI_KMCI_ENABLED));

        if (pbHVCIEnabled)
            *pbHVCIEnabled = hvciEnabled;

        if (pbHVCIStrictMode)
            *pbHVCIStrictMode = hvciEnabled &&
            (CodeIntegrity.CodeIntegrityOptions & CODEINTEGRITY_OPTION_HVCI_KMCI_STRICTMODE_ENABLED);

        if (pbHVCIIUMEnabled)
            *pbHVCIIUMEnabled = (CodeIntegrity.CodeIntegrityOptions & CODEINTEGRITY_OPTION_HVCI_IUM_ENABLED) > 0;

        return TRUE;
    }

    return FALSE;
}

/*
* supExpandEnvironmentStrings
*
* Purpose:
*
* Reimplemented ExpandEnvironmentStrings.
*
*/
DWORD supExpandEnvironmentStrings(
    _In_ LPCWSTR lpSrc,
    _Out_writes_to_opt_(nSize, return) LPWSTR lpDst,
    _In_ DWORD nSize
)
{
    NTSTATUS Status;
    SIZE_T SrcLength = 0, ReturnLength = 0, DstLength = (SIZE_T)nSize;

    if (lpSrc) {
        SrcLength = _strlen(lpSrc);
    }

    Status = RtlExpandEnvironmentStrings(
        NULL,
        (PWSTR)lpSrc,
        SrcLength,
        (PWSTR)lpDst,
        DstLength,
        &ReturnLength);

    if ((NT_SUCCESS(Status)) || (Status == STATUS_BUFFER_TOO_SMALL)) {

        if (ReturnLength <= MAXDWORD32)
            return (DWORD)ReturnLength;

        Status = STATUS_UNSUCCESSFUL;
    }
    RtlSetLastWin32Error(RtlNtStatusToDosError(Status));
    return 0;
}

/*
* supQueryMaximumUserModeAddress
*
* Purpose:
*
* Return maximum user mode address.
*
*/
ULONG_PTR supQueryMaximumUserModeAddress()
{
    NTSTATUS ntStatus;

    SYSTEM_BASIC_INFORMATION basicInfo;

    ULONG returnLength = 0;
    SYSTEM_INFO systemInfo;

    RtlSecureZeroMemory(&basicInfo, sizeof(basicInfo));

    ntStatus = NtQuerySystemInformation(SystemBasicInformation,
        &basicInfo,
        sizeof(basicInfo),
        &returnLength);

    if (NT_SUCCESS(ntStatus)) {
        return basicInfo.MaximumUserModeAddress;
    }
    else {

        RtlSecureZeroMemory(&systemInfo, sizeof(systemInfo));
        GetSystemInfo(&systemInfo);
        return (ULONG_PTR)systemInfo.lpMaximumApplicationAddress;
    }

}

/*
* supFindPattern
*
* Purpose:
*
* Lookup pattern in buffer.
*
*/
PVOID supFindPattern(
    _In_ CONST PBYTE Buffer,
    _In_ SIZE_T BufferSize,
    _In_ CONST PBYTE Pattern,
    _In_ SIZE_T PatternSize
)
{
    PBYTE p0 = Buffer, pnext;

    if (PatternSize == 0)
        return NULL;

    if (BufferSize < PatternSize)
        return NULL;

    do {
        pnext = (PBYTE)memchr(p0, Pattern[0], BufferSize);
        if (pnext == NULL)
            break;

        BufferSize -= (ULONG_PTR)(pnext - p0);

        if (BufferSize < PatternSize)
            return NULL;

        if (memcmp(pnext, Pattern, PatternSize) == 0)
            return pnext;

        p0 = pnext + 1;
        --BufferSize;
    } while (BufferSize > 0);

    return NULL;
}

/*
* supGetCurrentProcessToken
*
* Purpose:
*
* Return current process token value with TOKEN_QUERY access right.
*
*/
HANDLE supGetCurrentProcessToken(
    VOID)
{
    HANDLE hToken = NULL;

    if (NT_SUCCESS(NtOpenProcessToken(
        NtCurrentProcess(),
        TOKEN_QUERY,
        &hToken)))
    {
        return hToken;
    }
    return NULL;
}

/*
* supUserIsFullAdmin
*
* Purpose:
*
* Tests if the current user is admin with full access token.
*
*/
BOOL supUserIsFullAdmin(
    VOID
)
{
    BOOL     bResult = FALSE;
    HANDLE   hToken = NULL;
    NTSTATUS status;
    DWORD    i, Attributes;
    ULONG    ReturnLength = 0;

    PTOKEN_GROUPS pTkGroups;

    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    PSID AdministratorsGroup = NULL;

    hToken = supGetCurrentProcessToken();
    if (hToken == NULL)
        return FALSE;

    do {
        if (!NT_SUCCESS(RtlAllocateAndInitializeSid(
            &NtAuthority,
            2,
            SECURITY_BUILTIN_DOMAIN_RID,
            DOMAIN_ALIAS_RID_ADMINS,
            0, 0, 0, 0, 0, 0,
            &AdministratorsGroup)))
        {
            break;
        }

        status = NtQueryInformationToken(hToken, TokenGroups, NULL, 0, &ReturnLength);
        if (status != STATUS_BUFFER_TOO_SMALL)
            break;

        pTkGroups = (PTOKEN_GROUPS)supHeapAlloc((SIZE_T)ReturnLength);
        if (pTkGroups == NULL)
            break;

        status = NtQueryInformationToken(hToken, TokenGroups, pTkGroups, ReturnLength, &ReturnLength);
        if (NT_SUCCESS(status)) {
            if (pTkGroups->GroupCount > 0)
                for (i = 0; i < pTkGroups->GroupCount; i++) {
                    Attributes = pTkGroups->Groups[i].Attributes;
                    if (RtlEqualSid(AdministratorsGroup, pTkGroups->Groups[i].Sid))
                        if (
                            (Attributes & SE_GROUP_ENABLED) &&
                            (!(Attributes & SE_GROUP_USE_FOR_DENY_ONLY))
                            )
                        {
                            bResult = TRUE;
                            break;
                        }
                }
        }
        supHeapFree(pTkGroups);

    } while (FALSE);

    if (AdministratorsGroup != NULL) {
        RtlFreeSid(AdministratorsGroup);
    }

    NtClose(hToken);
    return bResult;
}

/*
* supQueryTokenUserSid
*
* Purpose:
*
* Return SID of given token.
*
* Use supHeapFree to free memory allocated for result.
*
*/
PSID supQueryTokenUserSid(
    _In_ HANDLE ProcessToken
)
{
    PSID resultSid = NULL;
    PTOKEN_USER ptu;
    NTSTATUS status;
    ULONG sidLength = 0, allocLength;

    status = NtQueryInformationToken(
        ProcessToken,
        TokenUser,
        NULL, 0, &sidLength);

    if (status == STATUS_BUFFER_TOO_SMALL) {

        ptu = (PTOKEN_USER)supHeapAlloc(sidLength);

        if (ptu) {

            status = NtQueryInformationToken(
                ProcessToken,
                TokenUser,
                ptu,
                sidLength,
                &sidLength);

            if (NT_SUCCESS(status)) {

                allocLength = SECURITY_MAX_SID_SIZE;
                if (sidLength > allocLength)
                    allocLength = sidLength;

                resultSid = (PSID)supHeapAlloc(allocLength);
                if (resultSid) {

                    status = RtlCopySid(
                        allocLength,
                        resultSid,
                        ptu->User.Sid);

                }
            }

            supHeapFree(ptu);
        }
    }

    return (NT_SUCCESS(status)) ? resultSid : NULL;
}

/*
* supGetTokenInfo
*
* Purpose:
*
* Returns buffer with token information by given TokenInformationClass.
*
* Returned buffer must be freed with supHeapFree after usage.
*
*/
PVOID supGetTokenInfo(
    _In_ HANDLE TokenHandle,
    _In_ TOKEN_INFORMATION_CLASS TokenInformationClass,
    _Out_opt_ PULONG ReturnLength
)
{
    PVOID Buffer = NULL;
    ULONG returnLength = 0;

    if (ReturnLength)
        *ReturnLength = 0;

    NtQueryInformationToken(TokenHandle,
        TokenInformationClass,
        NULL,
        0,
        &returnLength);

    Buffer = supHeapAlloc((SIZE_T)returnLength);
    if (Buffer) {

        if (NT_SUCCESS(NtQueryInformationToken(TokenHandle,
            TokenInformationClass,
            Buffer,
            returnLength,
            &returnLength)))
        {
            if (ReturnLength)
                *ReturnLength = returnLength;
            return Buffer;
        }
        else {
            supHeapFree(Buffer);
            return NULL;
        }
    }

    return Buffer;
}

/*
* supGetImageVersionInfo
*
* Purpose:
*
* Return version numbers from version info.
*
*/
BOOL supGetImageVersionInfo(
    _In_ PWSTR lpFileName,
    _In_ PSUP_VERINFO_NUMBERS VersionNumbers
)
{
    BOOL bResult = FALSE;
    DWORD dwHandle, dwSize, dwError = ERROR_SUCCESS;
    PVOID vinfo = NULL;
    UINT Length;
    VS_FIXEDFILEINFO* pFileInfo;

    dwHandle = 0;
    dwSize = GetFileVersionInfoSize(lpFileName, &dwHandle);
    if (dwSize) {
        vinfo = supHeapAlloc(dwSize);
        if (vinfo) {
            if (GetFileVersionInfoEx(0, lpFileName, 0, dwSize, vinfo)) {
                bResult = VerQueryValue(vinfo, TEXT("\\"), (LPVOID*)&pFileInfo, (PUINT)&Length);
                if (bResult) {
                    VersionNumbers->VersionMS = pFileInfo->dwFileVersionMS;
                    VersionNumbers->VersionLS = pFileInfo->dwFileVersionLS;
                }
                else {
                    dwError = GetLastError();
                }
            }
            else {
                dwError = GetLastError();
            }
            supHeapFree(vinfo);
        }
        else {
            dwError = GetLastError();
        }
    }
    else {
        dwError = GetLastError();
    }

    SetLastError(dwError);
    return bResult;
}


text:
import pytest

from traw.models import Priority, Result, Status

@pytest.fixture()
def status1a(client):
    yield Status(client, {'id': 1})

@pytest.fixture()
def status1b(client):
    yield Status(client, {'id': 1})

@pytest.fixture()
def status1c(client):
    yield Status(client, {'id': 1, 'foo': 'bar'})

@pytest.fixture()
def status2(client):
    yield Status(client, {'id': 2})

@pytest.fixture()
def priority1(client):
    yield Priority(client, {'id': 1})

def test___eq___ids_match(status1a, status1b):
    assert (status1a == status1b) is True

def test___eq___ids_dont_match(status1a, status2):
    assert (status1a == status2) is False

def test___eq___ids_match_commutative(status1a, status1b):
    assert (status1b == status1a) is True

def test___eq___ids_dont_match_commutative(status1a, status2):
    assert (status2 == status1a) is False

def test___eq___hashes_dont_match(status1a, status1c):
    assert (status1a == status1c) is False

def test___eq___types_dont_match(status1a, priority1):
    assert (status1a == priority1) is False

def test___eq___hashes_change_as_object_changes(client):
    result1 = Result(client)
    result2 = Result(client)
    assert (result1 == result2) is True

    result1.comment = "mock comment a"

    assert (result1 == result2) is False

    result2.comment = "mock comment b"

    assert (result1 == result2) is False

    result2.comment = "mock comment a"

    assert (result1 == result2) is True

def test___ne___ids_match(status1a, status1b):
    assert (status1a != status1b) is False

def test___ne___ids_dont_match(status1a, status2):
    assert (status1a != status2) is True

def test___ne___ids_match_cummutative(status1a, status1b):
    assert (status1b != status1a) is False

def test___ne___ids_dont_match_cummutative(status1a, status2):
    assert (status2 != status1a) is True

def test___ne___hashes_dont_match(status1a, status1c):
    assert (status1a != status1c) is True

def test___ne___types_dont_match(status1a, priority1):
    assert (status1a != priority1) is True

def test___ne___hashes_change_as_object_changes(client):
    result1 = Result(client)
    result2 = Result(client)
    assert (result1 != result2) is False

    result1.comment = "mock comment a"

    assert (result1 != result2) is True

    result2.comment = "mock comment b"

    assert (result1 != result2) is True

    result2.comment = "mock comment a"

    assert (result1 != result2) is False


text:
package com.taoswork.tallycheck.authority.provider.onmongo.test;

import com.taoswork.tallycheck.authority.atom.Access;
import com.taoswork.tallycheck.authority.atom.ProtectionMode;
import com.taoswork.tallycheck.authority.core.ProtectionScope;
import com.taoswork.tallycheck.authority.domain.ResourceAccess;
import com.taoswork.tallycheck.authority.provider.AllPassAuthorityProvider;
import com.taoswork.tallycheck.authority.provider.AuthorityProviderImpl;
import com.taoswork.tallycheck.authority.provider.IAuthorityProvider;
import com.taoswork.tallycheck.authority.provider.onmongo.client.service.AuthSolutionDataSolution;
import com.taoswork.tallycheck.authority.provider.onmongo.client.service.datasource.AuthSolutionDatasourceConfiguration;
import com.taoswork.tallycheck.authority.provider.onmongo.common.domain.auth.TGroupAuthority;
import com.taoswork.tallycheck.authority.provider.onmongo.common.domain.auth.TUserAuthority;
import com.taoswork.tallycheck.authority.provider.onmongo.common.domain.resource.*;
import com.taoswork.tallycheck.dataservice.SecurityAccessor;
import com.taoswork.tallycheck.dataservice.exception.ServiceException;
import com.taoswork.tallycheck.datasolution.DatasourceDefinition;
import com.taoswork.tallycheck.datasolution.config.IDatasourceConfiguration;
import com.taoswork.tallycheck.datasolution.mongo.core.entityservice.MongoEntityService;
import com.taoswork.tallycheck.datasolution.service.IEntityService;

/**
 * Created by Gao Yuan on 2015/6/4.
 */
public class VerifierTestSupport {
    private static ResourceAccess READ_ACCESS = ResourceAccess.createByAccess(Access.Read);
    private static ResourceAccess OPEN_ACCESS = ResourceAccess.createByAccess(new Access(Access.NONE, 1));

    private  static AuthSolutionDataSolution dataSolution;

    protected static IAuthorityProvider authorityProvider;
    //    protected static PermissionEngine permissionEngine;
    protected static PermissionMockuper mockuper;
    protected static MongoEntityService entityService;
    public static final Access NORMAL_ACCESS = Access.Read;

    public static final String User_N____ = "User_N____";
    public static final String User__AB__ = "User__AB__";
    public static final String User__ABCD = "User__ABCD";
    public static final String User_G____ = "User_G____";
    public static final String User_GAB__ = "User_GAB__";
    public static final String User_GABCD = "User_GABCD";

    public static final String Group_N____ = "Group_N____";
    public static final String Group__AB__ = "Group__AB__";
    public static final String Group_G____ = "Group_G____";

//    protected IKAuthority user_N____ ;
//    protected IKAuthority user__AB__ ;
//    protected IKAuthority user__ABCD ;
//    protected IKAuthority user_G____ ;
//    protected IKAuthority user_GAB__ ;
//    protected IKAuthority user_GABCD ;

    public static final String FILE_G_____ = "FILE_G_____";
    public static final String FILE__A____ = "FILE__A____";
    public static final String FILE____C__ = "FILE____C__";
    public static final String FILE__AB___ = "FILE__AB___";
    public static final String FILE__A_C__ = "FILE__A_C__";
    public static final String FILE____CD_ = "FILE____CD_";
    public static final String FILE__ABC__ = "FILE__ABC__";
    public static final String FILE__A_CD_ = "FILE__A_CD_";
    public static final String FILE__ABCD_ = "FILE__ABCD_";
    public static final String FILE______E = "FILE______E";
    public static final String FILE__ABCDE = "FILE__ABCDE";

    protected XFile file_G_____ = null;
    protected XFile file__A____ = null;
    protected XFile file____C__ = null;
    protected XFile file__AB___ = null;
    protected XFile file__A_C__ = null;
    protected XFile file____CD_ = null;
    protected XFile file__ABC__ = null;
    protected XFile file__A_CD_ = null;
    protected XFile file__ABCD_ = null;
    protected XFile file______E = null;
    protected XFile file__ABCDE = null;
    public final int docCount = 11;

    public final static SecurityAccessor securityAccessor = new SecurityAccessor(new ProtectionScope(PermissionMockuper.PROTECTION_SPEC, PermissionMockuper.PROTECTION_REGION),"1");

    protected static void setupDatabaseData() {
        dataSolution = new AuthSolutionDataSolution();
        dataSolution.setAuthorityProvider(new AllPassAuthorityProvider());

        entityService = dataSolution.getService(IEntityService.COMPONENT_NAME);
        authorityProvider = new AuthorityProviderImpl(entityService, TUserAuthority.class, TGroupAuthority.class);
        mockuper = new PermissionMockuper(dataSolution, NORMAL_ACCESS);
    }

    protected static void teardownDatabaseData() {
        authorityProvider = null;
        AuthSolutionDatasourceConfiguration.DatasourceDefinition mdbDef = dataSolution.getService(DatasourceDefinition.DATA_SOURCE_DEFINITION);
        mdbDef.dropDatabase();
        dataSolution = null;
    }
//
//    @Before
//    public void setup() {
//        setupDatabaseData();
//    }
//
//    @After
//    public void teardown() {
//        teardownDatabaseData();
//    }
//
//    @Test
//    public void test() {
//        String tenant = "Function:Test";
//        makeDatabaseTestData(tenant);
//
//    }

    protected static void makeDatabaseTestData() throws ServiceException {
        String tenant = mockuper.PROTECTION_REGION;
        mockuper.makeProtectionSpec();
        mockuper.makeSecuredResource(tenant, CM1File.class, true, ProtectionMode.FitAll, true);
        mockuper.makeSecuredResource(tenant, CS1File.class, false, ProtectionMode.FitAll, true);
        mockuper.makeSecuredResource(tenant, CM0File.class, true, ProtectionMode.FitAny, true);
        mockuper.makeSecuredResource(tenant, CS0File.class, false, ProtectionMode.FitAny, true);
        mockuper.makeSecuredResource(tenant, CCFile.class, false, ProtectionMode.FitAny, false);

        for (Class resource : new Class[]{CM1File.class, CS0File.class, CM0File.class, CS1File.class, CCFile.class}) {
            mockuper.makePerson(tenant, User_N____, resource, false, false, false, false, false);
            mockuper.makePerson(tenant, User__AB__, resource, false, true, true, false, false);
            mockuper.makePerson(tenant, User__ABCD, resource, false, true, true, true, true);
            mockuper.makePerson(tenant, User_G____, resource, true, false, false, false, false);
            mockuper.makePerson(tenant, User_GAB__, resource, true, true, true, false, false);
            mockuper.makePerson(tenant, User_GABCD, resource, true, true, true, true, true);

            mockuper.makeGroup(tenant, Group_N____, resource, false, false, false, false, false);
            mockuper.makeGroup(tenant, Group__AB__, resource, false, true, true, false, false);
            mockuper.makeGroup(tenant, Group_G____, resource, true, false, false, false, false);

            mockuper.makeInstanceWithTag(FILE_G_____, resource, false, false, false, false, false);
            mockuper.makeInstanceWithTag(FILE__A____, resource, true, false, false, false, false);
            mockuper.makeInstanceWithTag(FILE____C__, resource, false, false, true, false, false);
            mockuper.makeInstanceWithTag(FILE__AB___, resource, true, true, false, false, false);
            mockuper.makeInstanceWithTag(FILE__A_C__, resource, true, false, true, false, false);
            mockuper.makeInstanceWithTag(FILE____CD_, resource, false, false, true, true, false);
            mockuper.makeInstanceWithTag(FILE__ABC__, resource, true, true, true, false, false);
            mockuper.makeInstanceWithTag(FILE__A_CD_, resource, true, false, true, true, false);
            mockuper.makeInstanceWithTag(FILE__ABCD_, resource, true, true, true, true, false);
            mockuper.makeInstanceWithTag(FILE______E, resource, false, false, false, false, true);
            mockuper.makeInstanceWithTag(FILE__ABCDE, resource, true, true, true, true, true);
        }
    }

    protected void makeResourceInstanceMembers(Class<? extends XFile> resource)throws ServiceException{
        file_G_____ = mockuper.fetchInstance(resource, FILE_G_____);
        file__A____ = mockuper.fetchInstance(resource, FILE__A____);
        file____C__ = mockuper.fetchInstance(resource, FILE____C__);
        file__AB___ = mockuper.fetchInstance(resource, FILE__AB___);
        file__A_C__ = mockuper.fetchInstance(resource, FILE__A_C__);
        file____CD_ = mockuper.fetchInstance(resource, FILE____CD_);
        file__ABC__ = mockuper.fetchInstance(resource, FILE__ABC__);
        file__A_CD_ = mockuper.fetchInstance(resource, FILE__A_CD_);
        file__ABCD_ = mockuper.fetchInstance(resource, FILE__ABCD_);
        file______E = mockuper.fetchInstance(resource, FILE______E);
        file__ABCDE = mockuper.fetchInstance(resource, FILE__ABCDE);
    }

//    protected void makeAuthoritiesUserMembers(String tenant){
//        user_N____ = permissionEngine.getAuthority(mockuper.PROTECTION_SPEC, tenant, User_N____);
//        user__AB__ = permissionEngine.getAuthority(mockuper.PROTECTION_SPEC, tenant, User__AB__);
//        user__ABCD = permissionEngine.getAuthority(mockuper.PROTECTION_SPEC, tenant, User__ABCD);
//        user_G____ = permissionEngine.getAuthority(mockuper.PROTECTION_SPEC, tenant, User_G____);
//        user_GAB__ = permissionEngine.getAuthority(mockuper.PROTECTION_SPEC, tenant, User_GAB__);
//        user_GABCD = permissionEngine.getAuthority(mockuper.PROTECTION_SPEC, tenant, User_GABCD);
//    }
}


text:
"use strict";

class TableController {
  constructor(table, fixtures) {
    this.table = table;
    this.fixtures = fixtures;
    this.tableCopy = [];
    this.output = [];
    this.outcomes = [
      [3, 0],  // home win
      [1, 1],  // draw
      [0, 3]  // home loss
    ];
  }

  /*
  * Tie break criteria:
  * 1. Name
  *
  * TODO: Add more realistic criteria like GD / Head-to-Head, GF, GA, etc.
  * This is also league specific
  */
  tieBreaker(a, b) {
    if (a.points === b.points) {
      return a.team.localeCompare(b.team);  // alphabetical order (asc)
    }
    return b.points - a.points;  // points order (desc)
  }

  validate() {
    // TODO make sure the table and fixtures are consistent
    return true;
  }

  validateTable(table) {
    if (!Array.isArray(table)) {
      return false;
    }
    for (let i=0; i<table.length; i++) {
      let elem = table[i];
      if (!elem.team || (typeof elem.team !== 'string')) {
        return false;
      }
      if (!elem.points || (typeof elem.points !== 'number')) {
        return false;
      }
    }
    return true;
  }

  validateFixtures(fixtures) {
    if (!Array.isArray(fixtures)) {
      return false;
    }
    for (let i=0; i<fixtures.length; i++) {
      let fixture = fixtures[i];
      if (!fixture.homeTeam || typeof fixture.homeTeam != 'string') {
        return false;
      }
      if (!fixture.awayTeam || typeof fixture.awayTeam != 'string') {
        return false;
      }
    }
    return true;
  }

  initOutput() {
    this.table.sort(this.tieBreaker);
    this.tableCopy = JSON.parse(JSON.stringify(this.table));
    this.output = [];
    let output = this.output;
    this.table.forEach(function(elem, index) {
      let outputElem = JSON.parse(JSON.stringify(elem));
      outputElem.currPos = index + 1;
      outputElem.highestPos = index + 1;
      outputElem.lowestPos = index + 1;
      output.push(outputElem);
    });
  }

  // Main routine
  project(index) {
    if (index >= this.fixtures.length) {
      return;
    }

    let currFixture = this.fixtures[index];
    for (let points of this.outcomes) {
      // TODO trim search tree if this result doesn't affect the table
      this.recordResult(currFixture, points);
      this.updatePositions();
      this.project(index + 1);
      this.undoResult(currFixture, points);
    }
  }

  updatePositions() {
    let output = this.output;
    this.tableCopy.forEach(function(elem, index) {
      let outputTeam = output.find(function(outputElem) {
        return outputElem.team === elem.team;
      });
      let currPos = index + 1;
      outputTeam.highestPos = Math.min(currPos, outputTeam.highestPos);
      outputTeam.lowestPos = Math.max(currPos, outputTeam.lowestPos);
    });
  }

  recordResult(fixture, points) {
    let homeTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.homeTeam;
    });
    let awayTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.awayTeam;
    });
    homeTeam.points += points[0];
    awayTeam.points += points[1];
    this.tableCopy.sort(this.tieBreaker);
  };

  undoResult(fixture, points) {
    let homeTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.homeTeam;
    });
    let awayTeam = this.tableCopy.find(function(elem) {
      return elem.team === fixture.awayTeam;
    });
    homeTeam.points -= points[0];
    awayTeam.points -= points[1];
    this.tableCopy.sort(this.tieBreaker);
  };
}

module.exports = TableController;


text:
$:.unshift File.dirname(__FILE__)
$:.unshift File.join(File.dirname(__FILE__), '..', 'lib')
require 'ebay_trading'
require 'config'
require 'rexml/document'

ebay = EbayTrading::Api.new

begin
  response = ebay.get_product_finder_xsl(:detail_level => 'ReturnAll')

  # There is currently only one stylesheet, but eBay may add more in the future
  file = response.xsl_files.first
  puts "Downloaded version #{file.file_version}"

  # Save the downloaded file
  puts "Saving file to: #{file.file_name}"
  File.open(file.file_name, 'w') do |f|
    f.puts file.file_content
  end
rescue EbayTrading::RequestError => e
  e.errors.each do |error|
    puts error.long_message
  end
end


text:
module Azure::DataFactory::Mgmt::V2018_06_01
  module Models
    #
    # Azure Data Factory nested debug resource.
    #
    class SubResourceDebugResource

      include MsRestAzure

      # @return [String] The resource name.
      attr_accessor :name

      #
      # Mapper for SubResourceDebugResource class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'SubResourceDebugResource',
          type: {
            name: 'Composite',
            class_name: 'SubResourceDebugResource',
            model_properties: {
              name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
module ApplicationHelper
  def bootstrap_class_for flash_type
    case flash_type.to_sym
    when :success;  'alert-success'
    when :error;    'alert-danger'
    when :alert;    'alert-warning'
    when :notice;   'alert-info'
    else; flash_type.to_s
    end
  end
end