text:
//TODO: replace all these defines with #pragma once
#ifndef PCAPPP_LIVE_DEVICE
#define PCAPPP_LIVE_DEVICE

#include <PcapDevice.h>
#include <vector>
#include <string.h>
#include "IpAddress.h"
#include <Packet.h>

/// @file

/**
* \namespace pcpp
* \brief The main namespace for the PcapPlusPlus lib
*/
namespace pcpp
{

	class PcapLiveDevice;

	/**
	 * @typedef OnPacketArrivesCallback
	 * A callback that is called when a packet is captured by PcapLiveDevice
	 * @param[in] pPacket A pointer to the raw packet
	 * @param[in] pDevice A pointer to the PcapLiveDevice instance
	 * @param[in] userCookie A pointer to the object put by the user when packet capturing stared
	 */
	typedef void (*OnPacketArrivesCallback)(RawPacket* pPacket, PcapLiveDevice* pDevice, void* userCookie);

	/**
	 * @typedef OnPacketArrivesStopBlocking
	 * A callback that is called when a packet is captured by PcapLiveDevice
	 * @param[in] pPacket A pointer to the raw packet
	 * @param[in] pDevice A pointer to the PcapLiveDevice instance
	 * @param[in] userCookie A pointer to the object put by the user when packet capturing stared
	 * @return True when main thread should stop blocking or false otherwise
	 */
	typedef bool (*OnPacketArrivesStopBlocking)(RawPacket* pPacket, PcapLiveDevice* pDevice, void* userData);

	/**
	 * @typedef OnStatsUpdateCallback
	 * A callback that is called periodically for stats collection if user asked to start packet capturing with periodic stats collection
	 * @param[in] stats A reference to the most updated stats
	 * @param[in] userCookie A pointer to the object put by the user when packet capturing stared
	 */
	typedef void (*OnStatsUpdateCallback)(pcap_stat& stats, void* userCookie);

	// for internal use only
	typedef void* (*ThreadStart)(void*);

	struct PcapThread;

	/**
	 * @class PcapLiveDevice
	 * A class that wraps a network interface (each of the interfaces listed in ifconfig/ipconfig).
	 * This class wraps the libpcap capabilities of capturing packets from the network, filtering packets and sending packets back to the network.
	 * This class is relevant for Linux applications only. On Windows the WinPcapLiveDevice (which inherits this class) is used. Both classes are
	 * almost similar in capabilities, the main difference between them is adapting some capabilities to the specific OS.
	 * This class cannot be instantiated by the user (it has a private constructor), as network interfaces aren't dynamic. Instances of
	 * this class (one instance per network interface) are created by PcapLiveDeviceList singleton on application startup and the user can get
	 * access to them by using PcapLiveDeviceList public methods such as PcapLiveDeviceList#getPcapLiveDeviceByIp()

	 * Main capabilities of this class:
	 * - Get all available information for this network interfaces such as name, IP addresses, MAC address, MTU, etc. This information is taken
	 * from both libpcap and the OS
	 * - Capture packets from the network. Capturing is always conducted on a different thread. PcapPlusPlus creates this
	 * thread when capturing starts and kills it when capturing ends. This prevents the application from being stuck while waiting for packets or
	 * processing them. Currently only one capturing thread is allowed, so when the interface is in capture mode, no further capturing is allowed.
	 * In addition to capturing the user can get stats on packets that were received by the application, dropped by the NIC (due to full
	 * NIC buffers), etc. Stats collection can be initiated by the user by calling getStatistics() or be pushed to the user periodically by
	 * supplying a callback and a timeout to startCapture()
	 * - Send packets back to the network. Sending the packets is done on the caller thread. No additional threads are created for this task
	 */
	class PcapLiveDevice : public IPcapDevice
	{
		friend class PcapLiveDeviceList;
	protected:
		// This is a second descriptor for the same device. It is needed because of a bug
		// that occurs in libpcap on Linux (on Windows using WinPcap it works well):
		// It's impossible to capture packets sent by the same descriptor
		pcap_t* m_PcapSendDescriptor;
		const char* m_Name;
		const char* m_Description;
		bool m_IsLoopback;
		uint16_t m_DeviceMtu;
		std::vector<pcap_addr_t> m_Addresses;
		MacAddress m_MacAddress;
		IPv4Address m_DefaultGateway;
		PcapThread* m_CaptureThread;
		bool m_CaptureThreadStarted;
		PcapThread* m_StatsThread;
		volatile bool m_StatsThreadStarted;
		volatile bool m_StopThread;
		OnPacketArrivesCallback m_cbOnPacketArrives;
		void* m_cbOnPacketArrivesUserCookie;
		OnStatsUpdateCallback m_cbOnStatsUpdate;
		void* m_cbOnStatsUpdateUserCookie;
		OnPacketArrivesStopBlocking m_cbOnPacketArrivesBlockingMode;
		void* m_cbOnPacketArrivesBlockingModeUserCookie;
		int m_IntervalToUpdateStats;
		RawPacketVector* m_CapturedPackets;
		bool m_CaptureCallbackMode;

		// c'tor is not public, there should be only one for every interface (created by PcapLiveDeviceList)
		PcapLiveDevice(pcap_if_t* pInterface, bool calculateMTU, bool calculateMacAddress, bool calculateDefaultGateway);
		// copy c'tor is not public
		PcapLiveDevice( const PcapLiveDevice& other );
		PcapLiveDevice& operator=(const PcapLiveDevice& other);

		void setDeviceMtu();
		void setDeviceMacAddress();
		void setDefaultGateway();
		static void* captureThreadMain(void *ptr);
		static void* statsThreadMain(void *ptr);
		static void onPacketArrives(uint8_t *user, const struct pcap_pkthdr *pkthdr, const uint8_t *packet);
		static void onPacketArrivesNoCallback(uint8_t *user, const struct pcap_pkthdr *pkthdr, const uint8_t *packet);
		static void onPacketArrivesBlockingMode(uint8_t *user, const struct pcap_pkthdr *pkthdr, const uint8_t *packet);
		std::string printThreadId(PcapThread* id);
		virtual ThreadStart getCaptureThreadStart();
	public:
		/**
		 * The type of the live device
		 */
		enum LiveDeviceType {
			/** libPcap live device */
			LibPcapDevice,
			/** WinPcap live device */
			WinPcapDevice,
			/** WinPcap Remote Capture device */
			RemoteDevice
		};

		/**
		 * Device capturing mode
		 */
		enum DeviceMode {
			/** Only packets that their destination is this NIC are captured */
			Normal = 0,
			/** All packets that arrive to the NIC are captured, even packets that their destination isn't this NIC */
			Promiscuous = 1
		};

		/**
		 * A destructor for this class
		 */
		virtual ~PcapLiveDevice();

		/**
		 * @return The type of the device (libPcap, WinPcap or a remote device)
		 */
		virtual LiveDeviceType getDeviceType() { return LibPcapDevice; }

		/**
		 * @return The name of the device (e.g eth0), taken from pcap_if_t->name
		 */
		inline const char* getName() { return m_Name; }

		/**
		 * @return A human-readable description of the device, taken from pcap_if_t->description. May be NULL in some interfaces
		 */
		inline const char* getDesc() { return m_Description; }

		/**
		 * @return True if this interface is a loopback interface, false otherwise
		 */
		inline bool getLoopback() { return m_IsLoopback; }

		/**
		 * @return The device's maximum transmission unit (MTU) in bytes
		 */
		virtual inline uint16_t getMtu() { return m_DeviceMtu; }

		/**
		 * @return A vector containing all addresses defined for this interface, each in pcap_addr_t struct
		 */
		inline std::vector<pcap_addr_t>& getAddresses() { return m_Addresses; }

		/**
		 * @return The MAC address for this interface
		 */
		virtual inline MacAddress getMacAddress() { return m_MacAddress; }

		/**
		 * @return The IPv4 address for this interface. If multiple IPv4 addresses are defined for this interface, the first will be picked.
		 * If no IPv4 addresses are defined, a zeroed IPv4 address (IPv4Address#Zero) will be returned
		 */
		IPv4Address getIPv4Address();

		/**
		 * @return The default gateway defined for this interface. If no default gateway is defined, if it's not IPv4 or if couldn't extract
		 * default gateway IPv4Address#Zero will be returned. If multiple gateways were defined the first one will be returned
		 */
		IPv4Address getDefaultGateway();

		/**
		 * @return A list of all DNS servers defined for this machine. If this list is empty it means no DNS servers were defined or they
		 * couldn't be extracted from some reason. This list is created in PcapLiveDeviceList class and can be also retrieved from there.
		 * This method exists for convenience - so it'll be possible to get this list from PcapLiveDevice as well
		 */
		std::vector<IPv4Address>& getDnsServers();

		/**
		 * Start capturing packets on this network interface (device). Each time a packet is captured the onPacketArrives callback is called.
		 * The capture is done on a new thread created by this method, meaning all callback calls are done in a thread other than the
		 * caller thread. Capture process will stop and this capture thread will be terminated when calling stopCapture(). This method must be
		 * called after the device is opened (i.e the open() method was called), otherwise an error will be returned.
		 * @param[in] onPacketArrives A callback that is called each time a packet is captured
		 * @param[in] onPacketArrivesUserCookie A pointer to a user provided object. This object will be transferred to the onPacketArrives callback
		 * each time it is called. This cookie is very useful for transferring objects that give context to the capture callback, for example:
		 * objects that counts packets, manages flow state or manages the application state according to the packet that was captured
		 * @return True if capture started successfully, false if (relevant log error is printed in any case):
		 * - Capture is already running
		 * - Device is not opened
		 * - Capture thread could not be created
		 */
		virtual bool startCapture(OnPacketArrivesCallback onPacketArrives, void* onPacketArrivesUserCookie);

		/**
		 * Start capturing packets on this network interface (device) with periodic stats collection. Each time a packet is captured the onPacketArrives
		 * callback is called. In addition, each intervalInSecondsToUpdateStats seconds stats are collected from the device and the onStatsUpdate
		 * callback is called. Both the capture and periodic stats collection are done on new threads created by this method, each on a different thread,
		 * meaning all callback calls are done in threads other than the caller thread. Capture process and stats collection will stop and threads will be
		 * terminated when calling stopCapture(). This method must be called after the device is opened (i.e the open() method was called), otherwise an
		 * error will be returned.
		 * @param[in] onPacketArrives A callback that is called each time a packet is captured
		 * @param[in] onPacketArrivesUserCookie A pointer to a user provided object. This object will be transferred to the onPacketArrives callback
		 * each time it is called. This cookie is very useful for transferring objects that give context to the capture callback, for example:
		 * objects that counts packets, manages flow state or manages the application state according to the packet that was captured
		 * @param[in] intervalInSecondsToUpdateStats The interval in seconds to activate periodic stats collection
		 * @param[in] onStatsUpdate A callback that will be called each time intervalInSecondsToUpdateStats expires and stats are collected. This
		 * callback will contain the collected stats
		 * @param[in] onStatsUpdateUserCookie A pointer to a user provided object. This object will be transferred to the onStatsUpdate callback
		 * each time it is called
		 * @return True if capture started successfully, false if (relevant log error is printed in any case):
		 * - Capture is already running
		 * - Device is not opened
		 * - Capture thread could not be created
		 * - Stats collection thread could not be created
		 */
		virtual bool startCapture(OnPacketArrivesCallback onPacketArrives, void* onPacketArrivesUserCookie, int intervalInSecondsToUpdateStats, OnStatsUpdateCallback onStatsUpdate, void* onStatsUpdateUserCookie);

		/**
		 * Start capturing packets on this network interface (device) with periodic stats collection only. This means that packets arriving to the
		 * network interface aren't delivered to the user but only counted. Each intervalInSecondsToUpdateStats seconds stats are collected from the
		 * device and the onStatsUpdate callback is called with the updated counters. The periodic stats collection is done on a new thread created
		 * by this method, meaning all callback calls are done in threads other than the caller thread. Stats collection will stop and threads will
		 * be terminated when calling stopCapture(). This method must be called after the device is opened (i.e the open() method was called),
		 * otherwise an error will be returned.
		 * @param[in] intervalInSecondsToUpdateStats The interval in seconds to activate periodic stats collection
		 * @param[in] onStatsUpdate A callback that will be called each time intervalInSecondsToUpdateStats expires and stats are collected. This
		 * callback will contain the collected stats
		 * @param[in] onStatsUpdateUserCookie A pointer to a user provided object. This object will be transferred to the onStatsUpdate callback
		 * each time it is called
		 * @return True if capture started successfully, false if (relevant log error is printed in any case):
		 * - Capture is already running
		 * - Device is not opened
		 * - Stats collection thread could not be created
		 */
		virtual bool startCapture(int intervalInSecondsToUpdateStats, OnStatsUpdateCallback onStatsUpdate, void* onStatsUpdateUserCookie);

		/**
		 * Start capturing packets on this network interface (device). All captured packets are added to capturedPacketsVector, so at the end of
		 * the capture (when calling stopCapture()) this vector contains pointers to all captured packets in the form of RawPacket. The capture
		 * is done on a new thread created by this method, meaning capturedPacketsVector is updated from another thread other than the caller
		 * thread (so user should avoid changing or iterating this vector while capture is on). Capture process will stop and this capture thread
		 * will be terminated when calling stopCapture(). This method must be called after the device is opened (i.e the open() method was called),
		 * otherwise an error will be returned.
		 * @param[in] capturedPacketsVector A reference to a RawPacketVector, meaning a vector of pointer to RawPacket objects
		 * @return True if capture started successfully, false if (relevant log error is printed in any case):
		 * - Capture is already running
		 * - Device is not opened
		 * - Capture thread could not be created
		 */
		virtual bool startCapture(RawPacketVector& capturedPacketsVector);

		/**
		 * Start capturing packets on this network interface (device) in blocking mode, meaning this method blocks and won't return until
		 * the user frees the blocking (via onPacketArrives callback) or until a user defined timeout expires.
		 * Whenever a packets is captured the onPacketArrives callback is called and lets the user handle the packet. In each callback call
		 * the user should return true if he wants to release the block or false if it wants it to keep blocking. Regardless of this callback
		 * a timeout is defined when start capturing. When this timeout expires the method will return.

		 * Please notice that stopCapture() isn't needed here because when the method returns (after timeout or per user decision) capturing
		 * on the device is stopped
		 * @param[in] onPacketArrives A callback given by the user for handling incoming packets. After handling each packet the user needs to
		 * return a boolean value. True value indicates stop capturing and stop blocking and false value indicates continue capturing and blocking
		 * @param[in] userCookie A pointer to a user provided object. This object will be transferred to the onPacketArrives callback
		 * each time it is called. This cookie is very useful for transferring objects that give context to the capture callback, for example:
		 * objects that counts packets, manages flow state or manages the application state according to the packet that was captured
		 * @param[in] timeout A timeout in seconds for the blocking to stop even if the user didn't return "true" in the onPacketArrives callback
		 * If this timeout is set to 0 or less the timeout will be ignored, meaning the method will keep blocking until the user frees it via
		 * the onPacketArrives callback
		 * @return -1 if timeout expired, 1 if blocking was stopped via onPacketArrives callback or 0 if an error occurred (such as device
		 * not open etc.). When returning 0 an appropriate error message is printed to log
		 */
		virtual int startCaptureBlockingMode(OnPacketArrivesStopBlocking onPacketArrives, void* userCookie, int timeout);

		/**
		 * Stop a currently running packet capture. This method terminates gracefully both packet capture thread and periodic stats collection
		 * thread (both if exist)
		 */
		void stopCapture();

		/**
		 * Send a RawPacket to the network
		 * @param[in] rawPacket A reference to the raw packet to send. This method treats the raw packet as read-only, it doesn't change anything
		 * in it
		 * @return True if packet was sent successfully. False will be returned in the following cases (relevant log error is printed in any case):
		 * - Device is not opened
		 * - Packet length is 0
		 * - Packet length is larger than device MTU
		 * - Packet could not be sent due to some error in libpcap/WinPcap
		 */
		bool sendPacket(RawPacket const& rawPacket);

		/**
		 * Send a buffer containing packet raw data (including all layers) to the network
		 * @param[in] packetData The buffer containing the packet raw data
		 * @param[in] packetDataLength The length of the buffer
		 * @return True if packet was sent successfully. False will be returned in the following cases (relevant log error is printed in any case):
		 * - Device is not opened
		 * - Packet length is 0
		 * - Packet length is larger than device MTU
		 * - Packet could not be sent due to some error in libpcap/WinPcap
		 */
		bool sendPacket(const uint8_t* packetData, int packetDataLength);

		/**
		 * Send a parsed Packet to the network
		 * @param[in] packet A pointer to the packet to send. This method treats the packet as read-only, it doesn't change anything in it
		 * @return True if packet was sent successfully. False will be returned in the following cases (relevant log error is printed in any case):
		 * - Device is not opened
		 * - Packet length is 0
		 * - Packet length is larger than device MTU
		 * - Packet could not be sent due to some error in libpcap/WinPcap
		 */
		bool sendPacket(Packet* packet);

		/**
		 * Send an array of RawPacket objects to the network
		 * @param[in] rawPacketsArr The array of RawPacket objects to send. This method treats all packets as read-only, it doesn't change anything
		 * in them
		 * @param[in] arrLength The length of the array
		 * @return The number of packets sent successfully. Sending a packet can fail if:
		 * - Device is not opened. In this case no packets will be sent, return value will be 0
		 * - Packet length is 0
		 * - Packet length is larger than device MTU
		 * - Packet could not be sent due to some error in libpcap/WinPcap
		 */
		virtual int sendPackets(RawPacket* rawPacketsArr, int arrLength);

		/**
		 * Send an array of pointers to Packet objects to the network
		 * @param[in] packetsArr The array of pointers to Packet objects to send. This method treats all packets as read-only, it doesn't change
		 * anything in them
		 * @param[in] arrLength The length of the array
		 * @return The number of packets sent successfully. Sending a packet can fail if:
		 * - Device is not opened. In this case no packets will be sent, return value will be 0
		 * - Packet length is 0
		 * - Packet length is larger than device MTU
		 * - Packet could not be sent due to some error in libpcap/WinPcap
		 */
		virtual int sendPackets(Packet** packetsArr, int arrLength);

		/**
		 * Send a vector of pointers to RawPacket objects to the network
		 * @param[in] rawPackets The array of pointers to RawPacket objects to send. This method treats all packets as read-only, it doesn't change
		 * anything in them
		 * @return The number of packets sent successfully. Sending a packet can fail if:
		 * - Device is not opened. In this case no packets will be sent, return value will be 0
		 * - Packet length is 0
		 * - Packet length is larger than device MTU
		 * - Packet could not be sent due to some error in libpcap/WinPcap
		 */
		virtual int sendPackets(const RawPacketVector& rawPackets);

		//override methods

		/**
		 * Open the device using libpcap pcap_open_live. Opening the device only makes the device ready for use, it doesn't start packet capturing.
		 * For packet capturing the user should call startCapture(). This implies that calling this method is a must before calling startCapture()
		 * (otherwise startCapture() will fail with a "device not open" error). The device is opened in promiscuous mode
		 * @return True if the device was opened successfully, false otherwise. When opening the device fails an error will be printed to log
		 * as well
		 */
		bool open();

		void close();

		virtual void getStatistics(pcap_stat& stats);

		/**
		 * Same as open(), but enables to open the device in normal or promiscuous mode
		 * @param[in] mode Normal or promiscuous mode
		 * @return Same as open()
		 */
		bool open(DeviceMode mode);
	protected:
		pcap_t* doOpen(DeviceMode mode);
	};

} // namespace pcpp

#endif


text:
var hyperspace = require('hyperspace');
var fs = require('fs');
var html = fs.readFileSync(__dirname + '/cat.html', 'utf8');

module.exports = function () {
    return hyperspace(html, { key: 'data-key' }, function (row) {
        return {
            '.name': row.value.name,
            '.lives': row.value.lives
        };
    });
};

redpajama_set_name: RedPajamaGithub


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

import javax.jms.JMSContext;

import org.apache.activemq.artemis.api.core.QueueConfiguration;
import org.apache.activemq.artemis.api.core.RoutingType;
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.DivertConfiguration;
import org.apache.activemq.artemis.core.server.ActiveMQServer;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.core.settings.impl.AddressSettings;
import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.tests.util.RandomUtil;
import org.apache.activemq.artemis.tests.util.Wait;
import org.apache.activemq.artemis.utils.CompositeAddress;
import org.junit.Before;
import org.junit.Test;

public class AutoCreateDeadLetterResourcesTest extends ActiveMQTestBase {
   public final SimpleString addressA = new SimpleString("addressA");
   public final SimpleString queueA = new SimpleString("queueA");
   public final SimpleString dla = new SimpleString("myDLA");

   private ActiveMQServer server;

   @Override
   @Before
   public void setUp() throws Exception {
      super.setUp();
      server = createServer(false);

      // set common address settings needed for all tests; make sure to use getMatch instead of addMatch in invidual tests or these will be overwritten
      server.getAddressSettingsRepository().addMatch("#", new AddressSettings().setAutoCreateDeadLetterResources(true).setDeadLetterAddress(dla).setMaxDeliveryAttempts(1));

      server.start();
   }

   @Test
   public void testAutoCreationOfDeadLetterResources() throws Exception {
      int before = server.getActiveMQServerControl().getQueueNames().length;
      triggerDlaDelivery();
      assertNotNull(server.getAddressInfo(dla));
      assertNotNull(server.locateQueue(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.concat(addressA).concat(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX)));
      assertEquals(2, server.getActiveMQServerControl().getQueueNames().length - before);
   }

   @Test
   public void testAutoCreationOfDeadLetterResourcesWithNullDLA() throws Exception {
      testAutoCreationOfDeadLetterResourcesWithNoDLA(null);
   }

   @Test
   public void testAutoCreationOfDeadLetterResourcesWithEmptyDLA() throws Exception {
      testAutoCreationOfDeadLetterResourcesWithNoDLA(SimpleString.toSimpleString(""));
   }

   private void testAutoCreationOfDeadLetterResourcesWithNoDLA(SimpleString dla) throws Exception {
      server.getAddressSettingsRepository().getMatch("#").setDeadLetterAddress(dla);
      int before = server.getActiveMQServerControl().getQueueNames().length;
      triggerDlaDelivery();
      if (dla != null) {
         assertNull(server.getAddressInfo(dla));
      }
      assertNull(server.locateQueue(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.concat(addressA).concat(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX)));
      assertEquals(1, server.getActiveMQServerControl().getQueueNames().length - before);
   }

   @Test
   public void testAutoCreateDeadLetterQueuePrefix() throws Exception {
      SimpleString prefix = RandomUtil.randomSimpleString();
      server.getAddressSettingsRepository().getMatch("#").setDeadLetterQueuePrefix(prefix);
      triggerDlaDelivery();
      assertNotNull(server.locateQueue(prefix.concat(addressA).concat(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX)));
   }

   @Test
   public void testAutoCreateDeadLetterQueueSuffix() throws Exception {
      SimpleString suffix = RandomUtil.randomSimpleString();
      server.getAddressSettingsRepository().getMatch("#").setDeadLetterQueueSuffix(suffix);
      triggerDlaDelivery();
      assertNotNull(server.locateQueue(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.concat(addressA).concat(suffix)));
   }

   @Test
   public void testAutoCreateDeadLetterQueuePrefixAndSuffix() throws Exception {
      SimpleString prefix = RandomUtil.randomSimpleString();
      SimpleString suffix = RandomUtil.randomSimpleString();
      server.getAddressSettingsRepository().getMatch("#").setDeadLetterQueuePrefix(prefix).setDeadLetterQueueSuffix(suffix);
      triggerDlaDelivery();
      assertNotNull(server.locateQueue(prefix.concat(addressA).concat(suffix)));
   }

   @Test
   public void testAutoCreatedDeadLetterFilterAnycast() throws Exception {
      testAutoCreatedDeadLetterFilter(RoutingType.ANYCAST);
   }

   @Test
   public void testAutoCreatedDeadLetterFilterMulticast() throws Exception {
      testAutoCreatedDeadLetterFilter(RoutingType.MULTICAST);
   }

   private void testAutoCreatedDeadLetterFilter(RoutingType routingType) throws Exception {
      final int ITERATIONS = 100;
      final int MESSAGE_COUNT = 10;

      for (int i = 0; i < ITERATIONS; i++) {
         SimpleString address = RandomUtil.randomSimpleString();
         SimpleString queue = RandomUtil.randomSimpleString();
         server.createQueue(new QueueConfiguration(queue).setAddress(address).setRoutingType(routingType));
         ServerLocator locator = createInVMNonHALocator();
         ClientSessionFactory cf = createSessionFactory(locator);
         ClientSession s = addClientSession(cf.createSession(true, false));
         ClientProducer p = s.createProducer(address);
         for (int j = 0; j < MESSAGE_COUNT; j++) {
            p.send(s.createMessage(true).setRoutingType(routingType));
         }
         p.close();
         ClientConsumer consumer = s.createConsumer(queue);
         s.start();
         for (int j = 0; j < MESSAGE_COUNT; j++) {
            ClientMessage message = consumer.receive();
            assertNotNull(message);
            message.acknowledge();
         }
         s.rollback();
         Queue dlq = server.locateQueue(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.concat(address).concat(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX));
         assertNotNull(dlq);
         Wait.assertEquals(MESSAGE_COUNT, dlq::getMessageCount);
      }

      assertEquals(ITERATIONS, server.getPostOffice().getBindingsForAddress(dla).getBindings().size());
   }

   @Test
   public void testAutoDeletionAndRecreationOfDeadLetterResources() throws Exception {
      SimpleString dlqName = AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.concat(addressA).concat(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX);

      triggerDlaDelivery();

      // consume the message from the DLQ so it will be auto-deleted
      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sessionFactory = createSessionFactory(locator);
      ClientSession session = addClientSession(sessionFactory.createSession(true, true));
      ClientConsumer consumer = session.createConsumer(dlqName);
      session.start();
      ClientMessage message = consumer.receive();
      assertNotNull(message);
      message.acknowledge();
      consumer.close();
      session.close();
      sessionFactory.close();
      locator.close();

      Wait.assertTrue(() -> server.locateQueue(dlqName) == null, 2000, 100);

      server.destroyQueue(queueA);

      triggerDlaDelivery();
      assertNotNull(server.getAddressInfo(dla));
      assertNotNull(server.locateQueue(dlqName));
   }

   @Test
   public void testWithJMSFQQN() throws Exception {
      SimpleString dlqName = AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.concat(addressA).concat(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX);
      String fqqn = CompositeAddress.toFullyQualified(dla, dlqName).toString();

      triggerDlaDelivery();

      JMSContext context = new ActiveMQConnectionFactory("vm://0").createContext();
      context.start();
      assertNotNull(context.createConsumer(context.createQueue(fqqn)).receive(2000));
   }

   @Test
   public void testDivertedMessage() throws Exception {
      SimpleString dlqName = AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.concat(addressA).concat(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX);
      String divertAddress = "divertAddress";

      server.deployDivert(new DivertConfiguration().setName("testDivert").setAddress(divertAddress).setForwardingAddress(addressA.toString()));

      server.createQueue(new QueueConfiguration(queueA).setAddress(addressA).setRoutingType(RoutingType.ANYCAST));

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sessionFactory = createSessionFactory(locator);
      ClientSession session = addClientSession(sessionFactory.createSession(true, true));
      ClientProducer producer = addClientProducer(session.createProducer(divertAddress));
      producer.send(session.createMessage(true));
      producer.close();

      Wait.assertEquals(1L, () -> server.locateQueue(queueA).getMessageCount(), 2000, 100);

      triggerDlaDelivery();

      Wait.assertTrue(() -> server.locateQueue(dlqName).getMessageCount() == 1, 2000, 100);

      ClientConsumer consumer = session.createConsumer(dlqName);
      session.start();
      ClientMessage message = consumer.receive(1000);
      assertNotNull(message);
      message.acknowledge();
   }

   @Test
   public void testMovedMessage() throws Exception {
      SimpleString dlqName = AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_PREFIX.concat(addressA).concat(AddressSettings.DEFAULT_DEAD_LETTER_QUEUE_SUFFIX);
      final SimpleString moveFromAddress = new SimpleString("moveFromAddress");
      final SimpleString moveFromQueue = new SimpleString("moveFromQueue");
      server.createQueue(new QueueConfiguration(moveFromQueue).setAddress(moveFromAddress).setRoutingType(RoutingType.ANYCAST));
      server.createQueue(new QueueConfiguration(queueA).setAddress(addressA).setRoutingType(RoutingType.ANYCAST));

      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sessionFactory = createSessionFactory(locator);
      ClientSession session = addClientSession(sessionFactory.createSession(true, true));
      ClientProducer producer = addClientProducer(session.createProducer(moveFromAddress));
      producer.send(session.createMessage(true));
      producer.close();
      Wait.assertEquals(1L, server.locateQueue(moveFromQueue)::getMessageCount, 2000, 100);
      server.locateQueue(moveFromQueue).moveReferences(null, addressA, null);

      Wait.assertEquals(1L, server.locateQueue(queueA)::getMessageCount, 2000, 100);

      triggerDlaDelivery();

      Wait.assertEquals(1L, server.locateQueue(dlqName)::getMessageCount, 2000, 100);

      ClientConsumer consumer = session.createConsumer(dlqName);
      session.start();
      ClientMessage message = consumer.receive(1000);
      assertNotNull(message);
      message.acknowledge();
   }

   private void triggerDlaDelivery() throws Exception {
      try {
         server.createQueue(new QueueConfiguration(queueA).setAddress(addressA).setRoutingType(RoutingType.ANYCAST));
      } catch (Exception e) {
         // ignore
      }
      ServerLocator locator = createInVMNonHALocator();
      ClientSessionFactory sessionFactory = createSessionFactory(locator);
      ClientSession session = addClientSession(sessionFactory.createSession(true, false));
      ClientProducer producer = addClientProducer(session.createProducer(addressA));
      producer.send(session.createMessage(true));
      producer.close();
      ClientConsumer consumer = addClientConsumer(session.createConsumer(queueA));
      session.start();
      ClientMessage message = consumer.receive();
      assertNotNull(message);
      message.acknowledge();
      session.rollback();
      session.close();
      sessionFactory.close();
      locator.close();
   }
}


text:
package mock.controllers.shared;

import io.vertx.core.shareddata.LocalMap;
import io.vertx.ext.web.RoutingContext;

import com.github.aesteve.vertx.nubes.annotations.Controller;
import com.github.aesteve.vertx.nubes.annotations.params.LocalMapValue;
import com.github.aesteve.vertx.nubes.annotations.params.Param;
import com.github.aesteve.vertx.nubes.annotations.params.VertxLocalMap;
import com.github.aesteve.vertx.nubes.annotations.routing.http.GET;

@Controller("/shared/local")
public class TestLocalMap {

	@GET("/staticValue")
	public void getLocalValue(RoutingContext context, @LocalMapValue(mapName = "test-map", key = "key") String value) {
		context.response().putHeader("X-Map-Value", value);
		context.response().end();
	}

	@GET("/dynamicValue")
	public void getDynamicValue(RoutingContext context, @VertxLocalMap("test-map") LocalMap<String, String> map, @Param("key") String key) {
		context.response().putHeader("X-Map-Value", map.get(key));
		context.response().end();
	}
}


text:
#include "src/core/iomgr/fd_posix.h"

#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/time.h>
#include "test/core/util/test_config.h"

static grpc_pollset g_pollset;

/* buffer size used to send and receive data.
   1024 is the minimal value to set TCP send and receive buffer. */
#define BUF_SIZE 1024

/* Create a test socket with the right properties for testing.
   port is the TCP port to listen or connect to.
   Return a socket FD and sockaddr_in. */
static void create_test_socket(int port, int *socket_fd,
                               struct sockaddr_in *sin) {
  int fd;
  int one = 1;
  int buf_size = BUF_SIZE;
  int flags;

  fd = socket(AF_INET, SOCK_STREAM, 0);
  setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
  /* Reset the size of socket send buffer to the minimal value to facilitate
     buffer filling up and triggering notify_on_write  */
  GPR_ASSERT(
      setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &buf_size, sizeof(buf_size)) != -1);
  GPR_ASSERT(
      setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &buf_size, sizeof(buf_size)) != -1);
  /* Make fd non-blocking */
  flags = fcntl(fd, F_GETFL, 0);
  GPR_ASSERT(fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0);
  *socket_fd = fd;

  /* Use local address for test */
  sin->sin_family = AF_INET;
  sin->sin_addr.s_addr = htonl(0x7f000001);
  GPR_ASSERT(port >= 0 && port < 65536);
  sin->sin_port = htons((gpr_uint16)port);
}

/* Dummy gRPC callback */
void no_op_cb(void *arg, int success) {}

/* =======An upload server to test notify_on_read===========
   The server simply reads and counts a stream of bytes. */

/* An upload server. */
typedef struct {
  grpc_fd *em_fd;           /* listening fd */
  ssize_t read_bytes_total; /* total number of received bytes */
  int done;                 /* set to 1 when a server finishes serving */
  grpc_closure listen_closure;
} server;

static void server_init(server *sv) {
  sv->read_bytes_total = 0;
  sv->done = 0;
}

/* An upload session.
   Created when a new upload request arrives in the server. */
typedef struct {
  server *sv;              /* not owned by a single session */
  grpc_fd *em_fd;          /* fd to read upload bytes */
  char read_buf[BUF_SIZE]; /* buffer to store upload bytes */
  grpc_closure session_read_closure;
} session;

/* Called when an upload session can be safely shutdown.
   Close session FD and start to shutdown listen FD. */
static void session_shutdown_cb(grpc_exec_ctx *exec_ctx, void *arg, /*session */
                                int success) {
  session *se = arg;
  server *sv = se->sv;
  grpc_fd_orphan(exec_ctx, se->em_fd, NULL, "a");
  gpr_free(se);
  /* Start to shutdown listen fd. */
  grpc_fd_shutdown(exec_ctx, sv->em_fd);
}

/* Called when data become readable in a session. */
static void session_read_cb(grpc_exec_ctx *exec_ctx, void *arg, /*session */
                            int success) {
  session *se = arg;
  int fd = se->em_fd->fd;

  ssize_t read_once = 0;
  ssize_t read_total = 0;

  if (!success) {
    session_shutdown_cb(exec_ctx, arg, 1);
    return;
  }

  do {
    read_once = read(fd, se->read_buf, BUF_SIZE);
    if (read_once > 0) read_total += read_once;
  } while (read_once > 0);
  se->sv->read_bytes_total += read_total;

  /* read() returns 0 to indicate the TCP connection was closed by the client.
     read(fd, read_buf, 0) also returns 0 which should never be called as such.
     It is possible to read nothing due to spurious edge event or data has
     been drained, In such a case, read() returns -1 and set errno to EAGAIN. */
  if (read_once == 0) {
    session_shutdown_cb(exec_ctx, arg, 1);
  } else if (read_once == -1) {
    if (errno == EAGAIN) {
      /* An edge triggered event is cached in the kernel until next poll.
         In the current single thread implementation, session_read_cb is called
         in the polling thread, such that polling only happens after this
         callback, and will catch read edge event if data is available again
         before notify_on_read.
         TODO(chenw): in multi-threaded version, callback and polling can be
         run in different threads. polling may catch a persist read edge event
         before notify_on_read is called.  */
      grpc_fd_notify_on_read(exec_ctx, se->em_fd, &se->session_read_closure);
    } else {
      gpr_log(GPR_ERROR, "Unhandled read error %s", strerror(errno));
      abort();
    }
  }
}

/* Called when the listen FD can be safely shutdown.
   Close listen FD and signal that server can be shutdown. */
static void listen_shutdown_cb(grpc_exec_ctx *exec_ctx, void *arg /*server */,
                               int success) {
  server *sv = arg;

  grpc_fd_orphan(exec_ctx, sv->em_fd, NULL, "b");

  gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  sv->done = 1;
  grpc_pollset_kick(&g_pollset, NULL);
  gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
}

/* Called when a new TCP connection request arrives in the listening port. */
static void listen_cb(grpc_exec_ctx *exec_ctx, void *arg, /*=sv_arg*/
                      int success) {
  server *sv = arg;
  int fd;
  int flags;
  session *se;
  struct sockaddr_storage ss;
  socklen_t slen = sizeof(ss);
  grpc_fd *listen_em_fd = sv->em_fd;

  if (!success) {
    listen_shutdown_cb(exec_ctx, arg, 1);
    return;
  }

  fd = accept(listen_em_fd->fd, (struct sockaddr *)&ss, &slen);
  GPR_ASSERT(fd >= 0);
  GPR_ASSERT(fd < FD_SETSIZE);
  flags = fcntl(fd, F_GETFL, 0);
  fcntl(fd, F_SETFL, flags | O_NONBLOCK);
  se = gpr_malloc(sizeof(*se));
  se->sv = sv;
  se->em_fd = grpc_fd_create(fd, "listener");
  grpc_pollset_add_fd(exec_ctx, &g_pollset, se->em_fd);
  se->session_read_closure.cb = session_read_cb;
  se->session_read_closure.cb_arg = se;
  grpc_fd_notify_on_read(exec_ctx, se->em_fd, &se->session_read_closure);

  grpc_fd_notify_on_read(exec_ctx, listen_em_fd, &sv->listen_closure);
}

/* Max number of connections pending to be accepted by listen(). */
#define MAX_NUM_FD 1024

/* Start a test server, return the TCP listening port bound to listen_fd.
   listen_cb() is registered to be interested in reading from listen_fd.
   When connection request arrives, listen_cb() is called to accept the
   connection request. */
static int server_start(grpc_exec_ctx *exec_ctx, server *sv) {
  int port = 0;
  int fd;
  struct sockaddr_in sin;
  socklen_t addr_len;

  create_test_socket(port, &fd, &sin);
  addr_len = sizeof(sin);
  GPR_ASSERT(bind(fd, (struct sockaddr *)&sin, addr_len) == 0);
  GPR_ASSERT(getsockname(fd, (struct sockaddr *)&sin, &addr_len) == 0);
  port = ntohs(sin.sin_port);
  GPR_ASSERT(listen(fd, MAX_NUM_FD) == 0);

  sv->em_fd = grpc_fd_create(fd, "server");
  grpc_pollset_add_fd(exec_ctx, &g_pollset, sv->em_fd);
  /* Register to be interested in reading from listen_fd. */
  sv->listen_closure.cb = listen_cb;
  sv->listen_closure.cb_arg = sv;
  grpc_fd_notify_on_read(exec_ctx, sv->em_fd, &sv->listen_closure);

  return port;
}

/* Wait and shutdown a sever. */
static void server_wait_and_shutdown(server *sv) {
  gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  while (!sv->done) {
    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
    grpc_pollset_worker worker;
    grpc_pollset_work(&exec_ctx, &g_pollset, &worker,
                      gpr_now(GPR_CLOCK_MONOTONIC),
                      gpr_inf_future(GPR_CLOCK_MONOTONIC));
    gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
    grpc_exec_ctx_finish(&exec_ctx);
    gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  }
  gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
}

/* ===An upload client to test notify_on_write=== */

/* Client write buffer size */
#define CLIENT_WRITE_BUF_SIZE 10
/* Total number of times that the client fills up the write buffer */
#define CLIENT_TOTAL_WRITE_CNT 3

/* An upload client. */
typedef struct {
  grpc_fd *em_fd;
  char write_buf[CLIENT_WRITE_BUF_SIZE];
  ssize_t write_bytes_total;
  /* Number of times that the client fills up the write buffer and calls
     notify_on_write to schedule another write. */
  int client_write_cnt;

  int done; /* set to 1 when a client finishes sending */
  grpc_closure write_closure;
} client;

static void client_init(client *cl) {
  memset(cl->write_buf, 0, sizeof(cl->write_buf));
  cl->write_bytes_total = 0;
  cl->client_write_cnt = 0;
  cl->done = 0;
}

/* Called when a client upload session is ready to shutdown. */
static void client_session_shutdown_cb(grpc_exec_ctx *exec_ctx,
                                       void *arg /*client */, int success) {
  client *cl = arg;
  grpc_fd_orphan(exec_ctx, cl->em_fd, NULL, "c");
  cl->done = 1;
  grpc_pollset_kick(&g_pollset, NULL);
}

/* Write as much as possible, then register notify_on_write. */
static void client_session_write(grpc_exec_ctx *exec_ctx, void *arg, /*client */
                                 int success) {
  client *cl = arg;
  int fd = cl->em_fd->fd;
  ssize_t write_once = 0;

  if (!success) {
    gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
    client_session_shutdown_cb(exec_ctx, arg, 1);
    gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
    return;
  }

  do {
    write_once = write(fd, cl->write_buf, CLIENT_WRITE_BUF_SIZE);
    if (write_once > 0) cl->write_bytes_total += write_once;
  } while (write_once > 0);

  if (errno == EAGAIN) {
    gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
    if (cl->client_write_cnt < CLIENT_TOTAL_WRITE_CNT) {
      cl->write_closure.cb = client_session_write;
      cl->write_closure.cb_arg = cl;
      grpc_fd_notify_on_write(exec_ctx, cl->em_fd, &cl->write_closure);
      cl->client_write_cnt++;
    } else {
      client_session_shutdown_cb(exec_ctx, arg, 1);
    }
    gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
  } else {
    gpr_log(GPR_ERROR, "unknown errno %s", strerror(errno));
    abort();
  }
}

/* Start a client to send a stream of bytes. */
static void client_start(grpc_exec_ctx *exec_ctx, client *cl, int port) {
  int fd;
  struct sockaddr_in sin;
  create_test_socket(port, &fd, &sin);
  if (connect(fd, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
    if (errno == EINPROGRESS) {
      struct pollfd pfd;
      pfd.fd = fd;
      pfd.events = POLLOUT;
      pfd.revents = 0;
      if (poll(&pfd, 1, -1) == -1) {
        gpr_log(GPR_ERROR, "poll() failed during connect; errno=%d", errno);
        abort();
      }
    } else {
      gpr_log(GPR_ERROR, "Failed to connect to the server (errno=%d)", errno);
      abort();
    }
  }

  cl->em_fd = grpc_fd_create(fd, "client");
  grpc_pollset_add_fd(exec_ctx, &g_pollset, cl->em_fd);

  client_session_write(exec_ctx, cl, 1);
}

/* Wait for the signal to shutdown a client. */
static void client_wait_and_shutdown(client *cl) {
  gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  while (!cl->done) {
    grpc_pollset_worker worker;
    grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
    grpc_pollset_work(&exec_ctx, &g_pollset, &worker,
                      gpr_now(GPR_CLOCK_MONOTONIC),
                      gpr_inf_future(GPR_CLOCK_MONOTONIC));
    gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
    grpc_exec_ctx_finish(&exec_ctx);
    gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  }
  gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
}

/* Test grpc_fd. Start an upload server and client, upload a stream of
   bytes from the client to the server, and verify that the total number of
   sent bytes is equal to the total number of received bytes. */
static void test_grpc_fd(void) {
  server sv;
  client cl;
  int port;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;

  server_init(&sv);
  port = server_start(&exec_ctx, &sv);
  client_init(&cl);
  client_start(&exec_ctx, &cl, port);
  grpc_exec_ctx_finish(&exec_ctx);
  client_wait_and_shutdown(&cl);
  server_wait_and_shutdown(&sv);
  GPR_ASSERT(sv.read_bytes_total == cl.write_bytes_total);
  gpr_log(GPR_INFO, "Total read bytes %d", sv.read_bytes_total);
}

typedef struct fd_change_data {
  void (*cb_that_ran)(grpc_exec_ctx *exec_ctx, void *, int success);
} fd_change_data;

void init_change_data(fd_change_data *fdc) { fdc->cb_that_ran = NULL; }

void destroy_change_data(fd_change_data *fdc) {}

static void first_read_callback(grpc_exec_ctx *exec_ctx,
                                void *arg /* fd_change_data */, int success) {
  fd_change_data *fdc = arg;

  gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  fdc->cb_that_ran = first_read_callback;
  grpc_pollset_kick(&g_pollset, NULL);
  gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
}

static void second_read_callback(grpc_exec_ctx *exec_ctx,
                                 void *arg /* fd_change_data */, int success) {
  fd_change_data *fdc = arg;

  gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  fdc->cb_that_ran = second_read_callback;
  grpc_pollset_kick(&g_pollset, NULL);
  gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
}

/* Test that changing the callback we use for notify_on_read actually works.
   Note that we have two different but almost identical callbacks above -- the
   point is to have two different function pointers and two different data
   pointers and make sure that changing both really works. */
static void test_grpc_fd_change(void) {
  grpc_fd *em_fd;
  fd_change_data a, b;
  int flags;
  int sv[2];
  char data;
  ssize_t result;
  grpc_closure first_closure;
  grpc_closure second_closure;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;

  first_closure.cb = first_read_callback;
  first_closure.cb_arg = &a;
  second_closure.cb = second_read_callback;
  second_closure.cb_arg = &b;

  init_change_data(&a);
  init_change_data(&b);

  GPR_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
  flags = fcntl(sv[0], F_GETFL, 0);
  GPR_ASSERT(fcntl(sv[0], F_SETFL, flags | O_NONBLOCK) == 0);
  flags = fcntl(sv[1], F_GETFL, 0);
  GPR_ASSERT(fcntl(sv[1], F_SETFL, flags | O_NONBLOCK) == 0);

  em_fd = grpc_fd_create(sv[0], "test_grpc_fd_change");
  grpc_pollset_add_fd(&exec_ctx, &g_pollset, em_fd);

  /* Register the first callback, then make its FD readable */
  grpc_fd_notify_on_read(&exec_ctx, em_fd, &first_closure);
  data = 0;
  result = write(sv[1], &data, 1);
  GPR_ASSERT(result == 1);

  /* And now wait for it to run. */
  gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  while (a.cb_that_ran == NULL) {
    grpc_pollset_worker worker;
    grpc_pollset_work(&exec_ctx, &g_pollset, &worker,
                      gpr_now(GPR_CLOCK_MONOTONIC),
                      gpr_inf_future(GPR_CLOCK_MONOTONIC));
    gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
    grpc_exec_ctx_finish(&exec_ctx);
    gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  }
  GPR_ASSERT(a.cb_that_ran == first_read_callback);
  gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));

  /* And drain the socket so we can generate a new read edge */
  result = read(sv[0], &data, 1);
  GPR_ASSERT(result == 1);

  /* Now register a second callback with distinct change data, and do the same
     thing again. */
  grpc_fd_notify_on_read(&exec_ctx, em_fd, &second_closure);
  data = 0;
  result = write(sv[1], &data, 1);
  GPR_ASSERT(result == 1);

  gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  while (b.cb_that_ran == NULL) {
    grpc_pollset_worker worker;
    grpc_pollset_work(&exec_ctx, &g_pollset, &worker,
                      gpr_now(GPR_CLOCK_MONOTONIC),
                      gpr_inf_future(GPR_CLOCK_MONOTONIC));
    gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));
    grpc_exec_ctx_finish(&exec_ctx);
    gpr_mu_lock(GRPC_POLLSET_MU(&g_pollset));
  }
  /* Except now we verify that second_read_callback ran instead */
  GPR_ASSERT(b.cb_that_ran == second_read_callback);
  gpr_mu_unlock(GRPC_POLLSET_MU(&g_pollset));

  grpc_fd_orphan(&exec_ctx, em_fd, NULL, "d");
  grpc_exec_ctx_finish(&exec_ctx);
  destroy_change_data(&a);
  destroy_change_data(&b);
  close(sv[1]);
}

static void destroy_pollset(grpc_exec_ctx *exec_ctx, void *p, int success) {
  grpc_pollset_destroy(p);
}

int main(int argc, char **argv) {
  grpc_closure destroyed;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_test_init(argc, argv);
  grpc_iomgr_init();
  grpc_pollset_init(&g_pollset);
  test_grpc_fd();
  test_grpc_fd_change();
  grpc_closure_init(&destroyed, destroy_pollset, &g_pollset);
  grpc_pollset_shutdown(&exec_ctx, &g_pollset, &destroyed);
  grpc_exec_ctx_finish(&exec_ctx);
  grpc_iomgr_shutdown();
  return 0;
}


text:
Step 7: Adding role based ACL security
======================================

**Note:**

> This bundle ships with support different security setups. You can also have a look at [Adding Symfony2's built in ACL security](8-adding_symfony2s_builtin_acl_security.md).

CommentBundle also provides the ability to configure permissions based on the roles
a specific user has. See the configuration example below for how to customise the
default roles used for permissions.

To configure Role based security override the Acl services:

``` yaml
# app/config/config.yml

fos_comment:
    acl: true
    service:
        acl:
            thread: fos_comment.acl.thread.roles
            comment: fos_comment.acl.comment.roles
            vote: fos_comment.acl.vote.roles
```

To change the roles required for specific actions, modify the `acl_roles` configuration
key:

``` yaml
# app/config/config.yml

fos_comment:
    acl_roles:
        comment:
            create: IS_AUTHENTICATED_ANONYMOUSLY
            view: IS_AUTHENTICATED_ANONYMOUSLY
            edit: ROLE_ADMIN
            delete: ROLE_ADMIN
        thread:
            create: IS_AUTHENTICATED_ANONYMOUSLY
            view: IS_AUTHENTICATED_ANONYMOUSLY
            edit: ROLE_ADMIN
            delete: ROLE_ADMIN
        vote:
            create: IS_AUTHENTICATED_ANONYMOUSLY
            view: IS_AUTHENTICATED_ANONYMOUSLY
            edit: ROLE_ADMIN
            delete: ROLE_ADMIN
```

## That is it!
[Return to the index.](index.md)


text:
    <META http-equiv="refresh" content="0;URL=http://sir-buckyball.github.io/opencut/src/index.html">

    You should be redirected to http://sir-buckyball.github.io/opencut/src/index.html.


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

namespace UniRitter.UniRitter2016.Models
{
    public enum HealthStatus
    {
        green,
        yellow,
        red
    }

    public class HealthCheck
    {
        public HealthStatus status { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.SolutionCrawler
{
    internal sealed partial class SolutionCrawlerRegistrationService
    {
        private sealed partial class WorkCoordinator
        {
            private sealed class SemanticChangeProcessor : IdleProcessor
            {
                private static readonly Func<int, DocumentId, bool, string> s_enqueueLogger = (t, i, b) => string.Format("[{0}] {1} - hint: {2}", t, i.ToString(), b);

                private readonly AsyncSemaphore _gate;

                private readonly Registration _registration;
                private readonly ProjectProcessor _processor;

                private readonly NonReentrantLock _workGate;
                private readonly Dictionary<DocumentId, Data> _pendingWork;

                public SemanticChangeProcessor(
                    IAsynchronousOperationListener listener,
                    Registration registration,
                    IncrementalAnalyzerProcessor documentWorkerProcessor,
                    int backOffTimeSpanInMS,
                    int projectBackOffTimeSpanInMS,
                    CancellationToken cancellationToken) :
                    base(listener, backOffTimeSpanInMS, cancellationToken)
                {
                    _gate = new AsyncSemaphore(initialCount: 0);

                    _registration = registration;

                    _processor = new ProjectProcessor(listener, registration, documentWorkerProcessor, projectBackOffTimeSpanInMS, cancellationToken);

                    _workGate = new NonReentrantLock();
                    _pendingWork = new Dictionary<DocumentId, Data>();

                    Start();
                }

                public override Task AsyncProcessorTask
                {
                    get
                    {
                        return Task.WhenAll(base.AsyncProcessorTask, _processor.AsyncProcessorTask);
                    }
                }

                protected override Task WaitAsync(CancellationToken cancellationToken)
                {
                    return _gate.WaitAsync(cancellationToken);
                }

                protected override async Task ExecuteAsync()
                {
                    var data = Dequeue();

                    // we have a hint. check whether we can take advantage of it
                    if (await TryEnqueueFromHint(data.Document, data.ChangedMember).ConfigureAwait(continueOnCapturedContext: false))
                    {
                        data.AsyncToken.Dispose();
                        return;
                    }

                    EnqueueFullProjectDependency(data.Document);
                    data.AsyncToken.Dispose();
                }

                private Data Dequeue()
                {
                    return DequeueWorker(_workGate, _pendingWork, this.CancellationToken);
                }

                private async Task<bool> TryEnqueueFromHint(Document document, SyntaxPath changedMember)
                {
                    if (changedMember == null)
                    {
                        return false;
                    }

                    // see whether we already have semantic model. otherwise, use the expansive full project dependency one
                    // TODO: if there is a reliable way to track changed member, we could use GetSemanticModel here which could
                    //       rebuild compilation from scratch
                    SemanticModel model;
                    SyntaxNode declarationNode;
                    if (!document.TryGetSemanticModel(out model) ||
                        !changedMember.TryResolve(await document.GetSyntaxRootAsync(this.CancellationToken).ConfigureAwait(false), out declarationNode))
                    {
                        return false;
                    }

                    var symbol = model.GetDeclaredSymbol(declarationNode, this.CancellationToken);
                    if (symbol == null)
                    {
                        return false;
                    }

                    return TryEnqueueFromMember(document, symbol) ||
                           TryEnqueueFromType(document, symbol);
                }

                private bool TryEnqueueFromType(Document document, ISymbol symbol)
                {
                    if (!IsType(symbol))
                    {
                        return false;
                    }

                    if (symbol.DeclaredAccessibility == Accessibility.Private)
                    {
                        EnqueueWorkItem(document, symbol);

                        Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromType, symbol.Name);
                        return true;
                    }

                    if (IsInternal(symbol))
                    {
                        var assembly = symbol.ContainingAssembly;
                        EnqueueFullProjectDependency(document, assembly);
                        return true;
                    }

                    return false;
                }

                private bool TryEnqueueFromMember(Document document, ISymbol symbol)
                {
                    if (!IsMember(symbol))
                    {
                        return false;
                    }

                    var typeSymbol = symbol.ContainingType;

                    if (symbol.DeclaredAccessibility == Accessibility.Private)
                    {
                        EnqueueWorkItem(document, symbol);

                        Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromMember, symbol.Name);
                        return true;
                    }

                    if (typeSymbol == null)
                    {
                        return false;
                    }

                    return TryEnqueueFromType(document, typeSymbol);
                }

                private void EnqueueWorkItem(Document document, ISymbol symbol)
                {
                    EnqueueWorkItem(document, symbol.ContainingType != null ? symbol.ContainingType.Locations : symbol.Locations);
                }

                private void EnqueueWorkItem(Document thisDocument, ImmutableArray<Location> locations)
                {
                    var solution = thisDocument.Project.Solution;
                    var projectId = thisDocument.Id.ProjectId;

                    foreach (var location in locations)
                    {
                        Contract.Requires(location.IsInSource);

                        var document = solution.GetDocument(location.SourceTree, projectId);
                        Contract.Requires(document != null);

                        if (thisDocument == document)
                        {
                            continue;
                        }

                        _processor.EnqueueWorkItem(document);
                    }
                }

                private bool IsInternal(ISymbol symbol)
                {
                    return symbol.DeclaredAccessibility == Accessibility.Internal ||
                           symbol.DeclaredAccessibility == Accessibility.ProtectedAndInternal ||
                           symbol.DeclaredAccessibility == Accessibility.ProtectedOrInternal;
                }

                private bool IsType(ISymbol symbol)
                {
                    return symbol.Kind == SymbolKind.NamedType;
                }

                private bool IsMember(ISymbol symbol)
                {
                    return symbol.Kind == SymbolKind.Event ||
                           symbol.Kind == SymbolKind.Field ||
                           symbol.Kind == SymbolKind.Method ||
                           symbol.Kind == SymbolKind.Property;
                }

                private void EnqueueFullProjectDependency(Document document, IAssemblySymbol internalVisibleToAssembly = null)
                {
                    var self = document.Project.Id;

                    // if there is no hint (this can happen for cases such as solution/project load and etc),
                    // we can postpond it even further
                    if (internalVisibleToAssembly == null)
                    {
                        _processor.Enqueue(self, needDependencyTracking: true);
                        return;
                    }

                    // most likely we got here since we are called due to typing.
                    // calculate dependency here and register each affected project to the next pipe line
                    var solution = document.Project.Solution;

                    var graph = solution.GetProjectDependencyGraph();
                    foreach (var projectId in graph.GetProjectsThatTransitivelyDependOnThisProject(self).Concat(self))
                    {
                        var project = solution.GetProject(projectId);
                        if (project == null)
                        {
                            continue;
                        }

                        Compilation compilation;
                        if (project.TryGetCompilation(out compilation))
                        {
                            var assembly = compilation.Assembly;
                            if (assembly != null && !assembly.IsSameAssemblyOrHasFriendAccessTo(internalVisibleToAssembly))
                            {
                                continue;
                            }
                        }

                        _processor.Enqueue(projectId);
                    }

                    Logger.Log(FunctionId.WorkCoordinator_SemanticChange_FullProjects, internalVisibleToAssembly == null ? "full" : "internals");
                }

                public void Enqueue(Document document, SyntaxPath changedMember)
                {
                    this.UpdateLastAccessTime();

                    using (_workGate.DisposableWait(this.CancellationToken))
                    {
                        Data data;
                        if (_pendingWork.TryGetValue(document.Id, out data))
                        {
                            // create new async token and dispose old one.
                            var newAsyncToken = this.Listener.BeginAsyncOperation("EnqueueSemanticChange");
                            data.AsyncToken.Dispose();

                            _pendingWork[document.Id] = new Data(document, data.ChangedMember == changedMember ? changedMember : null, newAsyncToken);
                            return;
                        }

                        _pendingWork.Add(document.Id, new Data(document, changedMember, this.Listener.BeginAsyncOperation("EnqueueSemanticChange")));
                        _gate.Release();
                    }

                    Logger.Log(FunctionId.WorkCoordinator_SemanticChange_Enqueue, s_enqueueLogger, Environment.TickCount, document.Id, changedMember != null);
                }

                private static TValue DequeueWorker<TKey, TValue>(NonReentrantLock gate, Dictionary<TKey, TValue> map, CancellationToken cancellationToken)
                {
                    using (gate.DisposableWait(cancellationToken))
                    {
                        var first = default(KeyValuePair<TKey, TValue>);
                        foreach (var kv in map)
                        {
                            first = kv;
                            break;
                        }

                        // this is only one that removes data from the queue. so, it should always succeed
                        var result = map.Remove(first.Key);
                        Contract.Requires(result);

                        return first.Value;
                    }
                }

                private struct Data
                {
                    public readonly Document Document;
                    public readonly SyntaxPath ChangedMember;
                    public readonly IAsyncToken AsyncToken;

                    public Data(Document document, SyntaxPath changedMember, IAsyncToken asyncToken)
                    {
                        this.AsyncToken = asyncToken;
                        this.Document = document;
                        this.ChangedMember = changedMember;
                    }
                }

                private class ProjectProcessor : IdleProcessor
                {
                    private static readonly Func<int, ProjectId, string> s_enqueueLogger = (t, i) => string.Format("[{0}] {1}", t, i.ToString());

                    private readonly AsyncSemaphore _gate;

                    private readonly Registration _registration;
                    private readonly IncrementalAnalyzerProcessor _processor;

                    private readonly NonReentrantLock _workGate;
                    private readonly Dictionary<ProjectId, Data> _pendingWork;

                    public ProjectProcessor(
                        IAsynchronousOperationListener listener,
                        Registration registration,
                        IncrementalAnalyzerProcessor processor,
                        int backOffTimeSpanInMS,
                        CancellationToken cancellationToken) :
                        base(listener, backOffTimeSpanInMS, cancellationToken)
                    {
                        _registration = registration;
                        _processor = processor;

                        _gate = new AsyncSemaphore(initialCount: 0);

                        _workGate = new NonReentrantLock();
                        _pendingWork = new Dictionary<ProjectId, Data>();

                        Start();
                    }

                    public void Enqueue(ProjectId projectId, bool needDependencyTracking = false)
                    {
                        this.UpdateLastAccessTime();

                        using (_workGate.DisposableWait(this.CancellationToken))
                        {
                            // the project is already in the queue. nothing needs to be done
                            if (_pendingWork.ContainsKey(projectId))
                            {
                                return;
                            }

                            var data = new Data(projectId, needDependencyTracking, this.Listener.BeginAsyncOperation("EnqueueWorkItemForSemanticChangeAsync"));
                            _pendingWork.Add(projectId, data);
                            _gate.Release();
                        }

                        Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, projectId);
                    }

                    public void EnqueueWorkItem(Document document)
                    {
                        // we are shutting down
                        this.CancellationToken.ThrowIfCancellationRequested();

                        // call to this method is serialized. and only this method does the writing.
                        var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
                        _processor.Enqueue(
                            new WorkItem(document.Id, document.Project.Language, InvocationReasons.SemanticChanged,
                            priorityService != null && priorityService.IsLowPriority(document),
                            this.Listener.BeginAsyncOperation("Semantic WorkItem")));
                    }

                    protected override Task WaitAsync(CancellationToken cancellationToken)
                    {
                        return _gate.WaitAsync(cancellationToken);
                    }

                    protected override Task ExecuteAsync()
                    {
                        var data = Dequeue();

                        var project = _registration.CurrentSolution.GetProject(data.ProjectId);
                        if (project == null)
                        {
                            data.AsyncToken.Dispose();
                            return Task.FromResult(true);
                        }

                        if (!data.NeedDependencyTracking)
                        {
                            EnqueueWorkItem(project);
                            data.AsyncToken.Dispose();
                            return Task.FromResult(true);
                        }

                        // do dependency tracking here with current solution
                        var solution = _registration.CurrentSolution;

                        var graph = solution.GetProjectDependencyGraph();
                        foreach (var projectId in graph.GetProjectsThatTransitivelyDependOnThisProject(data.ProjectId).Concat(data.ProjectId))
                        {
                            project = solution.GetProject(projectId);
                            EnqueueWorkItem(project);
                        }

                        data.AsyncToken.Dispose();
                        return Task.FromResult(true);
                    }

                    private Data Dequeue()
                    {
                        return DequeueWorker(_workGate, _pendingWork, this.CancellationToken);
                    }

                    private void EnqueueWorkItem(Project project)
                    {
                        if (project == null)
                        {
                            return;
                        }

                        foreach (var documentId in project.DocumentIds)
                        {
                            EnqueueWorkItem(project.GetDocument(documentId));
                        }
                    }

                    private struct Data
                    {
                        public readonly IAsyncToken AsyncToken;
                        public readonly ProjectId ProjectId;
                        public readonly bool NeedDependencyTracking;

                        public Data(ProjectId projectId, bool needDependencyTracking, IAsyncToken asyncToken)
                        {
                            this.AsyncToken = asyncToken;
                            this.ProjectId = projectId;
                            this.NeedDependencyTracking = needDependencyTracking;
                        }
                    }
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Input;

namespace BlisterUI.Input {
    public class TextInput : IDisposable {
        public bool IsActive {
            get;
            private set;
        }

        private StringBuilder text;
        public string Text {
            get { return text.ToString(); }
            set {
                text.Clear();
                text.Append(value);
                Caret = Math.Min(Caret, Length);
                if(OnTextChanged != null)
                    OnTextChanged(this, Text);
            }
        }
        private int caret;
        public int Caret {
            get { return caret; }
            private set {
                caret = value;
                if(OnCaretMoved != null)
                    OnCaretMoved(this, Caret);
            }
        }
        public int Length {
            get { return text.Length; }
        }

        public event Action<TextInput, string> OnTextEntered;
        public event Action<TextInput, string> OnTextChanged;
        public event Action<TextInput, int> OnCaretMoved;

        public TextInput() {
            text = new StringBuilder();
            Caret = 0;
            IsActive = false;
        }
        public void Dispose() {
            OnTextEntered = null;
            OnTextChanged = null;
            OnCaretMoved = null;
            Deactivate();
            text.Clear();
            text = null;
        }

        public void Activate() {
            if(IsActive) return;
            IsActive = true;

            KeyboardEventDispatcher.OnKeyPressed += OnKeyPress;
            KeyboardEventDispatcher.ReceiveChar += OnChar;
            KeyboardEventDispatcher.ReceiveCommand += OnControl;
        }
        public void Deactivate() {
            if(!IsActive) return;
            IsActive = false;

            KeyboardEventDispatcher.OnKeyPressed -= OnKeyPress;
            KeyboardEventDispatcher.ReceiveChar -= OnChar;
            KeyboardEventDispatcher.ReceiveCommand -= OnControl;
        }

        public void Insert(char c) {
            text.Insert(Caret, c);
            Caret++;
            if(OnTextChanged != null)
                OnTextChanged(this, Text);
        }
        public void Insert(string s) {
            if(string.IsNullOrEmpty(s))
                return;
            text.Insert(Caret, s);
            Caret += s.Length;
            if(OnTextChanged != null)
                OnTextChanged(this, Text);
        }
        public void Delete() {
            if(Caret == Length)
                return;
            text.Remove(Caret, 1);
            if(OnTextChanged != null)
                OnTextChanged(this, Text);
        }
        public void BackSpace() {
            if(Caret == 0)
                return;
            Caret--;
            Delete();
        }

        public void OnKeyPress(object s, KeyEventArgs args) {
            switch(args.KeyCode) {
                case Keys.Enter:
                    if(text.Length < 1)
                        return;
                    if(OnTextEntered != null)
                        OnTextEntered(this, Text);
                    return;
                case Keys.Back:
                    BackSpace();
                    return;
                case Keys.Delete:
                    Delete();
                    return;
                case Keys.Left:
                    if(Caret > 0) Caret--;
                    return;
                case Keys.Right:
                    if(Caret < Length) Caret++;
                    return;
            }
        }
        public void OnChar(object s, CharacterEventArgs args) {
            Insert(args.Character);
        }
        public void OnControl(object s, CharacterEventArgs args) {
            switch(args.Character) {
                case ControlCharacters.CtrlV:
                    string c = KeyboardEventDispatcher.GetNewClipboard();
                    Insert(c);
                    return;
                case ControlCharacters.CtrlC:
                    if(text.Length > 0)
                        KeyboardEventDispatcher.SetToClipboard(Text);
                    return;
            }
        }
    }
}


text:
The release process hopes to encourage early, consistent consensus-building during project development.
The mechanisms used are regular community communication on the mailing list about progress, scheduled meetings for issue resolution and release triage, and regularly paced and communicated releases.
Releases are proposed and adopted or rejected using the usual [project governance](GOVERNANCE.md) rules and procedures.

An anti-pattern that we want to avoid is heavy development or discussions "late cycle" around major releases.
We want to build a community that is involved and communicates consistently through all releases instead of relying on "silent periods" as a judge of stability.

## Parallel releases

A single project MAY consider several motions to release in parallel.
However each motion to release after the initial 0.1.0 MUST be based on a previous release that has already landed.

For example, runtime-spec maintainers may propose a v1.0.0-rc2 on the 1st of the month and a v0.9.1 bugfix on the 2nd of the month.
They may not propose a v1.0.0-rc3 until the v1.0.0-rc2 is accepted (on the 7th if the vote initiated on the 1st passes).

## Specifications

The OCI maintains three categories of projects: specifications, applications, and conformance-testing tools.
However, specification releases have special restrictions in the [OCI charter][charter]:

* They are the target of backwards compatibility (§7.g), and
* They are subject to the OFWa patent grant (§8.d and e).

To avoid unfortunate side effects (onerous backwards compatibity requirements or Member resignations), the following additional procedures apply to specification releases:

### Planning a release

Every OCI specification project SHOULD hold meetings that involve maintainers reviewing pull requests, debating outstanding issues, and planning releases.
This meeting MUST be advertised on the project README and MAY happen on a phone call, video conference, or on IRC.
Maintainers MUST send updates to the dev@opencontainers.org with results of these meetings.

Before the specification reaches v1.0.0, the meetings SHOULD be weekly.
Once a specification has reached v1.0.0, the maintainers may alter the cadence, but a meeting MUST be held within four weeks of the previous meeting.

The release plans, corresponding milestones and estimated due dates MUST be published on GitHub (e.g. https://github.com/opencontainers/runtime-spec/milestones).
GitHub milestones and issues are only used for community organization and all releases MUST follow the [project governance](GOVERNANCE.md) rules and procedures.

### Timelines

Specifications have a variety of different timelines in their lifecycle.

* Pre-v1.0.0 specifications SHOULD release on a monthly cadence to garner feedback.
* Major specification releases MUST release at least three release candidates spaced a minimum of one week apart.
  This means a major release like a v1.0.0 or v2.0.0 release will take 1 month at minimum: one week for rc1, one week for rc2, one week for rc3, and one week for the major release itself.
  Maintainers SHOULD strive to make zero breaking changes during this cycle of release candidates and SHOULD restart the three-candidate count when a breaking change is introduced.
  For example if a breaking change is introduced in v1.0.0-rc2 then the series would end with v1.0.0-rc4 and v1.0.0.
* Minor and patch releases SHOULD be made on an as-needed basis.

[charter]: https://www.opencontainers.org/about/governance


text:
<?php

namespace Rjakes\FmPdo;

use Exception;
use PDO;

class Find
{
    /**
     * @var FmPdo
     */
    private $fmPdo;
    private $table;
    private $selectFields = array();
    private $findCriteria = array();
    private $sortRules = array();
    private $limit;

    /**
     * Find command constructor.
     * Assign variable and check parameter
     */
    public function __construct($table, FmPdo $fmPdo = null)
    {
        $this->fmPdo = $fmPdo;
        $this->table = $table;
    }

    /**
     * Adds field to be used in the SQL select, to limit the return
     * @param $fieldArray
     * @return NULL | Error
     */
    public function setSelectFields($fieldArray)
    {
        if (!isset($fieldArray) or !is_array($fieldArray)) {
            return new Error("Missing parameter to Find->setSelectFields", "-1");
        }
        $this->selectFields = $fieldArray;
    }

    /**
     * Adds a find criteria with an optional find operator
     * @param $field
     * @param $value
     */
    public function addFindCriterion($field, $value, $operator = '=')
    {
        $this->findCriteria[$field]['value'] = $value;
        $this->findCriteria[$field]['operator'] = $operator;

    }

    /**
     * Adds a single sort rule to the array of sort rules
     * @param $field
     * @param $precedence
     * @param string $direction // direction names are FileMaker standard for backwards compatibility
     */
    public function addSortRule($field, $precedence, $direction = 'ascend')
    {
        $sqlOrder = strtolower($direction) == "descend" ? "DESC" : "ASC";
        $this->sortRules[$precedence] = array('field' => $field, 'direction' => $sqlOrder);
    }

    /**
     * Stores the optional SQL LIMIT value
     * @param $limit
     */
    public function setLimit($limit)
    {
        $this->limit = $limit;
    }

    /**
     * Transforms the passed select fields into SQL
     * @param $fieldArray
     * @return string
     */
    private function sqlSelect($fieldArray)
    {
        $selectString = "SELECT ";
        if (empty($fieldArray)) {
            $selectString .= '*';
        } else {
            foreach ($fieldArray as $k => $v) {
                $selectString .= $v . ',';
            }
            $selectString = substr($selectString, 0, -1);
        }
        return $selectString;
    }

    /**
     * Transforms the passed find criteria into SQL
     * @param $whereArray
     * @return string
     */
    private function sqlWhere($whereArray)
    {
        $whereString = "";
        if (!empty($whereArray)) {
            foreach ($whereArray as $k => $v) {
                $op = isset($v['operator']) ? $v['operator'] : "=";
                $whereString .= $k . $op . ":" . $k . " AND ";
            }
            $whereString = "WHERE " . substr($whereString, 0, -5);
        }
        return $whereString;
    }

    /**
     * Transforms the passed orderby array into SQL
     * @param $orderByArray
     * @return string
     */
    private function sqlOrderBy($orderByArray)
    {
        $orderString = "";
        ksort($orderByArray);
        if (!empty($orderByArray)) {
            foreach ($orderByArray as $orderBy) {
                $orderString .= " `" . $orderBy['field'] . "` " . $orderBy['direction'] . ",";
            }
            $orderString = "ORDER BY" . substr($orderString, 0, -1);
        }
        return $orderString;
    }

    /**
     * Transforms passed limit value into SQL
     * @param $limit
     * @return string
     */
    private function sqlLimit($limit)
    {
        if (intval($limit)) {
            return "LIMIT " . intval($limit);
        }
    }

    public function setRelatedSetsFilters()
    {
        //this function is supposedly like a limit.
        //@see FileMaker_Command_Find
        //we don't support this limit function right now.
    }

    public function assemble()
    {
        $selectString = $this->sqlSelect($this->selectFields);
        $whereString = $this->sqlWhere($this->findCriteria);
        $orderString = $this->sqlOrderBy($this->sortRules);
        $limitString = $this->sqlLimit($this->limit);
        return $selectString
        . ' FROM '
        . $this->table
        . " "
        . $whereString
        . " "
        . $orderString
        . " "
        . $limitString
        . ';';
    }

    /**
     * Assembles the object properties and executes the SQL SELECT statement
     * @return Error|Result
     */
    public function execute()
    {
        $db = $this->fmPdo->getConnection();
        try {
            $query = $db->prepare($this->assemble());
            if (!$query) {
                return new Error($db->errorInfo());
            }
            foreach ($this->findCriteria as $k => $v) {
                $query->bindParam(':' . $k, $v['value'], PDO::PARAM_STR);
            }
            $result = $query->execute();
        } catch (Exception $e) {
            return new Error($e);
        }

        $rows = $query->fetchAll();

        if (count($rows) > 0) {
            return new Result($this->table, $rows);
        } else {
            return new Error("No records found", "401");
        }

    }
}


text:
package org.talend.components.google.drive.runtime;

import java.io.IOException;
import java.security.GeneralSecurityException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.talend.components.api.component.runtime.ComponentDriverInitialization;
import org.talend.components.api.container.RuntimeContainer;
import org.talend.components.api.exception.ComponentException;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.google.drive.GoogleDriveComponentProperties.AccessMethod;
import org.talend.components.google.drive.create.GoogleDriveCreateDefinition;
import org.talend.components.google.drive.create.GoogleDriveCreateProperties;
import org.talend.daikon.properties.ValidationResult;
import org.talend.daikon.properties.ValidationResult.Result;

public class GoogleDriveCreateRuntime extends GoogleDriveRuntime implements ComponentDriverInitialization<ComponentProperties> {

    private GoogleDriveCreateProperties properties;

    private String parentFolderId;

    private String newFolderId;

    private transient static final Logger LOG = LoggerFactory.getLogger(GoogleDriveCreateRuntime.class);

    @Override
    public ValidationResult initialize(RuntimeContainer container, ComponentProperties properties) {
        ValidationResult vr = super.initialize(container, properties);
        if (vr.getStatus().equals(Result.ERROR)) {
            return vr;
        }
        this.properties = (GoogleDriveCreateProperties) properties;
        return validateProperties(this.properties);
    }

    @Override
    public void runAtDriver(RuntimeContainer container) {
        createFolder(container);
        setReturnValues(container);
    }

    public void createFolder(RuntimeContainer container) {
        try {
            final GoogleDriveUtils utils = getDriveUtils();
            utils.setIncludeSharedDrives(properties.includeSharedDrives.getValue());
            if (properties.includeSharedDrives.getValue()) {
                utils.setCorpora(properties.corpora.getValue());
                utils.setDriveId(properties.driveId.getValue());
            }
            String parentFolder = properties.parentFolder.getValue();
            parentFolderId = properties.parentFolderAccessMethod.getValue().equals(AccessMethod.Id) ? parentFolder
                    : utils.getFolderId(parentFolder, false, properties.includeSharedItems.getValue());
            newFolderId = utils.createFolder(parentFolderId, properties.newFolder.getValue());
        } catch (IOException | GeneralSecurityException e) {
            LOG.error(e.getLocalizedMessage());
            throw new ComponentException(e);
        }
    }

    public void setReturnValues(RuntimeContainer container) {
        String componentId = container.getCurrentComponentId();
        container.setComponentData(componentId, getStudioName(GoogleDriveCreateDefinition.RETURN_PARENT_FOLDER_ID),
                parentFolderId);
        container.setComponentData(componentId, getStudioName(GoogleDriveCreateDefinition.RETURN_NEW_FOLDER_ID), newFolderId);
    }
}


text:
'use strict'

const utils = require('../../../../utils/common')
const createNewLeaderboardHousehold = require('../helpers/createNewLeaderboardHousehold')
const sortByTotalCo2 = require('../../common/helpers/sortByTotalCo2')

function updateChallengeDepartmentAllLeaderboard (context) {
  const data = context.input.data
  const firebase = context.firebase
  const scoreModifier = context.input.scoreModifier
  const transactionPath = `challenges/leaderboards/${data.challengeKey}/${data.departmentKey}/all`

  return firebase.transaction(transactionPath, (maybeCurrentChallengeLeaderboard) => {
    const currentChallengeLeaderboard = maybeCurrentChallengeLeaderboard || {}

    const leaderboardHousehold = (
      currentChallengeLeaderboard[data.householdKey]
        ? utils.merge({}, currentChallengeLeaderboard[data.householdKey])
        : createNewLeaderboardHousehold()
    )

    if (!leaderboardHousehold.days[data.datetime]) {
      leaderboardHousehold.days[data.datetime] = {
        points: {energy: 0, food: 0, social: 0, transport: 0, consumption: 0},
        co2: {energy: 0, food: 0, social: 0, transport: 0, consumption: 0}
      }
    }

    leaderboardHousehold.days[data.datetime].co2[data.categoryKey] = (
      utils.toCo2(
        leaderboardHousehold.days[data.datetime].co2[data.categoryKey] +
        scoreModifier.co2
      )
    )

    leaderboardHousehold.days[data.datetime].points[data.categoryKey] += scoreModifier.points

    leaderboardHousehold.totalPoints += scoreModifier.points

    leaderboardHousehold.totalCo2 = utils.toCo2(leaderboardHousehold.totalCo2 + scoreModifier.co2)

    currentChallengeLeaderboard[data.householdKey] = leaderboardHousehold

    return Object.keys(currentChallengeLeaderboard)
      .sort(sortByTotalCo2(currentChallengeLeaderboard))
      .reduce((newChallengeLeaderboard, key, index) => {
        newChallengeLeaderboard[key] = currentChallengeLeaderboard[key]
        newChallengeLeaderboard[key].position = index + 1

        return newChallengeLeaderboard
      }, {})
  })
  .then(() => null)
}

module.exports = updateChallengeDepartmentAllLeaderboard


text:
<?php

namespace Shim\Test\TestCase\Generator\Task;

use Cake\TestSuite\TestCase;
use IdeHelper\Generator\Directive\RegisterArgumentsSet;
use Shim\Generator\Task\ConfigureHelperTask;
use Shim\TestSuite\TestTrait;

class ConfigureHelperTaskTest extends TestCase {

	use TestTrait;

	/**
	 * @var \IdeHelper\Generator\Task\ConfigureHelperTask
	 */
	protected $task;

	/**
	 * @return void
	 */
	public function setUp(): void {
		parent::setUp();

		$this->task = new ConfigureHelperTask();
	}

	/**
	 * @return void
	 */
	public function testCollect() {
		$result = $this->task->collect();

		$this->assertCount(6, $result);

		/** @var \IdeHelper\Generator\Directive\RegisterArgumentsSet $directive */
		$directive = array_shift($result);
		$this->assertInstanceOf(RegisterArgumentsSet::class, $directive);
		$this->assertSame(ConfigureHelperTask::SET_CONFIGURE_KEYS, $directive->toArray()['set']);

		/** @var \IdeHelper\Generator\Directive\ExpectedArguments $directive */
		$directive = array_shift($result);
		$this->assertSame('\Shim\View\Helper\ConfigureHelper::read()', $directive->toArray()['method']);

		$list = $directive->toArray()['list'];
		$list = array_map(function ($className) {
			return (string)$className;
		}, $list);

		$expected = [
			'argumentsSet(\'configureHelperKeys\')',
		];
		$this->assertSame($expected, $list);
	}

	/**
	 * @return void
	 */
	public function testCollectKeys(): void {
		$result = $this->invokeMethod($this->task, 'collectKeys');

		$this->assertArrayHasKey('App.paths.templates', $result);
		$this->assertArrayNotHasKey('paths', $result);
		$this->assertArrayNotHasKey('templates', $result);

		$this->assertSame('\'debug\'', (string)$result['debug']);
	}

}


text:
package com.android.browser.preferences;

import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.android.browser.BrowserSettings;
import com.android.browser.R;

public class FontSizePreview extends WebViewPreview {

    static final String HTML_FORMAT = "<!DOCTYPE html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">
%s

%s

%s

%s

%s
";

    String mHtml;

    public FontSizePreview(
            Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public FontSizePreview(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FontSizePreview(Context context) {
        super(context);
    }

    @Override
    protected void init(Context context) {
        super.init(context);
        Resources res = context.getResources();
        Object[] visualNames = res.getStringArray(R.array.pref_text_size_choices);
        mHtml = String.format(HTML_FORMAT, visualNames);
    }

    @Override
    protected void updatePreview(boolean forceReload) {
        if (mWebView == null) return;

        WebSettings ws = mWebView.getSettings();
        BrowserSettings bs = BrowserSettings.getInstance();
        ws.setMinimumFontSize(bs.getMinimumFontSize());
        ws.setTextZoom(bs.getTextZoom());
        mWebView.loadDataWithBaseURL(null, mHtml, "text/html", "utf-8", null);
    }

    @Override
    protected void setupWebView(WebView view) {
        super.setupWebView(view);
        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

}


text:
/**
 *  Test set calls native functions with various number of arguments.
 */
 package com.intel.JACW.jni;


text:
package scalaxy.streams

import scala.collection.generic.CanBuildFrom

private[streams] trait SetBuilderSinks extends BuilderSinks {
  val global: scala.reflect.api.Universe
  import global._

  case object SetBuilderSink extends BuilderSink
  {
    override def describe = Some("Set")

    override def usesSizeHint = false

    override def subTrees = Nil

    override def isFinalOnly = true

    override def createBuilder(inputVars: TuploidValue[Tree], typed: Tree => Tree) = {
      val setModule =
        rootMirror.staticModule("scala.collection.immutable.Set")
      typed(q"$setModule.canBuildFrom[${inputVars.tpe}]()")
    }
  }
}


text:
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "Xlibint.h"

int
XQueryColor(
    register Display *dpy,
    Colormap cmap,
    XColor *def)	/* RETURN */
{
    xrgb color;
    xQueryColorsReply rep;
    register xQueryColorsReq *req;
    unsigned long val = def->pixel;	/* needed for macro below */

    LockDisplay(dpy);
    GetReqExtra(QueryColors, 4, req); /* a pixel (CARD32) is 4 bytes */
    req->cmap = cmap;

    OneDataCard32 (dpy, NEXTPTR(req,xQueryColorsReq), val);

    if (_XReply(dpy, (xReply *) &rep, 0, xFalse) != 0) {

	    _XRead(dpy, (char *)&color, (long) SIZEOF(xrgb));

	    def->red = color.red;
	    def->blue = color.blue;
	    def->green = color.green;
	    def->flags = DoRed | DoGreen | DoBlue;
        }
    UnlockDisplay(dpy);
    SyncHandle();
    return 1;
}


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('sponsors', '0027_sponsorbenefit_program_name'),
    ]

    operations = [
        migrations.AlterField(
            model_name='sponsorshipbenefit',
            name='program',
            field=models.ForeignKey(help_text='Which sponsorship program the benefit is associated with.', on_delete=django.db.models.deletion.CASCADE, to='sponsors.SponsorshipProgram', verbose_name='Sponsorship Program'),
        ),
    ]


text:
require_relative './test_base'
require 'experiment'
require 'test/unit'
require 'tmpdir'
require 'json'

class TestSignal < ExperimentTestCase

	def test_sig
		["TERM", "INT"].each do |s|
			@e["arguments"] = ["$SRC/test", "5000"]
			@e["iterations"] = 10
			Dir.mktmpdir("test_", ".") {|d|
				build d

				d = File.absolute_path d
				File.open File.join(d, "experiment.json"), "w" do |f|
					f.write(JSON.generate(@e))
				end

				here = File.absolute_path Dir.pwd
				bin = File.absolute_path File.join(File.dirname(__FILE__), "../bin/experiment")
				Dir.chdir d
				pid = Kernel.spawn(bin, "--trace", "--output", File.join(d, "out"), :out => "/dev/null", :err => "/dev/null")
				Dir.chdir here

				Kernel.sleep 1

				killat = Time.now
				Process.kill(s, pid)
				Process.waitpid pid
				took = Time.now - killat

				assert_compare(took, "<", 1)
			}
		end
	end

end