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

import java.util.Collection;
import java.util.concurrent.TimeUnit;

import org.apache.activemq.artemis.api.core.Message;

import org.apache.activemq.artemis.api.core.SimpleString;
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.ClientProducer;
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.DivertConfiguration;
import org.apache.activemq.artemis.core.postoffice.Binding;
import org.apache.activemq.artemis.core.postoffice.impl.DivertBinding;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.ActiveMQServers;
import org.apache.activemq.artemis.core.server.Divert;
import org.apache.activemq.artemis.api.core.RoutingType;

import org.apache.activemq.artemis.core.server.transformer.Transformer;
import org.apache.activemq.artemis.core.server.impl.ActiveMQServerImpl;
import org.apache.activemq.artemis.core.server.impl.ServiceRegistryImpl;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.junit.Assert;
import org.junit.Test;

public class DivertTest extends ActiveMQTestBase {

   private static final int TIMEOUT = 3000;

   @Test
   public void testSingleNonExclusiveDivert() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      session.createQueue(new SimpleString(forwardAddress), RoutingType.MULTICAST, queueName1, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName2, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      final int numMessages = 1;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         Assert.assertEquals("forwardAddress", message.getAddress());

         Assert.assertEquals("testAddress", message.getStringProperty(Message.HDR_ORIGINAL_ADDRESS));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         Assert.assertEquals("testAddress", message.getAddress());

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());
   }

   @Test
   public void testSingleNonExclusiveDivertWithRoutingType() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      session.createQueue(new SimpleString(forwardAddress), RoutingType.ANYCAST, queueName1, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName2, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      final int numMessages = 1;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.setRoutingType(RoutingType.MULTICAST);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());
   }

   @Test
   public void testSingleExclusiveDivertWithRoutingType() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress).setExclusive(true);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      session.createQueue(new SimpleString(forwardAddress), RoutingType.ANYCAST, queueName1, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName2, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      final int numMessages = 1;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.setRoutingType(RoutingType.MULTICAST);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());
   }

   @Test
   public void testSingleDivertWithExpiry() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      final String expiryAddress = "expiryAddress";

      AddressSettings expirySettings = new AddressSettings().setExpiryAddress(new SimpleString(expiryAddress));

      DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf).clearAddressesSettings().addAddressesSetting("#", expirySettings);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, true));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, false, false);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      session.createQueue(new SimpleString(forwardAddress), RoutingType.MULTICAST, queueName1, null, true);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName2, null, true);

      session.createQueue(new SimpleString(expiryAddress), RoutingType.MULTICAST, new SimpleString(expiryAddress), null, true);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      final int numMessages = 1;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(true);

         message.putIntProperty(propKey, i);

         message.setExpiration(System.currentTimeMillis() + 1000);

         producer.send(message);
      }
      session.commit();

      // this context is validating if these messages are routed correctly
      {
         int count1 = 0;
         ClientMessage message = null;
         while ((message = consumer1.receiveImmediate()) != null) {
            message.acknowledge();
            count1++;
         }

         int count2 = 0;
         while ((message = consumer2.receiveImmediate()) != null) {
            message.acknowledge();
            count2++;
         }

         assertEquals(1, count1);
         assertEquals(1, count2);
         session.rollback();
      }
      Thread.sleep(2000);

      // it must been expired by now
      assertNull(consumer1.receiveImmediate());
      // it must been expired by now
      assertNull(consumer2.receiveImmediate());

      int countOriginal1 = 0;
      int countOriginal2 = 0;
      ClientConsumer consumerExpiry = session.createConsumer(expiryAddress);

      for (int i = 0; i < numMessages * 2; i++) {
         ClientMessage message = consumerExpiry.receive(5000);
         System.out.println("Received message " + message);
         assertNotNull(message);

         if (message.getStringProperty(Message.HDR_ORIGINAL_QUEUE).equals("divert1")) {
            countOriginal1++;
         } else if (message.getStringProperty(Message.HDR_ORIGINAL_QUEUE).equals("queue2")) {
            countOriginal2++;
         } else {
            System.out.println("message not part of any expired queue" + message);
         }
      }

      assertEquals(numMessages, countOriginal1);
      assertEquals(numMessages, countOriginal2);
   }

   @Test
   public void testSingleNonExclusiveDivert2() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress), RoutingType.MULTICAST, queueName1, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName2, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testSingleNonExclusiveDivert3() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      session.createQueue(new SimpleString(forwardAddress), RoutingType.MULTICAST, queueName1, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());
   }

   @Test
   public void testSingleExclusiveDivert() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress = "forwardAddress";

      DivertConfiguration divertConf = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress).setExclusive(true);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress), RoutingType.MULTICAST, queueName1, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName2, null, false);
      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName3, null, false);
      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         Assert.assertEquals("forwardAddress", message.getAddress());

         Assert.assertEquals("testAddress", message.getStringProperty(Message.HDR_ORIGINAL_ADDRESS));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      Assert.assertNull(consumer2.receiveImmediate());

      Assert.assertNull(consumer3.receiveImmediate());

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testMultipleNonExclusiveDivert() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1);

      DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2);

      DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), RoutingType.MULTICAST, queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), RoutingType.MULTICAST, queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), RoutingType.MULTICAST, queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testMultipleExclusiveDivert() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1).setExclusive(true);

      DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2).setExclusive(true);

      DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3).setExclusive(true);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), RoutingType.MULTICAST, queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), RoutingType.MULTICAST, queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), RoutingType.MULTICAST, queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testMixExclusiveAndNonExclusiveDiverts() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1).setExclusive(true);

      DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2).setExclusive(true);

      DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), RoutingType.MULTICAST, queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), RoutingType.MULTICAST, queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), RoutingType.MULTICAST, queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      Assert.assertNull(consumer3.receiveImmediate());

      Assert.assertNull(consumer4.receiveImmediate());
   }

   // If no exclusive diverts match then non exclusive ones should be called
   @Test
   public void testSingleExclusiveNonMatchingAndNonExclusiveDiverts() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      final String filter = "animal='antelope'";

      DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("divert1").setAddress(testAddress).setForwardingAddress(forwardAddress1).setExclusive(true).setFilterString(filter);

      DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("divert2").setAddress(testAddress).setForwardingAddress(forwardAddress2);

      DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("divert3").setAddress(testAddress).setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), RoutingType.MULTICAST, queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), RoutingType.MULTICAST, queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), RoutingType.MULTICAST, queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putStringProperty(new SimpleString("animal"), new SimpleString("giraffe"));

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      // for (int i = 0; i < numMessages; i++)
      // {
      // ClientMessage message = consumer1.receive(200);
      //
      // assertNotNull(message);
      //
      // assertEquals((Integer)i, (Integer)message.getProperty(propKey));
      //
      // message.acknowledge();
      // }

      Assert.assertNull(consumer1.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putStringProperty(new SimpleString("animal"), new SimpleString("antelope"));

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      Assert.assertNull(consumer2.receiveImmediate());

      Assert.assertNull(consumer3.receiveImmediate());

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testRoundRobinDiverts() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("thename").setAddress(testAddress).setForwardingAddress(forwardAddress1);

      DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert2").setRoutingName("thename").setAddress(testAddress).setForwardingAddress(forwardAddress2);

      DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert3").setRoutingName("thename").setAddress(testAddress).setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), RoutingType.MULTICAST, queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), RoutingType.MULTICAST, queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), RoutingType.MULTICAST, queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; ) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();

         i++;

         if (i == numMessages) {
            break;
         }

         message = consumer2.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();

         i++;

         if (i == numMessages) {
            break;
         }

         message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();

         i++;
      }

      Assert.assertNull(consumer1.receiveImmediate());
      Assert.assertNull(consumer2.receiveImmediate());
      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getObjectProperty(propKey));

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testDeployDivertsSameUniqueName() throws Exception {
      final String testAddress = "testAddress";

      final String forwardAddress1 = "forwardAddress1";
      final String forwardAddress2 = "forwardAddress2";
      final String forwardAddress3 = "forwardAddress3";

      DivertConfiguration divertConf1 = new DivertConfiguration().setName("divert1").setRoutingName("thename1").setAddress(testAddress).setForwardingAddress(forwardAddress1);

      DivertConfiguration divertConf2 = new DivertConfiguration().setName("divert1").setRoutingName("thename2").setAddress(testAddress).setForwardingAddress(forwardAddress2);

      DivertConfiguration divertConf3 = new DivertConfiguration().setName("divert2").setRoutingName("thename3").setAddress(testAddress).setForwardingAddress(forwardAddress3);

      Configuration config = createDefaultInVMConfig().addDivertConfiguration(divertConf1).addDivertConfiguration(divertConf2).addDivertConfiguration(divertConf3);

      ActiveMQServer server = addServer(ActiveMQServers.newActiveMQServer(config, false));

      server.start();

      // Only the first and third should be deployed

      ServerLocator locator = createInVMNonHALocator();

      ClientSessionFactory sf = createSessionFactory(locator);

      ClientSession session = sf.createSession(false, true, true);

      final SimpleString queueName1 = new SimpleString("queue1");

      final SimpleString queueName2 = new SimpleString("queue2");

      final SimpleString queueName3 = new SimpleString("queue3");

      final SimpleString queueName4 = new SimpleString("queue4");

      session.createQueue(new SimpleString(forwardAddress1), RoutingType.MULTICAST, queueName1, null, false);

      session.createQueue(new SimpleString(forwardAddress2), RoutingType.MULTICAST, queueName2, null, false);

      session.createQueue(new SimpleString(forwardAddress3), RoutingType.MULTICAST, queueName3, null, false);

      session.createQueue(new SimpleString(testAddress), RoutingType.MULTICAST, queueName4, null, false);

      session.start();

      ClientProducer producer = session.createProducer(new SimpleString(testAddress));

      ClientConsumer consumer1 = session.createConsumer(queueName1);

      ClientConsumer consumer2 = session.createConsumer(queueName2);

      ClientConsumer consumer3 = session.createConsumer(queueName3);

      ClientConsumer consumer4 = session.createConsumer(queueName4);

      final int numMessages = 10;

      final SimpleString propKey = new SimpleString("testkey");

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = session.createMessage(false);

         message.putIntProperty(propKey, i);

         producer.send(message);
      }

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer1.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer1.receiveImmediate());

      Assert.assertNull(consumer2.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer3.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer3.receiveImmediate());

      for (int i = 0; i < numMessages; i++) {
         ClientMessage message = consumer4.receive(DivertTest.TIMEOUT);

         Assert.assertNotNull(message);

         Assert.assertEquals(i, message.getIntProperty(propKey).intValue());

         message.acknowledge();
      }

      Assert.assertNull(consumer4.receiveImmediate());
   }

   @Test
   public void testInjectedTransformer() throws Exception {
      final SimpleString ADDRESS = new SimpleString("myAddress");
      final String DIVERT = "myDivert";

      ServiceRegistryImpl serviceRegistry = new ServiceRegistryImpl();
      Transformer transformer = new Transformer() {
         @Override
         public Message transform(Message message) {
            return null;
         }
      };
      serviceRegistry.addDivertTransformer(DIVERT, transformer);

      ActiveMQServer server = addServer(new ActiveMQServerImpl(createBasicConfig(), null, null, null, serviceRegistry));
      server.start();
      server.waitForActivation(100, TimeUnit.MILLISECONDS);
      server.createQueue(ADDRESS, RoutingType.MULTICAST, SimpleString.toSimpleString("myQueue"), null, false, false);
      server.deployDivert(new DivertConfiguration().setName(DIVERT).setAddress(ADDRESS.toString()).setForwardingAddress(ADDRESS.toString()));
      Collection<Binding> bindings = server.getPostOffice().getBindingsForAddress(ADDRESS).getBindings();
      Divert divert = null;
      for (Binding binding : bindings) {
         if (binding instanceof DivertBinding) {
            divert = ((DivertBinding) binding).getDivert();
         }
      }
      assertNotNull(divert);
      assertEquals(transformer, divert.getTransformer());
   }
}


text:
#include "libtorrent/disk_buffer_pool.hpp"
#include "libtorrent/assert.hpp"
#include <algorithm>

#if TORRENT_USE_MLOCK && !defined TORRENT_WINDOWS
#include <sys/mman.h>
#endif

#ifdef TORRENT_DISK_STATS
#include "libtorrent/time.hpp"
#endif

namespace libtorrent
{
	disk_buffer_pool::disk_buffer_pool(int block_size)
		: m_block_size(block_size)
		, m_in_use(0)
	{
#if defined TORRENT_DISK_STATS || defined TORRENT_STATS
		m_allocations = 0;
#endif
#ifdef TORRENT_DISK_STATS
		m_log.open("disk_buffers.log", std::ios::trunc);
		m_categories["read cache"] = 0;
		m_categories["write cache"] = 0;

		m_disk_access_log.open("disk_access.log", std::ios::trunc);
#endif
#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
		m_magic = 0x1337;
#endif
	}

#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
	disk_buffer_pool::~disk_buffer_pool()
	{
		TORRENT_ASSERT(m_magic == 0x1337);
		m_magic = 0;
	}
#endif

#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS || defined TORRENT_DISK_STATS
	bool disk_buffer_pool::is_disk_buffer(char* buffer
		, mutex::scoped_lock& l) const
	{
		TORRENT_ASSERT(m_magic == 0x1337);
#ifdef TORRENT_DISK_STATS
		if (m_buf_to_category.find(buffer)
			== m_buf_to_category.end()) return false;
#endif
		return true;
	}

	bool disk_buffer_pool::is_disk_buffer(char* buffer) const
	{
		mutex::scoped_lock l(m_pool_mutex);
		return is_disk_buffer(buffer, l);
	}
#endif

	char* disk_buffer_pool::allocate_buffer(char const* category)
	{
		mutex::scoped_lock l(m_pool_mutex);
		TORRENT_ASSERT(m_magic == 0x1337);
		char* ret = page_aligned_allocator::malloc(m_block_size);
		++m_in_use;
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualLock(ret, m_block_size);
#else
			mlock(ret, m_block_size);
#endif
		}
#endif

#if defined TORRENT_DISK_STATS || defined TORRENT_STATS
		++m_allocations;
#endif
#ifdef TORRENT_DISK_STATS
		++m_categories[category];
		m_buf_to_category[ret] = category;
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
#endif
		TORRENT_ASSERT(ret == 0 || is_disk_buffer(ret, l));
		return ret;
	}

#ifdef TORRENT_DISK_STATS
	void disk_buffer_pool::rename_buffer(char* buf, char const* category)
	{
		mutex::scoped_lock l(m_pool_mutex);
		TORRENT_ASSERT(is_disk_buffer(buf, l));
		TORRENT_ASSERT(m_categories.find(m_buf_to_category[buf])
			!= m_categories.end());
		std::string const& prev_category = m_buf_to_category[buf];
		--m_categories[prev_category];
		m_log << log_time() << " " << prev_category << ": " << m_categories[prev_category] << "\n";

		++m_categories[category];
		m_buf_to_category[buf] = category;
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
		TORRENT_ASSERT(m_categories.find(m_buf_to_category[buf])
			!= m_categories.end());
	}
#endif

	void disk_buffer_pool::free_multiple_buffers(char** bufvec, int numbufs)
	{
		char** end = bufvec + numbufs;
		// sort the pointers in order to maximize cache hits
		std::sort(bufvec, end);

		mutex::scoped_lock l(m_pool_mutex);
		for (; bufvec != end; ++bufvec)
		{
			char* buf = *bufvec;
			TORRENT_ASSERT(buf);
			free_buffer_impl(buf, l);;
		}
	}

	void disk_buffer_pool::free_buffer(char* buf)
	{
		mutex::scoped_lock l(m_pool_mutex);
		free_buffer_impl(buf, l);
	}

	void disk_buffer_pool::free_buffer_impl(char* buf, mutex::scoped_lock& l)
	{
		TORRENT_ASSERT(buf);
		TORRENT_ASSERT(m_magic == 0x1337);
		TORRENT_ASSERT(is_disk_buffer(buf, l));
#if defined TORRENT_DISK_STATS || defined TORRENT_STATS
		--m_allocations;
#endif
#ifdef TORRENT_DISK_STATS
		TORRENT_ASSERT(m_categories.find(m_buf_to_category[buf])
			!= m_categories.end());
		std::string const& category = m_buf_to_category[buf];
		--m_categories[category];
		m_log << log_time() << " " << category << ": " << m_categories[category] << "\n";
		m_buf_to_category.erase(buf);
#endif
#if TORRENT_USE_MLOCK
		if (m_settings.lock_disk_cache)
		{
#ifdef TORRENT_WINDOWS
			VirtualUnlock(buf, m_block_size);
#else
			munlock(buf, m_block_size);
#endif
		}
#endif
		page_aligned_allocator::free(buf);
		--m_in_use;
	}

	void disk_buffer_pool::release_memory()
	{
		TORRENT_ASSERT(m_magic == 0x1337);
	}
}

redpajama_set_name: RedPajamaGithub


text:
module SidekiqQueueStatus
  class QueueLatency < Metric
    DEFAULT_TRESHOLD = 30
    def monitor
      queues_with_latency.each do |name, latency|
        error("Queue #{name} above threshold of #{max_latency(name)}s") if latency > max_latency(name)
      end
    end

    def queues_with_latency
      Hash[*Sidekiq::Queue.all.map { |q| [q.name, q.latency.to_i] }.flatten]
    end

    def max_latency(name)
      Hash.new(DEFAULT_TRESHOLD).merge(Metric.config['queue_tresholds'])[name]
    end
  end
end


text:
RSpec::Matchers.define(:have_scope) do |*name|
  include Remockable::ActiveRecord::Helpers

  attr_accessor :relation

  valid_options %w(with)

  match do |actual|
    if subject.class.respond_to?(attribute)
      scope = if options.key?(:with)
        with = [options[:with]] unless options[:with].is_a?(Array)
        subject.class.send(attribute, *with)
      else
        subject.class.send(attribute)
      end

      if scope.is_a?(ActiveRecord::Relation)
        if relation
          query_matches = scope.to_sql == relation.to_sql
          eager_load_matches = scope.eager_load_values == relation.eager_load_values
          includes_matches = scope.includes_values == relation.includes_values
          lock_matches = scope.lock_value == relation.lock_value
          preload_matches = scope.preload_values == relation.preload_values
          readonly_matches = scope.readonly_value == relation.readonly_value

          query_matches && eager_load_matches && includes_matches && lock_matches && preload_matches && readonly_matches
        else
          true
        end
      end
    end
  end

  def method_missing(method, *args, &block)
    unsupported_query_methods = %w(create_with)

    query_methods = %w(
      eager_load
      from
      group
      having
      includes
      joins
      limit
      lock
      offset
      order
      preload
      readonly
      reorder
      select
      where
    ).collect(&:to_sym)

    if query_methods.include?(method)
      self.relation ||= subject.class.all
      self.relation = relation.send(method, *args)
      self
    else
      super
    end
  end

  failure_message do |actual|
    "Expected #{subject.class.name} to #{description}"
  end

  failure_message_when_negated do |actual|
    "Did not expect #{subject.class.name} to #{description}"
  end

  description do
    with = " with #{options.inspect}" if options.any?
    "have scope #{attribute}#{with}"
  end
end


text:
#ifndef __HV_API_H
#define __HV_API_H

/* Status codes for hypervisor operations. */

/*
 * HV_STATUS_SUCCESS
 * The specified hypercall succeeded
 */
#define HV_STATUS_SUCCESS				((u16)0x0000)

/*
 * HV_STATUS_INVALID_HYPERCALL_CODE
 * The hypervisor does not support the operation because the specified
 * hypercall code is not supported.
 */
#define HV_STATUS_INVALID_HYPERCALL_CODE		((u16)0x0002)

/*
 * HV_STATUS_INVALID_HYPERCALL_INPUT
 * The hypervisor does not support the operation because the encoding for the
 * hypercall input register is not supported.
 */
#define HV_STATUS_INVALID_HYPERCALL_INPUT		((u16)0x0003)

/*
 * HV_STATUS_INVALID_ALIGNMENT
 * The hypervisor could not perform the operation beacuse a parameter has an
 * invalid alignment.
 */
#define HV_STATUS_INVALID_ALIGNMENT			((u16)0x0004)

/*
 * HV_STATUS_INVALID_PARAMETER
 * The hypervisor could not perform the operation beacuse an invalid parameter
 * was specified.
 */
#define HV_STATUS_INVALID_PARAMETER			((u16)0x0005)

/*
 * HV_STATUS_ACCESS_DENIED
 * Access to the specified object was denied.
 */
#define HV_STATUS_ACCESS_DENIED				((u16)0x0006)

/*
 * HV_STATUS_INVALID_PARTITION_STATE
 * The hypervisor could not perform the operation because the partition is
 * entering or in an invalid state.
 */
#define HV_STATUS_INVALID_PARTITION_STATE		((u16)0x0007)

/*
 * HV_STATUS_OPERATION_DENIED
 * The operation is not allowed in the current state.
 */
#define HV_STATUS_OPERATION_DENIED			((u16)0x0008)

/*
 * HV_STATUS_UNKNOWN_PROPERTY
 * The hypervisor does not recognize the specified partition property.
 */
#define HV_STATUS_UNKNOWN_PROPERTY			((u16)0x0009)

/*
 * HV_STATUS_PROPERTY_VALUE_OUT_OF_RANGE
 * The specified value of a partition property is out of range or violates an
 * invariant.
 */
#define HV_STATUS_PROPERTY_VALUE_OUT_OF_RANGE		((u16)0x000A)

/*
 * HV_STATUS_INSUFFICIENT_MEMORY
 * There is not enough memory in the hypervisor pool to complete the operation.
 */
#define HV_STATUS_INSUFFICIENT_MEMORY			((u16)0x000B)

/*
 * HV_STATUS_PARTITION_TOO_DEEP
 * The maximum partition depth has been exceeded for the partition hierarchy.
 */
#define HV_STATUS_PARTITION_TOO_DEEP			((u16)0x000C)

/*
 * HV_STATUS_INVALID_PARTITION_ID
 * A partition with the specified partition Id does not exist.
 */
#define HV_STATUS_INVALID_PARTITION_ID			((u16)0x000D)

/*
 * HV_STATUS_INVALID_VP_INDEX
 * The hypervisor could not perform the operation because the specified VP
 * index is invalid.
 */
#define HV_STATUS_INVALID_VP_INDEX			((u16)0x000E)

/*
 * HV_STATUS_NOT_FOUND
 * The iteration is complete; no addition items in the iteration could be
 * found.
 */
#define HV_STATUS_NOT_FOUND				((u16)0x0010)

/*
 * HV_STATUS_INVALID_PORT_ID
 * The hypervisor could not perform the operation because the specified port
 * identifier is invalid.
 */
#define HV_STATUS_INVALID_PORT_ID			((u16)0x0011)

/*
 * HV_STATUS_INVALID_CONNECTION_ID
 * The hypervisor could not perform the operation because the specified
 * connection identifier is invalid.
 */
#define HV_STATUS_INVALID_CONNECTION_ID			((u16)0x0012)

/*
 * HV_STATUS_INSUFFICIENT_BUFFERS
 * You did not supply enough message buffers to send a message.
 */
#define HV_STATUS_INSUFFICIENT_BUFFERS			((u16)0x0013)

/*
 * HV_STATUS_NOT_ACKNOWLEDGED
 * The previous virtual interrupt has not been acknowledged.
 */
#define HV_STATUS_NOT_ACKNOWLEDGED			((u16)0x0014)

/*
 * HV_STATUS_INVALID_VP_STATE
 * A virtual processor is not in the correct state for the performance of the
 * indicated operation.
 */
#define HV_STATUS_INVALID_VP_STATE			((u16)0x0015)

/*
 * HV_STATUS_ACKNOWLEDGED
 * The previous virtual interrupt has already been acknowledged.
 */
#define HV_STATUS_ACKNOWLEDGED				((u16)0x0016)

/*
 * HV_STATUS_INVALID_SAVE_RESTORE_STATE
 * The indicated partition is not in a valid state for saving or restoring.
 */
#define HV_STATUS_INVALID_SAVE_RESTORE_STATE		((u16)0x0017)

/*
 * HV_STATUS_INVALID_SYNIC_STATE
 * The hypervisor could not complete the operation because a required feature
 * of the synthetic interrupt controller (SynIC) was disabled.
 */
#define HV_STATUS_INVALID_SYNIC_STATE			((u16)0x0018)

/*
 * HV_STATUS_OBJECT_IN_USE
 * The hypervisor could not perform the operation because the object or value
 * was either already in use or being used for a purpose that would not permit
 * completing the operation.
 */
#define HV_STATUS_OBJECT_IN_USE				((u16)0x0019)

/*
 * HV_STATUS_INVALID_PROXIMITY_DOMAIN_INFO
 * The proximity domain information is invalid.
 */
#define HV_STATUS_INVALID_PROXIMITY_DOMAIN_INFO		((u16)0x001A)

/*
 * HV_STATUS_NO_DATA
 * An attempt to retrieve debugging data failed because none was available.
 */
#define HV_STATUS_NO_DATA				((u16)0x001B)

/*
 * HV_STATUS_INACTIVE
 * The physical connection being used for debuggging has not recorded any
 * receive activity since the last operation.
 */
#define HV_STATUS_INACTIVE				((u16)0x001C)

/*
 * HV_STATUS_NO_RESOURCES
 * There are not enough resources to complete the operation.
 */
#define HV_STATUS_NO_RESOURCES				((u16)0x001D)

/*
 * HV_STATUS_FEATURE_UNAVAILABLE
 * A hypervisor feature is not available to the user.
 */
#define HV_STATUS_FEATURE_UNAVAILABLE			((u16)0x001E)

/*
 * HV_STATUS_UNSUCCESSFUL
 * {Operation Failed} The requested operation was unsuccessful.
 */
#define HV_STATUS_UNSUCCESSFUL				((u16)0x1001)

/*
 * HV_STATUS_INSUFFICIENT_BUFFER
 * The specified buffer was too small to contain all of the requested data.
 */
#define HV_STATUS_INSUFFICIENT_BUFFER			((u16)0x1002)

/*
 * HV_STATUS_GPA_NOT_PRESENT
 * The guest physical address is not currently associated with a system
 * physical address.
 */
#define HV_STATUS_GPA_NOT_PRESENT			((u16)0x1003)

/*
 * HV_STATUS_GUEST_PAGE_FAULT
 * The operation would have resulted in a page fault in the guest.
 */
#define HV_STATUS_GUEST_PAGE_FAULT			((u16)0x1004)

/*
 * HV_STATUS_RUNDOWN_DISABLED
 * The operation cannot proceed as the rundown object was marked disabled.
 */
#define HV_STATUS_RUNDOWN_DISABLED			((u16)0x1005)

/*
 * HV_STATUS_KEY_ALREADY_EXISTS
 * The entry cannot be added as another entry with the same key already exists.
 */
#define HV_STATUS_KEY_ALREADY_EXISTS			((u16)0x1006)

/*
 * HV_STATUS_GPA_INTERCEPT
 * The operation resulted an intercept on a region of guest physical memory.
 */
#define HV_STATUS_GPA_INTERCEPT				((u16)0x1007)

/*
 * HV_STATUS_GUEST_GENERAL_PROTECTION_FAULT
 * The operation would have resulted in a general protection fault in the
 * guest.
 */
#define HV_STATUS_GUEST_GENERAL_PROTECTION_FAULT	((u16)0x1008)

/*
 * HV_STATUS_GUEST_STACK_FAULT
 * The operation would have resulted in a stack fault in the guest.
 */
#define HV_STATUS_GUEST_STACK_FAULT			((u16)0x1009)

/*
 * HV_STATUS_GUEST_INVALID_OPCODE_FAULT
 * The operation would have resulted in an invalid opcode fault in the guest.
 */
#define HV_STATUS_GUEST_INVALID_OPCODE_FAULT		((u16)0x100A)

/*
 * HV_STATUS_FINALIZE_INCOMPLETE
 * The partition is not completely finalized.
 */
#define HV_STATUS_FINALIZE_INCOMPLETE			((u16)0x100B)

/*
 * HV_STATUS_GUEST_MACHINE_CHECK_ABORT
 * The operation would have resulted in an machine check abort in the guest.
 */
#define HV_STATUS_GUEST_MACHINE_CHECK_ABORT		((u16)0x100C)

/*
 * HV_STATUS_ILLEGAL_OVERLAY_ACCESS
 * An illegal access was attempted to an overlay page.
 */
#define HV_STATUS_ILLEGAL_OVERLAY_ACCESS		((u16)0x100D)

/*
 * HV_STATUS_INSUFFICIENT_SYSTEM_VA
 * There is not enough system VA space available to satisfy the request,
 */
#define HV_STATUS_INSUFFICIENT_SYSTEM_VA		((u16)0x100E)

/*
 * HV_STATUS_VIRTUAL_ADDRESS_NOT_MAPPED
 * The passed virtual address was not mapped in the hypervisor address space.
 */
#define HV_STATUS_VIRTUAL_ADDRESS_NOT_MAPPED		((u16)0x100F)

/*
 * HV_STATUS_NOT_IMPLEMENTED
 * The requested operation is not implemented in this version of the
 * hypervisor.
 */
#define HV_STATUS_NOT_IMPLEMENTED			((u16)0x1010)

/*
 * HV_STATUS_VMX_INSTRUCTION_FAILED
 * The requested VMX instruction failed to complete succesfully.
 */
#define HV_STATUS_VMX_INSTRUCTION_FAILED		((u16)0x1011)

/*
 * HV_STATUS_VMX_INSTRUCTION_FAILED_WITH_STATUS
 * The requested VMX instruction failed to complete succesfully indicating
 * status.
 */
#define HV_STATUS_VMX_INSTRUCTION_FAILED_WITH_STATUS	((u16)0x1012)

/*
 * HV_STATUS_MSR_ACCESS_FAILED
 * The requested access to the model specific register failed.
 */
#define HV_STATUS_MSR_ACCESS_FAILED		((u16)0x1013)

/*
 * HV_STATUS_CR_ACCESS_FAILED
 * The requested access to the control register failed.
 */
#define HV_STATUS_CR_ACCESS_FAILED		((u16)0x1014)

/*
 * HV_STATUS_TIMEOUT
 * The specified timeout expired before the operation completed.
 */
#define HV_STATUS_TIMEOUT			((u16)0x1016)

/*
 * HV_STATUS_MSR_INTERCEPT
 * The requested access to the model specific register generated an intercept.
 */
#define HV_STATUS_MSR_INTERCEPT			((u16)0x1017)

/*
 * HV_STATUS_CPUID_INTERCEPT
 * The CPUID instruction generated an intercept.
 */
#define HV_STATUS_CPUID_INTERCEPT		((u16)0x1018)

/*
 * HV_STATUS_REPEAT_INSTRUCTION
 * The current instruction should be repeated and the instruction pointer not
 * advanced.
 */
#define HV_STATUS_REPEAT_INSTRUCTION		((u16)0x1019)

/*
 * HV_STATUS_PAGE_PROTECTION_VIOLATION
 * The current instruction should be repeated and the instruction pointer not
 * advanced.
 */
#define HV_STATUS_PAGE_PROTECTION_VIOLATION	((u16)0x101A)

/*
 * HV_STATUS_PAGE_TABLE_INVALID
 * The current instruction should be repeated and the instruction pointer not
 * advanced.
 */
#define HV_STATUS_PAGE_TABLE_INVALID		((u16)0x101B)

/*
 * HV_STATUS_PAGE_NOT_PRESENT
 * The current instruction should be repeated and the instruction pointer not
 * advanced.
 */
#define HV_STATUS_PAGE_NOT_PRESENT		((u16)0x101C)

/*
 * HV_STATUS_IO_INTERCEPT
 * The requested access to the I/O port generated an intercept.
 */
#define HV_STATUS_IO_INTERCEPT				((u16)0x101D)

/*
 * HV_STATUS_NOTHING_TO_DO
 * There is nothing to do.
 */
#define HV_STATUS_NOTHING_TO_DO				((u16)0x101E)

/*
 * HV_STATUS_THREAD_TERMINATING
 * The requested thread is terminating.
 */
#define HV_STATUS_THREAD_TERMINATING			((u16)0x101F)

/*
 * HV_STATUS_SECTION_ALREADY_CONSTRUCTED
 * The specified section was already constructed.
 */
#define HV_STATUS_SECTION_ALREADY_CONSTRUCTED		((u16)0x1020)

/* HV_STATUS_SECTION_NOT_ALREADY_CONSTRUCTED
 * The specified section was not already constructed.
 */
#define HV_STATUS_SECTION_NOT_ALREADY_CONSTRUCTED	((u16)0x1021)

/*
 * HV_STATUS_PAGE_ALREADY_COMMITTED
 * The specified virtual address was already backed by physical memory.
 */
#define HV_STATUS_PAGE_ALREADY_COMMITTED		((u16)0x1022)

/*
 * HV_STATUS_PAGE_NOT_ALREADY_COMMITTED
 * The specified virtual address was not already backed by physical memory.
 */
#define HV_STATUS_PAGE_NOT_ALREADY_COMMITTED		((u16)0x1023)

/*
 * HV_STATUS_COMMITTED_PAGES_REMAIN
 * Committed pages remain in the section.
 */
#define HV_STATUS_COMMITTED_PAGES_REMAIN		((u16)0x1024)

/*
 * HV_STATUS_NO_REMAINING_COMMITTED_PAGES
 * No additional committed pages beyond the specified page exist in the
 * section.
 */
#define HV_STATUS_NO_REMAINING_COMMITTED_PAGES		((u16)0x1025)

/*
 * HV_STATUS_INSUFFICIENT_COMPARTMENT_VA
 * The VA space of the compartment is exhausted.
 */
#define HV_STATUS_INSUFFICIENT_COMPARTMENT_VA		((u16)0x1026)

/*
 * HV_STATUS_DEREF_SPA_LIST_FULL
 * The SPA dereference list is full, and there are additional entries to be
 * added to it.
 */
#define HV_STATUS_DEREF_SPA_LIST_FULL			((u16)0x1027)

/*
 * HV_STATUS_GPA_OUT_OF_RANGE
 * The supplied GPA is out of range.
 */
#define HV_STATUS_GPA_OUT_OF_RANGE			((u16)0x1027)

/*
 * HV_STATUS_NONVOLATILE_XMM_STALE
 * The XMM register that was being accessed is stale.
 */
#define HV_STATUS_NONVOLATILE_XMM_STALE			((u16)0x1028)

/* HV_STATUS_UNSUPPORTED_PROCESSOR
 * The hypervisor does not support the processors in this system.
 */
#define HV_STATUS_UNSUPPORTED_PROCESSOR			((u16)0x1029)

/*
 * HV_STATUS_INSUFFICIENT_CROM_SPACE
 * Insufficient space existed for copying over the CROM contents.
 */
#define HV_STATUS_INSUFFICIENT_CROM_SPACE		((u16)0x2000)

/*
 * HV_STATUS_BAD_CROM_FORMAT
 * The contents of the CROM failed validation attempts.
 */
#define HV_STATUS_BAD_CROM_FORMAT			((u16)0x2001)

/*
 * HV_STATUS_UNSUPPORTED_CROM_FORMAT
 * The contents of the CROM contain contents the parser doesn't support.
 */
#define HV_STATUS_UNSUPPORTED_CROM_FORMAT		((u16)0x2002)

/*
 * HV_STATUS_UNSUPPORTED_CONTROLLER
 * The register format of the OHCI controller specified for debugging is not
 * supported.
 */
#define HV_STATUS_UNSUPPORTED_CONTROLLER		((u16)0x2003)

/*
 * HV_STATUS_CROM_TOO_LARGE
 * The CROM contents were to large to copy over.
 */
#define HV_STATUS_CROM_TOO_LARGE			((u16)0x2004)

/*
 * HV_STATUS_CONTROLLER_IN_USE
 * The OHCI controller specified for debugging cannot be used as it is already
 * in use.
 */
#define HV_STATUS_CONTROLLER_IN_USE			((u16)0x2005)

/*
 * The below CPUID leaves are present if VersionAndFeatures.HypervisorPresent
 * is set by CPUID(HvCpuIdFunctionVersionAndFeatures).
 */
enum hv_cpuid_function {
	HvCpuIdFunctionVersionAndFeatures		= 0x00000001,
	HvCpuIdFunctionHvVendorAndMaxFunction		= 0x40000000,
	HvCpuIdFunctionHvInterface			= 0x40000001,

	/*
	 * The remaining functions depend on the value of
	 * HvCpuIdFunctionInterface
	 */
	HvCpuIdFunctionMsHvVersion			= 0x40000002,
	HvCpuIdFunctionMsHvFeatures			= 0x40000003,
	HvCpuIdFunctionMsHvEnlightenmentInformation	= 0x40000004,
	HvCpuIdFunctionMsHvImplementationLimits		= 0x40000005,
};

/* Define the virtual APIC registers */
#define HV_X64_MSR_EOI			(0x40000070)
#define HV_X64_MSR_ICR			(0x40000071)
#define HV_X64_MSR_TPR			(0x40000072)
#define HV_X64_MSR_APIC_ASSIST_PAGE	(0x40000073)

/* Define version of the synthetic interrupt controller. */
#define HV_SYNIC_VERSION		(1)

/* Define synthetic interrupt controller model specific registers. */
#define HV_X64_MSR_SCONTROL		(0x40000080)
#define HV_X64_MSR_SVERSION		(0x40000081)
#define HV_X64_MSR_SIEFP		(0x40000082)
#define HV_X64_MSR_SIMP			(0x40000083)
#define HV_X64_MSR_EOM			(0x40000084)
#define HV_X64_MSR_SINT0		(0x40000090)
#define HV_X64_MSR_SINT1		(0x40000091)
#define HV_X64_MSR_SINT2		(0x40000092)
#define HV_X64_MSR_SINT3		(0x40000093)
#define HV_X64_MSR_SINT4		(0x40000094)
#define HV_X64_MSR_SINT5		(0x40000095)
#define HV_X64_MSR_SINT6		(0x40000096)
#define HV_X64_MSR_SINT7		(0x40000097)
#define HV_X64_MSR_SINT8		(0x40000098)
#define HV_X64_MSR_SINT9		(0x40000099)
#define HV_X64_MSR_SINT10		(0x4000009A)
#define HV_X64_MSR_SINT11		(0x4000009B)
#define HV_X64_MSR_SINT12		(0x4000009C)
#define HV_X64_MSR_SINT13		(0x4000009D)
#define HV_X64_MSR_SINT14		(0x4000009E)
#define HV_X64_MSR_SINT15		(0x4000009F)

/* Define the expected SynIC version. */
#define HV_SYNIC_VERSION_1		(0x1)

/* Define synthetic interrupt controller message constants. */
#define HV_MESSAGE_SIZE			(256)
#define HV_MESSAGE_PAYLOAD_BYTE_COUNT	(240)
#define HV_MESSAGE_PAYLOAD_QWORD_COUNT	(30)
#define HV_ANY_VP			(0xFFFFFFFF)

/* Define synthetic interrupt controller flag constants. */
#define HV_EVENT_FLAGS_COUNT		(256 * 8)
#define HV_EVENT_FLAGS_BYTE_COUNT	(256)
#define HV_EVENT_FLAGS_DWORD_COUNT	(256 / sizeof(u32))

/* Define hypervisor message types. */
enum hv_message_type {
	HvMessageTypeNone			= 0x00000000,

	/* Memory access messages. */
	HvMessageTypeUnmappedGpa		= 0x80000000,
	HvMessageTypeGpaIntercept		= 0x80000001,

	/* Timer notification messages. */
	HvMessageTimerExpired			= 0x80000010,

	/* Error messages. */
	HvMessageTypeInvalidVpRegisterValue	= 0x80000020,
	HvMessageTypeUnrecoverableException	= 0x80000021,
	HvMessageTypeUnsupportedFeature		= 0x80000022,

	/* Trace buffer complete messages. */
	HvMessageTypeEventLogBufferComplete	= 0x80000040,

	/* Platform-specific processor intercept messages. */
	HvMessageTypeX64IoPortIntercept		= 0x80010000,
	HvMessageTypeX64MsrIntercept		= 0x80010001,
	HvMessageTypeX64CpuidIntercept		= 0x80010002,
	HvMessageTypeX64ExceptionIntercept	= 0x80010003,
	HvMessageTypeX64ApicEoi			= 0x80010004,
	HvMessageTypeX64LegacyFpError		= 0x80010005
};

/* Define the number of synthetic interrupt sources. */
#define HV_SYNIC_SINT_COUNT		(16)
#define HV_SYNIC_STIMER_COUNT		(4)

/* Define invalid partition identifier. */
#define HV_PARTITION_ID_INVALID		((u64)0x0)

/* Define connection identifier type. */
union hv_connection_id {
	u32 Asu32;
	struct {
		u32 Id:24;
		u32 Reserved:8;
	} u;
};

/* Define port identifier type. */
union hv_port_id {
	u32 Asu32;
	struct {
		u32 Id:24;
		u32 Reserved:8;
	} u ;
};

/* Define port type. */
enum hv_port_type {
	HvPortTypeMessage	= 1,
	HvPortTypeEvent		= 2,
	HvPortTypeMonitor	= 3
};

/* Define port information structure. */
struct hv_port_info {
	enum hv_port_type PortType;
	u32 Padding;
	union {
		struct {
			u32 TargetSint;
			u32 TargetVp;
			u64 RsvdZ;
		} MessagePortInfo;
		struct {
			u32 TargetSint;
			u32 TargetVp;
			u16 BaseFlagNumber;
			u16 FlagCount;
			u32 RsvdZ;
		} EventPortInfo;
		struct {
			u64 MonitorAddress;
			u64 RsvdZ;
		} MonitorPortInfo;
	};
};

struct hv_connection_info {
	enum hv_port_type PortType;
	u32 Padding;
	union {
		struct {
			u64 RsvdZ;
		} MessageConnectionInfo;
		struct {
			u64 RsvdZ;
		} EventConnectionInfo;
		struct {
			u64 MonitorAddress;
		} MonitorConnectionInfo;
	};
};

/* Define synthetic interrupt controller message flags. */
union hv_message_flags {
	u8 Asu8;
	struct {
		u8 MessagePending:1;
		u8 Reserved:7;
	};
};

/* Define synthetic interrupt controller message header. */
struct hv_message_header {
	enum hv_message_type MessageType;
	u8 PayloadSize;
	union hv_message_flags MessageFlags;
	u8 Reserved[2];
	union {
		u64 Sender;
		union hv_port_id Port;
	};
};

/* Define timer message payload structure. */
struct hv_timer_message_payload {
	u32 TimerIndex;
	u32 Reserved;
	u64 ExpirationTime;	/* When the timer expired */
	u64 DeliveryTime;	/* When the message was delivered */
};

/* Define synthetic interrupt controller message format. */
struct hv_message {
	struct hv_message_header Header;
	union {
		u64 Payload[HV_MESSAGE_PAYLOAD_QWORD_COUNT];
	} u ;
};

/* Define the number of message buffers associated with each port. */
#define HV_PORT_MESSAGE_BUFFER_COUNT	(16)

/* Define the synthetic interrupt message page layout. */
struct hv_message_page {
	struct hv_message SintMessage[HV_SYNIC_SINT_COUNT];
};

/* Define the synthetic interrupt controller event flags format. */
union hv_synic_event_flags {
	u8 Flags8[HV_EVENT_FLAGS_BYTE_COUNT];
	u32 Flags32[HV_EVENT_FLAGS_DWORD_COUNT];
};

/* Define the synthetic interrupt flags page layout. */
struct hv_synic_event_flags_page {
	union hv_synic_event_flags SintEventFlags[HV_SYNIC_SINT_COUNT];
};

/* Define SynIC control register. */
union hv_synic_scontrol {
	u64 AsUINT64;
	struct {
		u64 Enable:1;
		u64 Reserved:63;
	};
};

/* Define synthetic interrupt source. */
union hv_synic_sint {
	u64 AsUINT64;
	struct {
		u64 Vector:8;
		u64 Reserved1:8;
		u64 Masked:1;
		u64 AutoEoi:1;
		u64 Reserved2:46;
	};
};

/* Define the format of the SIMP register */
union hv_synic_simp {
	u64 AsUINT64;
	struct {
		u64 SimpEnabled:1;
		u64 Preserved:11;
		u64 BaseSimpGpa:52;
	};
};

/* Define the format of the SIEFP register */
union hv_synic_siefp {
	u64 AsUINT64;
	struct {
		u64 SiefpEnabled:1;
		u64 Preserved:11;
		u64 BaseSiefpGpa:52;
	};
};

/* Definitions for the monitored notification facility */
union hv_monitor_trigger_group {
	u64 AsUINT64;
	struct {
		u32 Pending;
		u32 Armed;
	};
};

struct hv_monitor_parameter {
	union hv_connection_id ConnectionId;
	u16 FlagNumber;
	u16 RsvdZ;
};

union hv_monitor_trigger_state {
	u32 Asu32;

	struct {
		u32 GroupEnable:4;
		u32 RsvdZ:28;
	};
};

/* struct hv_monitor_page Layout */
/* ------------------------------------------------------ */
/* | 0   | TriggerState (4 bytes) | Rsvd1 (4 bytes)     | */
/* | 8   | TriggerGroup[0]                              | */
/* | 10  | TriggerGroup[1]                              | */
/* | 18  | TriggerGroup[2]                              | */
/* | 20  | TriggerGroup[3]                              | */
/* | 28  | Rsvd2[0]                                     | */
/* | 30  | Rsvd2[1]                                     | */
/* | 38  | Rsvd2[2]                                     | */
/* | 40  | NextCheckTime[0][0]    | NextCheckTime[0][1] | */
/* | ...                                                | */
/* | 240 | Latency[0][0..3]                             | */
/* | 340 | Rsvz3[0]                                     | */
/* | 440 | Parameter[0][0]                              | */
/* | 448 | Parameter[0][1]                              | */
/* | ...                                                | */
/* | 840 | Rsvd4[0]                                     | */
/* ------------------------------------------------------ */
struct hv_monitor_page {
	union hv_monitor_trigger_state TriggerState;
	u32 RsvdZ1;

	union hv_monitor_trigger_group TriggerGroup[4];
	u64 RsvdZ2[3];

	s32 NextCheckTime[4][32];

	u16 Latency[4][32];
	u64 RsvdZ3[32];

	struct hv_monitor_parameter Parameter[4][32];

	u8 RsvdZ4[1984];
};

/* Declare the various hypercall operations. */
enum hv_call_code {
	HvCallPostMessage	= 0x005c,
	HvCallSignalEvent	= 0x005d,
};

/* Definition of the HvPostMessage hypercall input structure. */
struct hv_input_post_message {
	union hv_connection_id ConnectionId;
	u32 Reserved;
	enum hv_message_type MessageType;
	u32 PayloadSize;
	u64 Payload[HV_MESSAGE_PAYLOAD_QWORD_COUNT];
};

/* Definition of the HvSignalEvent hypercall input structure. */
struct hv_input_signal_event {
	union hv_connection_id ConnectionId;
	u16 FlagNumber;
	u16 RsvdZ;
};

/*
 * Versioning definitions used for guests reporting themselves to the
 * hypervisor, and visa versa.
 */

/* Version info reported by guest OS's */
enum hv_guest_os_vendor {
	HvGuestOsVendorMicrosoft	= 0x0001
};

enum hv_guest_os_microsoft_ids {
	HvGuestOsMicrosoftUndefined	= 0x00,
	HvGuestOsMicrosoftMSDOS		= 0x01,
	HvGuestOsMicrosoftWindows3x	= 0x02,
	HvGuestOsMicrosoftWindows9x	= 0x03,
	HvGuestOsMicrosoftWindowsNT	= 0x04,
	HvGuestOsMicrosoftWindowsCE	= 0x05
};

/*
 * Declare the MSR used to identify the guest OS.
 */
#define HV_X64_MSR_GUEST_OS_ID	0x40000000

union hv_x64_msr_guest_os_id_contents {
	u64 AsUINT64;
	struct {
		u64 BuildNumber:16;
		u64 ServiceVersion:8; /* Service Pack, etc. */
		u64 MinorVersion:8;
		u64 MajorVersion:8;
		u64 OsId:8; /* enum hv_guest_os_microsoft_ids (if Vendor=MS) */
		u64 VendorId:16; /* enum hv_guest_os_vendor */
	};
};

/*
 * Declare the MSR used to setup pages used to communicate with the hypervisor.
 */
#define HV_X64_MSR_HYPERCALL	0x40000001

union hv_x64_msr_hypercall_contents {
	u64 AsUINT64;
	struct {
		u64 Enable:1;
		u64 Reserved:11;
		u64 GuestPhysicalAddress:52;
	};
};

#endif


text:
Do you have a question regarding stack's usage that isn't covered by [the docs](http://haskellstack.org)?
In that case please ask your question on [Stack Overflow](http://stackoverflow.com) and use [the haskell-stack tag](http://stackoverflow.com/questions/tagged/haskell-stack).
This way your question will be more easily discoverable by other people with the same question.

Question related to stack project templates? Please report it at the [stack-templates](https://github.com/commercialhaskell/stack-templates) repository instead.

If you're reporting a bug please follow the steps below:

Make sure that you are using the latest release (currently stack-1.4.0).
See the [upgrade instructions](http://docs.haskellstack.org/en/stable/install_and_upgrade/#upgrade) to upgrade.

Please use the following schema for your bug report:

### General summary/comments (optional)

### Steps to reproduce

For example:

1. Remove directory *blah*.
2. Run command `stack blah`.
3. Edit file blah.
4. Run command `stack blah`.

Include any `.yaml` configuration if relevant.

### Expected

What you expected to see and happen.

### Actual

What actually happened.

If you suspect that a stack command misbehaved, please include the output of that command in `--verbose` mode.
If the output is larger than a page please paste the output in a [Gist](https://gist.github.com/).

```
$ stack <your command here> <args> --verbose
<output>
```

### Stack version

```
$ stack --version
Version 1.2.0, Git revision 241cd07d576d9c0c0e712e83d947e3dd64541c42 (4054 commits) x86_64 hpack-0.14.0
```

### Method of installation

* Official binary, downloaded from stackage.org or fpcomplete's package repository
* Via cabal-install
* An unofficial package repository (please specify which)
* Other (please specify)


text:
SUBDIR=	include include/arm26 include/arm32

# XXX VIDC includes are needed by Xarm32vidc
SUBDIR+= iomd

.include <bsd.kinc.mk>


text:
{# -*- coding: utf-8 -*-

  This file is part of Invenio.
  Copyright (C) 2015-2018 CERN.

  Invenio is free software; you can redistribute it and/or modify it
  under the terms of the MIT License; see LICENSE file for more details.
#}
{%- extends "invenio_oauth2server/base.html" %}

{%- block page_body %}
{%- block settings_content %}
{%- block settings_body %}
{%- block settings_form %}{%- endblock settings_form %}
{%- endblock settings_body %}
{%- endblock settings_content %}
{%- endblock page_body %}


text:
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  before_action :authenticate_user!

  # :nocov:
  def new_session_path(_scope)
    new_user_session_path
  end
  # :nocov:

  private

  # :nocov:
  def after_sign_out_path_for(_resource_or_scope)
    new_user_session_path
  end
  # :nocov:
end


text:
#ifndef PREPROCESS_INCLUDE_FILE
#define PREPROCESS_INCLUDE_FILE

#define NULL_RECORD		0
#define DUPLICATE_COLUMN	7
#define DUPLICATE_ROW   	8
#define ZERO_ROW		1
#define ZERO_COLUMN		2
#define FIXED_VARIABLE		3
#define SINGLETON_ROW		4
#define FREE_COLUMN_SINGLETON	5
#define FORCED_ROW              6

#define NORMAL			0
#define FREE			1

#define TRUE       1
#define FALSE      0
#define TINY       1.0e-10

#define STILL_ACTIVE		0
#define INFEASIBLE		-1
#define UNBOUNDED 		-2
#define PREPROCESSING_ERROR	-3

#define RANGELOWER              -1
#define RANGEUPPER              1

#define STACK_SIZE_FACTOR      0.1

typedef struct  {
  int size; /* size of the sparse vector storage structures in
		this record */
  int *Index;
  double *Value;
} SparseVector;

typedef struct  {
  int Split1, Split2; /* indices of split variable */
                      /* Column Split2 is the deleted one */
  int Type; /* Type is NORMAL if the two columns are positive
	       multiples of each other; FREE otherwise */
  double multiplier; /* value for which (Split2) = multiplier*(Split1) */
  double costdiff;   /* c(Split2) - multiplier * c(Split1) */
                     /* Any discrepancy affects the recovery strategy */
} DuplicateCol;

typedef struct  {
  int Split1, Split2; /* indices of duplicate row; Split1 < Split2 */
  /* Row Split2 is deleted */
} DuplicateRow;

typedef struct  {
  int RowIndex; /* index of deleted row */
} ZeroRow;

typedef struct  {
  int ColumnIndex; /* index of deleted column */
  double Value; /* value of fixed variable */
  double cshiftChange; /* change to the constant term in the primal objective */
  double cElement; /* the deleted member of the cost vector */
} ZeroColumn;

typedef struct  {
  int ColumnIndex; /* index of fixed column */
  double Value; /* value of fixed variable */
  double cshiftChange; /* change to the constant term in the primal objective */
  double cElement; /* the deleted member of the cost vector */
  SparseVector *DeletedColumn; /* the deleted column */
} FixedVariable;

typedef struct  {
  int ColumnIndex; /* column index */
  int RowIndex;    /* row index */
  double Value; /* value of fixed variable */
  double cshiftChange; /* change to the constant term in the primal objective */
  double cElement; /* the deleted member of the cost vector */
  double bElement; /* the deleted element from the rhs */
  double aElement; /* the deleted element from the matrix */
  SparseVector *DeletedColumn; /* the deleted column */
} SingletonRow;

typedef struct  {
  int ColumnIndex; /* column index */
  int RowIndex;    /* row index */
  double cshiftChange; /* change to the constant term in the primal objective */
  double bElement; /* the deleted element from the rhs */
  double aElement; /* the deleted element from the matrix */
  double cElement; /* the deleted element from the cost vector */
  SparseVector *DeletedRow; /* the deleted row */
} FreeColumnSingleton;

typedef struct {
  int RowIndex;    /* row index */
  int LowerUpper;  /* indicates whether row was forced to upper or lower
	end of its range RANGELOWER=-1, RANGEUPPER=+1 */
  double cshiftChange; /* change to the constant term in the primal objective */
  SparseVector *DeletedRow; /* the deleted row */
  SparseVector *Values;     /* values of the fixed variables */
  SparseVector *cElements;  /* costs for these fixed variables */
  SparseVector **DeletedColumns; /* the deleted columns */
  double bElement; /* the deleted element from the rhs */
} ForcedRow;

typedef struct  {
  int ChangeType; /* which preprocessing operation? */

/* only one of the following pointers is active within
                              each SingleChange record */
  DuplicateCol 		 *pDuplicateCol;
  DuplicateRow 		 *pDuplicateRow;
  ZeroRow                *pZeroRow;
  ZeroColumn             *pZeroColumn;
  FixedVariable          *pFixedVariable;
  SingletonRow           *pSingletonRow;
  FreeColumnSingleton    *pFreeColumnSingleton;
  ForcedRow              *pForcedRow;
} SingleChange;

typedef struct ChangeStack {
  int Rows; /* rows in the matrix */
  int Columns; /* cols in the matrix */
  double cshift;
  int Size; /* how many SingleChanges can we put into this stack? */
  int Top;  /* how many are in the stack right now? */

  SingleChange **StackOfChanges; /* stack of single-change records */

  int *RowMask;    /* mask vector indicating deleted status of rows.
		If nonzero, indicates the pass on which they were deleted. */
  int *ColumnMask; /* mask vector indicating deleted status of columns */

  int *VarType; /*  Variable Types; may change during preprocessing due to
		    combining of columns, etc */

  int Passes;      /* number of passes */
  int ReducedRows;  /* Rows remaining in the matrix after reduction */
  int ReducedColumns; /* Columns remaining in the matrix after reduction */
  int SizeUnit;    /* the amount of space added to the stack on each increment */
} ChangeStack;

extern ChangeStack *NewRecord();
extern LPtype   *Convert_MPS_LP();
extern solution *MPSsolution();
#endif


text:
GameState::GameState(StateStack& stack, State::Context context)
        : State(stack, context)
        , mWorld(*context.window)
        , mPlayer(*context.player)
{
}

void GameState::draw()
{
    mWorld.draw();
}

bool GameState::update(sf::Time dt)
{
    mWorld.update(dt);
;
    CommandQueue& commands = mWorld.getCommandQueue();
    mPlayer.handleRealtimeInput(commands);

    return true;
}

bool GameState::handleEvent(const sf::Event& event)
{
    // Game input handling
    CommandQueue& commands = mWorld.getCommandQueue();
    mPlayer.handleEvent(event, commands);

    // Escape pressed, trigger the pause screen
    if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape)
        requestStackPush(States::Pause);

    return true;
}


text:
require 'rails_helper'

RSpec.feature MailManager::Mailing do
  before(:each) do
    @design = import_design
    @newsletter = FactoryGirl.create(:newsletter, name: "Bobo newsletter!", design: @design)
    @mailing = FactoryGirl.create(:mailing, subject: "Bobo Mailing", mailable: @newsletter)
  end
  it "shows a newsletter's(mailable's) name on the index" do
    visit "/admin/mail_manager/mailings"
    expect(page.body).to match /Bobo newsletter!/
  end
  it "shows a mailings time format like: Mar 09, 2015 08:51 am" do
    @mailing.update_attribute(:scheduled_at, Time.parse('2015-03-09 08:51 UTC'))
    visit "/admin/mail_manager/mailings"
    expect(page.body).to match /Mar 09, 2015 08:51 am/
  end
end


text:
package mesosphere.marathon
package core.task

import akka.Done
import akka.actor.ActorSystem
import mesosphere.marathon.test.SettableClock
import mesosphere.marathon.core.condition.Condition
import mesosphere.marathon.core.event.MarathonEvent
import mesosphere.marathon.core.instance.update.InstanceChangedEventsGenerator
import mesosphere.marathon.core.instance.Instance
import mesosphere.marathon.core.task.Task.Id
import mesosphere.marathon.core.task.termination.{ KillReason, KillService }
import mesosphere.marathon.test.Mockito

import scala.collection.mutable
import scala.concurrent.Future

/**
  * A Mocked KillService that publishes a TASK_KILLED event for each given task and always works successfully
  */
class KillServiceMock(system: ActorSystem) extends KillService with Mockito {

  var numKilled = 0
  val customStatusUpdates = mutable.Map.empty[Instance.Id, Seq[MarathonEvent]]
  val killed = mutable.Set.empty[Instance.Id]
  val eventsGenerator = InstanceChangedEventsGenerator
  val clock = new SettableClock()

  override def killInstances(instances: Seq[Instance], reason: KillReason): Future[Done] = {
    instances.foreach { instance =>
      killInstance(instance, reason)
    }
    Future.successful(Done)
  }
  override def killInstance(instance: Instance, reason: KillReason): Future[Done] = {
    val id = instance.instanceId
    val updatedInstance = instance.copy(state = instance.state.copy(condition = Condition.Killed))
    val events = customStatusUpdates.getOrElse(id, eventsGenerator.events(updatedInstance, task = None, now = clock.now(), previousCondition = Some(instance.state.condition)))
    events.foreach(system.eventStream.publish)
    numKilled += 1
    killed += id
    Future.successful(Done)
  }

  override def killUnknownTask(taskId: Id, reason: KillReason): Unit = {
    val instance = mock[Instance]
    instance.instanceId returns taskId.instanceId
    killInstance(instance, reason)
  }
}


text: package win_perf_counters


text:
""" support for providing temporary directories to test functions.  """
from __future__ import absolute_import, division, print_function

import re

import pytest
import py
from _pytest.monkeypatch import MonkeyPatch

class TempdirFactory:
    """Factory for temporary directories under the common base temp directory.

    The base directory can be configured using the ``--basetemp`` option.
    """

    def __init__(self, config):
        self.config = config
        self.trace = config.trace.get("tmpdir")

    def ensuretemp(self, string, dir=1):
        """ (deprecated) return temporary directory path with
            the given string as the trailing part.  It is usually
            better to use the 'tmpdir' function argument which
            provides an empty unique-per-test-invocation directory
            and is guaranteed to be empty.
        """
        # py.log._apiwarn(">1.1", "use tmpdir function argument")
        return self.getbasetemp().ensure(string, dir=dir)

    def mktemp(self, basename, numbered=True):
        """Create a subdirectory of the base temporary directory and return it.
        If ``numbered``, ensure the directory is unique by adding a number
        prefix greater than any existing one.
        """
        basetemp = self.getbasetemp()
        if not numbered:
            p = basetemp.mkdir(basename)
        else:
            p = py.path.local.make_numbered_dir(prefix=basename,
                                                keep=0, rootdir=basetemp, lock_timeout=None)
        self.trace("mktemp", p)
        return p

    def getbasetemp(self):
        """ return base temporary directory. """
        try:
            return self._basetemp
        except AttributeError:
            basetemp = self.config.option.basetemp
            if basetemp:
                basetemp = py.path.local(basetemp)
                if basetemp.check():
                    basetemp.remove()
                basetemp.mkdir()
            else:
                temproot = py.path.local.get_temproot()
                user = get_user()
                if user:
                    # use a sub-directory in the temproot to speed-up
                    # make_numbered_dir() call
                    rootdir = temproot.join('pytest-of-%s' % user)
                else:
                    rootdir = temproot
                rootdir.ensure(dir=1)
                basetemp = py.path.local.make_numbered_dir(prefix='pytest-',
                                                           rootdir=rootdir)
            self._basetemp = t = basetemp.realpath()
            self.trace("new basetemp", t)
            return t

    def finish(self):
        self.trace("finish")

def get_user():
    """Return the current user name, or None if getuser() does not work
    in the current environment (see #1010).
    """
    import getpass
    try:
        return getpass.getuser()
    except (ImportError, KeyError):
        return None

# backward compatibility
TempdirHandler = TempdirFactory

def pytest_configure(config):
    """Create a TempdirFactory and attach it to the config object.

    This is to comply with existing plugins which expect the handler to be
    available at pytest_configure time, but ideally should be moved entirely
    to the tmpdir_factory session fixture.
    """
    mp = MonkeyPatch()
    t = TempdirFactory(config)
    config._cleanup.extend([mp.undo, t.finish])
    mp.setattr(config, '_tmpdirhandler', t, raising=False)
    mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)

@pytest.fixture(scope='session')
def tmpdir_factory(request):
    """Return a TempdirFactory instance for the test session.
    """
    return request.config._tmpdirhandler

@pytest.fixture
def tmpdir(request, tmpdir_factory):
    """Return a temporary directory path object
    which is unique to each test function invocation,
    created as a sub directory of the base temporary
    directory.  The returned object is a `py.path.local`_
    path object.
    """
    name = request.node.name
    name = re.sub(r"[\W]", "_", name)
    MAXVAL = 30
    if len(name) > MAXVAL:
        name = name[:MAXVAL]
    x = tmpdir_factory.mktemp(name, numbered=True)
    return x