text:
using namespace ndnrtc;
using namespace ndnrtc::statistics;
using namespace ndn;
using namespace testing;

//******************************************************************************
TEST(TestSlotSegment, TestCreate)
{
	{
		std::string name = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07/%00%00";
		boost::shared_ptr<Interest> interest(boost::make_shared<Interest>(Name(name), 1000));
		EXPECT_NO_THROW(SlotSegment s(interest));

		SlotSegment seg(interest);
		EXPECT_NE(0, seg.getRequestTimeUsec());
		EXPECT_FALSE(seg.isRightmostRequested());
	}
	{
		std::string name = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d";
		boost::shared_ptr<Interest> interest(boost::make_shared<Interest>(Name(name), 1000));
		EXPECT_NO_THROW(SlotSegment s(interest));

		SlotSegment seg(interest);
		EXPECT_TRUE(seg.isRightmostRequested());
	}
	{
		std::string name = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%07/%00%00";
		boost::shared_ptr<Interest> interest(boost::make_shared<Interest>(Name(name), 1000));
		EXPECT_NO_THROW(SlotSegment s(interest));

		SlotSegment seg(interest);
		EXPECT_FALSE(seg.isRightmostRequested());
	}
	{
		std::string name = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd";
		boost::shared_ptr<Interest> interest(boost::make_shared<Interest>(Name(name), 1000));
		EXPECT_NO_THROW(SlotSegment s(interest));

		SlotSegment seg(interest);
		EXPECT_TRUE(seg.isRightmostRequested());
	}
}

TEST(TestBufferSlot, TestRtx)
{
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%07";
	std::vector<boost::shared_ptr<const Interest>> interests;
	int n = 10;

	for (int i = 0; i < n; ++i)
	{
		Name iname(frameName);
		iname.appendSegment(i);
		interests.push_back(boost::make_shared<Interest>(iname, 1000));
	}

	BufferSlot slot;

	EXPECT_EQ(BufferSlot::Free, slot.getState());
	EXPECT_NO_THROW(slot.segmentsRequested(interests));
	EXPECT_EQ(7, slot.getNameInfo().sampleNo_);
	EXPECT_EQ(Name(frameName), slot.getPrefix());

    EXPECT_EQ(0, slot.getRtxNum());
    EXPECT_NO_THROW(slot.segmentsRequested(interests));
    EXPECT_EQ(n, slot.getRtxNum());

    for (auto i:interests)
        EXPECT_EQ(1, slot.getRtxNum(i->getName()));

	EXPECT_EQ(0, slot.getAssembledLevel());
	EXPECT_EQ(BufferSlot::New, slot.getState());
}

TEST(TestBufferSlot, TestAddInterests)
{
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%07";
	std::vector<boost::shared_ptr<const Interest>> interests;
	int n = 10;

	for (int i = 0; i < n; ++i)
	{
		Name iname(frameName);
		iname.appendSegment(i);
		interests.push_back(boost::make_shared<Interest>(iname, 1000));
	}

	BufferSlot slot;

	EXPECT_EQ(BufferSlot::Free, slot.getState());
	EXPECT_NO_THROW(slot.segmentsRequested(interests));
	EXPECT_EQ(7, slot.getNameInfo().sampleNo_);
	EXPECT_EQ(Name(frameName), slot.getPrefix());

	EXPECT_EQ(0, slot.getAssembledLevel());
	EXPECT_EQ(BufferSlot::New, slot.getState());
}

TEST(TestBufferSlot, TestAddInterestsTwoTimes)
{
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%07";
	std::vector<boost::shared_ptr<const Interest>> interests;
	int n = 10;

	for (int i = 0; i < n/2; ++i)
	{
		Name iname(frameName);
		iname.appendSegment(i);
		interests.push_back(boost::make_shared<Interest>(iname, 1000));
	}

	BufferSlot slot;

	EXPECT_EQ(BufferSlot::Free, slot.getState());
	EXPECT_NO_THROW(slot.segmentsRequested(interests));
	EXPECT_EQ(7, slot.getNameInfo().sampleNo_);
	EXPECT_EQ(Name(frameName), slot.getPrefix());

	EXPECT_EQ(0, slot.getAssembledLevel());
	EXPECT_EQ(BufferSlot::New, slot.getState());

	interests.clear();
	for (int i = n/2; i < n; ++i)
	{
		Name iname(frameName);
		iname.appendSegment(i);
		interests.push_back(boost::make_shared<Interest>(iname, 1000));
	}

	EXPECT_EQ(BufferSlot::New, slot.getState());
	EXPECT_NO_THROW(slot.segmentsRequested(interests));
	EXPECT_EQ(7, slot.getNameInfo().sampleNo_);
	EXPECT_EQ(Name(frameName), slot.getPrefix());

	EXPECT_EQ(0, slot.getAssembledLevel());
	EXPECT_EQ(BufferSlot::New, slot.getState());

}

TEST(TestBufferSlot, TestBadInterestRange)
{
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%07";

	{
		std::vector<boost::shared_ptr<const Interest>> interests;
		Name iname(frameName);
		interests.push_back(boost::make_shared<Interest>(iname, 1000));
		iname.appendSegment(0);
		interests.push_back(boost::make_shared<Interest>(iname, 1000));

		BufferSlot slot;
		EXPECT_ANY_THROW(slot.segmentsRequested(interests));
		EXPECT_EQ(slot.getState(), BufferSlot::Free);
	}
	{
		std::vector<boost::shared_ptr<const Interest>> interests;
		Name iname(frameName);
		iname.appendSegment(0);
		interests.push_back(boost::make_shared<Interest>(iname, 1000));
		interests.push_back(boost::make_shared<Interest>(Name(frameName), 1000));

		BufferSlot slot;
		EXPECT_ANY_THROW(slot.segmentsRequested(interests));
		EXPECT_NE(BufferSlot::Free, slot.getState());
		slot.clear();
		EXPECT_EQ(BufferSlot::Free, slot.getState());
	}
	{
		std::vector<boost::shared_ptr<const Interest>> interests;
		interests.push_back(boost::make_shared<Interest>(Name("/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%07").appendSegment(0), 1000));
		interests.push_back(boost::make_shared<Interest>(Name("/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%08").appendSegment(0), 1000));

		BufferSlot slot;
		EXPECT_ANY_THROW(slot.segmentsRequested(interests));
		EXPECT_NE(BufferSlot::Free, slot.getState());
		slot.clear();
		EXPECT_EQ(BufferSlot::Free, slot.getState());
	}
}

TEST(TestBufferSlot, TestAddData)
{
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%07";
	VideoFramePacket vp = getVideoFramePacket();
	std::vector<VideoFrameSegment> segments = sliceFrame(vp);

	{ // all data arrived in order
		std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
		std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size());
		BufferSlot slot;

		slot.segmentsRequested(makeInterestsConst(interests));
		ASSERT_EQ(BufferSlot::New, slot.getState());

		int idx = 0;
		for (auto d:dataObjects)
		{
			boost::shared_ptr<WireSegment> wd(boost::make_shared<WireSegment>(d, interests[idx]));
			BufferSlot::State state;

			if (idx == 0) EXPECT_TRUE(slot.getConsistencyState() == BufferSlot::Inconsistent);

			slot.segmentReceived(wd);
			// EXPECT_NO_THROW(slot.segmentReceived(wd));

			EXPECT_TRUE(slot.getConsistencyState()&BufferSlot::HeaderMeta);
			EXPECT_TRUE(slot.getConsistencyState()&BufferSlot::SegmentMeta);
			EXPECT_EQ(slot.getConsistencyState(), BufferSlot::Consistent);

			if (++idx < dataObjects.size())
				EXPECT_EQ(BufferSlot::Assembling, slot.getState());
			else
				EXPECT_EQ(BufferSlot::Ready, slot.getState());

			EXPECT_EQ(round((double)idx/(double)dataObjects.size()*100)/100,
				round(slot.getAssembledLevel()*100)/100);
			EXPECT_TRUE(slot.hasOriginalSegments());
		}
	}

	{ // all data arrived in random order
		std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
		std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size());
		BufferSlot slot;

		slot.segmentsRequested(makeInterestsConst(interests));
		ASSERT_EQ(BufferSlot::New, slot.getState());

		std::random_shuffle(dataObjects.begin(), dataObjects.end());

		int idx = 0;
		for (auto d:dataObjects)
		{
			boost::shared_ptr<WireSegment> wd(boost::make_shared<WireSegment>(d, interests[idx]));
			BufferSlot::State state;

			if (idx == 0) EXPECT_TRUE(slot.getConsistencyState() == BufferSlot::Inconsistent);

			EXPECT_NO_THROW(slot.segmentReceived(wd));

			if (wd->getSampleNo() == 0)
				EXPECT_TRUE(slot.getConsistencyState()&BufferSlot::HeaderMeta);
			else
				EXPECT_TRUE(slot.getConsistencyState()&BufferSlot::SegmentMeta);

			if (++idx < dataObjects.size())
				EXPECT_EQ(BufferSlot::Assembling, slot.getState());
			else
				EXPECT_EQ(BufferSlot::Ready, slot.getState());

			EXPECT_EQ(round((double)idx/(double)dataObjects.size()*100)/100,
				round(slot.getAssembledLevel()*100)/100);
			EXPECT_LT(0, slot.getShortestDrd());
			if (idx < dataObjects.size())
			{
				EXPECT_EQ(0, slot.getAssemblingTime());
				EXPECT_EQ(0, slot.getLongestDrd());
			}
		}
		EXPECT_LT(0, slot.getAssemblingTime());
		EXPECT_LT(0, slot.getLongestDrd());
		EXPECT_EQ(slot.getConsistencyState(), BufferSlot::Consistent);
	}

	{ // some data arrived multiple times
		std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
		std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size());
		BufferSlot slot;

		slot.segmentsRequested(makeInterestsConst(interests));
		ASSERT_EQ(BufferSlot::New, slot.getState());

		std::random_shuffle(dataObjects.begin(), dataObjects.end());
		std::vector<boost::shared_ptr<ndn::Data>> objects(dataObjects);
		objects.insert(objects.end(), dataObjects.begin(), dataObjects.begin()+3);

		int idx = 0;
		for (auto d:objects)
		{
			boost::shared_ptr<WireSegment> wd(boost::make_shared<WireSegment>(d, interests[idx%dataObjects.size()]));
			BufferSlot::State state;

			if (idx == 0) EXPECT_TRUE(slot.getConsistencyState() == BufferSlot::Inconsistent);

			EXPECT_NO_THROW(slot.segmentReceived(wd));

			if (wd->getSampleNo() == 0)
				EXPECT_TRUE(slot.getConsistencyState()&BufferSlot::HeaderMeta);
			else
				EXPECT_TRUE(slot.getConsistencyState()&BufferSlot::SegmentMeta);

			if (++idx < dataObjects.size())
				EXPECT_EQ(BufferSlot::Assembling, slot.getState());
			else
				EXPECT_EQ(BufferSlot::Ready, slot.getState());

			if (idx <= dataObjects.size())
				EXPECT_EQ(round((double)idx/(double)dataObjects.size()*100)/100,
					round(slot.getAssembledLevel()*100)/100);
			else
				EXPECT_EQ(1, slot.getAssembledLevel());
			EXPECT_LT(0, slot.getShortestDrd());
			if (idx < dataObjects.size())
			{
				EXPECT_EQ(0, slot.getAssemblingTime());
				EXPECT_EQ(0, slot.getLongestDrd());
			}
		}
		EXPECT_LT(0, slot.getAssemblingTime());
		EXPECT_LT(0, slot.getLongestDrd());
		EXPECT_EQ(slot.getConsistencyState(), BufferSlot::Consistent);
	}

	{ // add data that was not requested
		std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
		std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size());
		BufferSlot slot;

		slot.segmentsRequested(makeInterestsConst(interests));
		ASSERT_EQ(BufferSlot::New, slot.getState());
		boost::shared_ptr<Data> dobj = dataObjects.back();
		dobj->setName(Name(frameName).appendSegment(100));
		boost::shared_ptr<ndn::Interest> i;
		EXPECT_ANY_THROW(slot.segmentReceived(boost::make_shared<WireSegment>(dobj, i)));
	}

	{ // add incorrectly named data
		std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
		std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size());
		BufferSlot slot;

		slot.segmentsRequested(makeInterestsConst(interests));
		ASSERT_EQ(BufferSlot::New, slot.getState());
		boost::shared_ptr<Data> dobj = dataObjects.back();
		dobj->setName(Name("/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/desktop/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07/%00%00"));
		boost::shared_ptr<ndn::Interest> i;
		EXPECT_ANY_THROW(slot.segmentReceived(boost::make_shared<WireSegment>(dobj, i)));
	}

	{ // add parity data
		std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07";
		std::string parityName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07/_parity/%00%00";
		std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
		std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size(), 0, 1);
		BufferSlot slot;

		slot.segmentsRequested(makeInterestsConst(interests));
		ASSERT_EQ(BufferSlot::New, slot.getState());
		boost::shared_ptr<Data> dobj = dataObjects.back();
		EXPECT_NO_THROW(slot.segmentReceived(boost::make_shared<WireSegment>(dobj, interests.back())));

		dobj->setName(Name(parityName));
		EXPECT_NO_THROW(slot.segmentReceived(boost::make_shared<WireSegment>(dobj, interests.back())));
	}
}

TEST(TestBufferSlot, TestMissingSegments)
{
    std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07";
    VideoFramePacket vp = getVideoFramePacket(30000);
    std::vector<VideoFrameSegment> segments = sliceFrame(vp);
    boost::shared_ptr<ndnrtc::NetworkData> parityData;
    std::vector<ndnrtc::VideoFrameSegment> paritySegments = sliceParity(vp, parityData);

    { // all data arrived in random order
        std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
        std::vector<boost::shared_ptr<ndn::Data>> parityObjects = dataFromParitySegments(frameName, paritySegments);
        std::vector<boost::shared_ptr<Interest>> allinterests = getInterests(frameName, 0, dataObjects.size(), 0, parityObjects.size());
        std::vector<boost::shared_ptr<Interest>> dataInterests, parityInterests;

        std::copy(allinterests.begin(), allinterests.end()-parityObjects.size(), std::back_inserter(dataInterests));
        std::copy(allinterests.end()-parityObjects.size(), allinterests.end(), std::back_inserter(parityInterests));

        BufferSlot slot;

        {
            std::vector<boost::shared_ptr<const Interest>> first(dataInterests.begin(), dataInterests.end()-3);
            std::vector<boost::shared_ptr<const Interest>> second(dataInterests.end()-3, dataInterests.end());

            slot.segmentsRequested(first);
            boost::shared_ptr<WireSegment> wd(boost::make_shared<WireSegment>(dataObjects.front(), dataInterests.front()));

            EXPECT_NO_THROW(slot.segmentReceived(wd));

            std::vector<ndn::Name> missing = slot.getMissingSegments();
            EXPECT_EQ(missing.size(), second.size());

            for (auto& i:second)
            {
                EXPECT_NE(std::find(missing.begin(), missing.end(), i->getName()), missing.end());
                missing.erase(std::find(missing.begin(), missing.end(), i->getName()));
            }
            slot.segmentsRequested(second);

            EXPECT_EQ(slot.getMissingSegments().size(), 0);
        }
        {
            std::vector<boost::shared_ptr<const Interest>> first(parityInterests.begin(), parityInterests.end()-2);
            std::vector<boost::shared_ptr<const Interest>> second(parityInterests.end()-2, parityInterests.end());

            slot.segmentsRequested(first);
            boost::shared_ptr<WireSegment> wd(boost::make_shared<WireSegment>(parityObjects.front(), parityInterests.front()));

            EXPECT_NO_THROW(slot.segmentReceived(wd));

            std::vector<ndn::Name> missing = slot.getMissingSegments();
            EXPECT_EQ(missing.size(), second.size());

            for (auto& i:second)
            {
                EXPECT_NE(std::find(missing.begin(), missing.end(), i->getName()), missing.end());
                missing.erase(std::find(missing.begin(), missing.end(), i->getName()));
            }
            slot.segmentsRequested(second);

            EXPECT_EQ(slot.getMissingSegments().size(), 0);
        }
    }
}

TEST(TestBufferSlot, TestReuseSlot)
{
	BufferSlot slot;

	for (int i = 0; i < 3; ++i)
	{ // all data arrived in random order

		EXPECT_EQ(BufferSlot::Free, slot.getState());
		EXPECT_EQ(SampleClass::Unknown, slot.getNameInfo().class_);
		EXPECT_EQ(0, slot.getAssembledLevel());
		EXPECT_EQ(Name(), slot.getPrefix());
		EXPECT_EQ(BufferSlot::Inconsistent, slot.getConsistencyState());
		EXPECT_EQ(0, slot.getRtxNum());
		EXPECT_EQ(0, slot.getAssemblingTime());
		EXPECT_EQ(0, slot.getShortestDrd());
		EXPECT_EQ(0, slot.getLongestDrd());
		EXPECT_FALSE(slot.hasOriginalSegments());

		std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%07";
		VideoFramePacket vp = getVideoFramePacket();
		std::vector<VideoFrameSegment> segments = sliceFrame(vp);
		std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
		std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size());

		slot.segmentsRequested(makeInterestsConst(interests));
		ASSERT_EQ(BufferSlot::New, slot.getState());

		std::random_shuffle(dataObjects.begin(), dataObjects.end());

		int idx = 0;
		for (auto d:dataObjects)
		{
			boost::shared_ptr<WireSegment> wd(boost::make_shared<WireSegment>(d, interests[idx]));
			BufferSlot::State state;

			if (idx == 0) EXPECT_TRUE(slot.getConsistencyState() == BufferSlot::Inconsistent);

			EXPECT_NO_THROW(slot.segmentReceived(wd));

			if (wd->getSampleNo() == 0)
				EXPECT_TRUE(slot.getConsistencyState()&BufferSlot::HeaderMeta);
			else
				EXPECT_TRUE(slot.getConsistencyState()&BufferSlot::SegmentMeta);

			if (++idx < dataObjects.size())
            {
				EXPECT_EQ(BufferSlot::Assembling, slot.getState());
                EXPECT_ANY_THROW(slot.toggleLock());
            }
			else
				EXPECT_EQ(BufferSlot::Ready, slot.getState());

			EXPECT_EQ(round((double)idx/(double)dataObjects.size()*100)/100,
				round(slot.getAssembledLevel()*100)/100);
			EXPECT_LT(0, slot.getShortestDrd());
			if (idx < dataObjects.size())
			{
				EXPECT_EQ(0, slot.getAssemblingTime());
				EXPECT_EQ(0, slot.getLongestDrd());
			}
		}
		EXPECT_LT(0, slot.getAssemblingTime());
		EXPECT_LT(0, slot.getLongestDrd());
		EXPECT_EQ(slot.getConsistencyState(), BufferSlot::Consistent);

        EXPECT_NO_THROW(slot.toggleLock());
        EXPECT_EQ(BufferSlot::Locked, slot.getState());

		slot.clear();
	}
}

TEST(TestVideoFrameSlot, TestAsembleVideoFrame)
{
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07";
	VideoFramePacket vp = getVideoFramePacket();

	std::vector<VideoFrameSegment> segments = sliceFrame(vp, 734, 1249);

	// all data arrived in random order
	std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
	std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size());
	BufferSlot slot;

	slot.segmentsRequested(makeInterestsConst(interests));
	ASSERT_EQ(BufferSlot::New, slot.getState());

	std::random_shuffle(dataObjects.begin(), dataObjects.end());

	int idx = 0;
	for (auto d:dataObjects)
	{
		boost::shared_ptr<WireData<VideoFrameSegmentHeader>> wd(boost::make_shared<WireData<VideoFrameSegmentHeader>>(d, interests[idx]));
		BufferSlot::State state;

		ASSERT_NO_THROW(slot.segmentReceived(wd));
		idx++;
	}

	VideoFrameSlot videoSlot;
	bool recovered = false;
	boost::shared_ptr<ImmutableVideoFramePacket> videoPacket = videoSlot.readPacket(slot, recovered);

	ASSERT_TRUE(videoPacket.get());
	EXPECT_FALSE(recovered);
	EXPECT_TRUE(checkVideoFrame(videoPacket->getFrame()));
	EXPECT_EQ(734, videoSlot.readSegmentHeader(slot).playbackNo_);
	EXPECT_EQ(1249, videoSlot.readSegmentHeader(slot).pairedSequenceNo_);
}

TEST(TestVideoFrameSlot, TestFailedAssembleNotEnoughData)
{
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07";
	VideoFramePacket vp = getVideoFramePacket();

	std::vector<VideoFrameSegment> segments = sliceFrame(vp);

	// all data arrived in random order
	std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
	std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size());
	BufferSlot slot;

	slot.segmentsRequested(makeInterestsConst(interests));
	ASSERT_EQ(BufferSlot::New, slot.getState());

	std::random_shuffle(dataObjects.begin(), dataObjects.end());

	int idx = 0;
	for (auto d:dataObjects)
	{
		boost::shared_ptr<WireData<VideoFrameSegmentHeader>> wd(boost::make_shared<WireData<VideoFrameSegmentHeader>>(d, interests[idx]));
		ASSERT_NO_THROW(slot.segmentReceived(wd));
		if (idx++ == 3) break;
	}

	VideoFrameSlot videoSlot;
	bool recovered = false;
	boost::shared_ptr<ImmutableVideoFramePacket> videoPacket = videoSlot.readPacket(slot, recovered);

	EXPECT_FALSE(recovered);
	EXPECT_FALSE(videoPacket.get());
}

TEST(TestVideoFrameSlot, TestAssembleVideoFrameRecover)
{
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07";
	VideoFramePacket vp = getVideoFramePacket(10000);

	boost::shared_ptr<NetworkData> parity;
	std::vector<VideoFrameSegment> segments = sliceFrame(vp);
	std::vector<VideoFrameSegment> paritySegments = sliceParity(vp, parity);

	// all data arrived in random order
	std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
	std::vector<boost::shared_ptr<ndn::Data>> parityObjects = dataFromParitySegments(frameName, paritySegments);
	std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size());
	std::vector<boost::shared_ptr<Interest>> parityInterests = getInterests(frameName+"/_parity", 0, parityObjects.size());
	BufferSlot slot;

	slot.segmentsRequested(makeInterestsConst(interests));
	slot.segmentsRequested(makeInterestsConst(parityInterests));
	ASSERT_EQ(BufferSlot::New, slot.getState());

	std::random_shuffle(dataObjects.begin(), dataObjects.end());
	std::random_shuffle(parityObjects.begin(), parityObjects.end());

	int idx = 0;
	for (auto d:dataObjects)
	{
		boost::shared_ptr<WireData<VideoFrameSegmentHeader>> wd(boost::make_shared<WireData<VideoFrameSegmentHeader>>(d, interests[idx]));
		BufferSlot::State state;

		ASSERT_TRUE(wd->isValid());
		ASSERT_NO_THROW(slot.segmentReceived(wd));
		if (++idx == dataObjects.size()-1) break;
	}

	idx = 0;
	for (auto p:parityObjects)
	{
		boost::shared_ptr<WireData<VideoFrameSegmentHeader>> wd(boost::make_shared<WireData<VideoFrameSegmentHeader>>(p, parityInterests[idx]));
		ASSERT_TRUE(wd->isValid());
		ASSERT_NO_THROW(slot.segmentReceived(wd));
		if (slot.getAssembledLevel() > 1) break;
		idx++;
	}

	EXPECT_LT(1, slot.getAssembledLevel());

	VideoFrameSlot videoSlot;
	bool recovered = false;
	boost::shared_ptr<ImmutableVideoFramePacket> videoPacket = videoSlot.readPacket(slot, recovered);

	EXPECT_TRUE(recovered);
	EXPECT_TRUE(videoPacket.get());
}

TEST(TestVideoFrameSlot, TestAssembleVideoFrameRecover2)
{
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d/%FE%07";
	VideoFramePacket vp = getVideoFramePacket(20000);

	boost::shared_ptr<NetworkData> parity;
	std::vector<VideoFrameSegment> segments = sliceFrame(vp);
	std::vector<VideoFrameSegment> paritySegments = sliceParity(vp, parity);

	// all data arrived in random order
	std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(frameName, segments);
	std::vector<boost::shared_ptr<ndn::Data>> parityObjects = dataFromParitySegments(frameName, paritySegments);
	std::vector<boost::shared_ptr<Interest>> interests = getInterests(frameName, 0, dataObjects.size(), 0, parityObjects.size());
	std::vector<boost::shared_ptr<Interest>> parityInterests(interests.end()-parityObjects.size(), interests.end());
	BufferSlot slot;

	slot.segmentsRequested(makeInterestsConst(interests));
	slot.segmentsRequested(makeInterestsConst(parityInterests));
	ASSERT_EQ(BufferSlot::New, slot.getState());

	std::random_shuffle(dataObjects.begin(), dataObjects.end());
	std::random_shuffle(parityObjects.begin(), parityObjects.end());

	EXPECT_EQ(0, slot.getAssembledLevel());

	int idx = 0;
	for (auto p:parityObjects)
	{
		boost::shared_ptr<WireData<VideoFrameSegmentHeader>> wd(
            boost::make_shared<WireData<VideoFrameSegmentHeader>>(p, parityInterests[idx]));
		ASSERT_TRUE(wd->isValid());
		ASSERT_NO_THROW(slot.segmentReceived(wd));
		idx++;
	}

	idx = 0;
	for (auto d:dataObjects)
	{
		boost::shared_ptr<WireData<VideoFrameSegmentHeader>> wd(
            boost::make_shared<WireData<VideoFrameSegmentHeader>>(d, interests[idx]));
		BufferSlot::State state;

		ASSERT_NO_THROW(slot.segmentReceived(wd));
		if (++idx == dataObjects.size()-parityObjects.size()/2) break;
	}

	EXPECT_LT(1, slot.getAssembledLevel());

	VideoFrameSlot videoSlot;
	bool recovered = false;
	boost::shared_ptr<ImmutableVideoFramePacket> videoPacket = videoSlot.readPacket(slot, recovered);

	EXPECT_TRUE(recovered);
	EXPECT_TRUE(videoPacket.get());
}

TEST(TestAudioBundleSlot, TestAssembleAudioBundle)
{
    int data_len = 247;
    std::vector<uint8_t> rtpData;
    for (int i = 0; i < data_len; ++i)
        rtpData.push_back((uint8_t)i);

    int wire_len = 1000;
    AudioBundlePacket bundlePacket(wire_len);
    AudioBundlePacket::AudioSampleBlob sample({false}, rtpData.begin(), rtpData.end());

    while (bundlePacket.hasSpace(sample))
        bundlePacket << sample;

    CommonHeader hdr;
    hdr.sampleRate_ = 24.7;
    hdr.publishTimestampMs_ = 488589553;
    hdr.publishUnixTimestamp_ = 1460488589;

    bundlePacket.setHeader(hdr);

    ASSERT_EQ(AudioBundlePacket::wireLength(wire_len, data_len)/AudioBundlePacket::AudioSampleBlob::wireLength(data_len),
        bundlePacket.getSamplesNum());

    std::vector<CommonSegment> segments = CommonSegment::slice(bundlePacket, wire_len);
    ASSERT_EQ(1, segments.size());

    std::string frameName = "/ndn/edu/ucla/remap/ndncon/instance1/ndnrtc/%FD%03/audio/mic/%FC%00%00%01c_%27%DE%D6/hd/%FE%00";
    ndn::Name n(frameName);
    n.appendSegment(0);
    boost::shared_ptr<ndn::Data> ds(boost::make_shared<ndn::Data>(n));
    ds->getMetaInfo().setFinalBlockId(ndn::Name::Component::fromNumber(0));
    ds->setContent(segments.front().getNetworkData()->data());

	std::vector<boost::shared_ptr<Interest>> interests;
	boost::shared_ptr<Interest> i(boost::make_shared<Interest>(Name(frameName).appendSegment(0), 1000));
	int nonce = 0x1234;
	i->setNonce(ndn::Blob((uint8_t*)&nonce, sizeof(nonce)));
	interests.push_back(i);

	boost::shared_ptr<WireData<DataSegmentHeader>> wd(new WireData<DataSegmentHeader>(ds, interests.front()));

    BufferSlot slot;
    slot.segmentsRequested(makeInterestsConst(interests));
    slot.segmentReceived(wd);

    AudioBundleSlot bundleSlot;
    boost::shared_ptr<ImmutableAudioBundlePacket> p = bundleSlot.readBundle(slot);
    ASSERT_TRUE(p.get());
    EXPECT_EQ(bundlePacket.getSamplesNum(), p->getSamplesNum());

    for (int i = 0; i < p->getSamplesNum(); ++i)
    {
    	bool identical = true;
    	for (int j = 0; j < data_len; ++j)
    		identical &= (rtpData[j] == (*p)[i].data()[j]);
    	EXPECT_TRUE(identical);
    }
}

TEST(TestSlotPool, TestPopPush)
{
	SlotPool pool(10);

	for (int i = 0; i < 10; ++i)
		boost::shared_ptr<BufferSlot> slot = pool.pop();
	EXPECT_FALSE(pool.pop().get());
	EXPECT_EQ(0, pool.size());
	EXPECT_EQ(10, pool.capacity());

	for (int i = 0; i < 10; ++i)
		EXPECT_TRUE(pool.push(boost::make_shared<BufferSlot>()));

	EXPECT_FALSE(pool.push(boost::make_shared<BufferSlot>()));
}

TEST(TestBuffer, TestRequestAndReceive)
{
	std::srand(std::time(0));
	size_t poolSize = 50;
	int n = poolSize+10;
	std::string frameName = "/ndn/edu/ucla/remap/peter/ndncon/instance1/ndnrtc/%FD%03/video/camera/%FC%00%00%01c_%27%DE%D6/hi/d";
    boost::shared_ptr<StatisticsStorage> storage(StatisticsStorage::createConsumerStatistics());
	boost::shared_ptr<SlotPool> pool(boost::make_shared<SlotPool>(poolSize));
	MockBufferObserver observer1, observer2;
	Buffer buffer(storage, pool);

	buffer.attach(&observer1);
	buffer.attach(&observer2);

	for (int i = 0; i < n; ++i)
	{
		std::vector<boost::shared_ptr<const Interest>> interests;
		int nInterests = std::rand()%30+10;
		for (int j = 0; j < nInterests; ++j)
		{
			boost::shared_ptr<Interest> interest(boost::make_shared<Interest>(Name(frameName).appendSequenceNumber(i).appendSegment(j), 1000));
			int nonce = 0x1234+i*10+j;
			interest->setNonce(Blob((uint8_t*)&nonce, sizeof(int)));
			interests.push_back(interest);
		}

		if (i < poolSize)
		{
			EXPECT_CALL(observer1, onNewRequest(_))
				.Times(1);
			EXPECT_CALL(observer2, onNewRequest(_))
				.Times(1);

			EXPECT_TRUE(buffer.requested(interests));
			EXPECT_EQ(i+1, buffer.getSlotsNum(Name(frameName), BufferSlot::New));
		}
		else
		{
			EXPECT_CALL(observer1, onNewRequest(_))
				.Times(0);
			EXPECT_CALL(observer2, onNewRequest(_))
				.Times(0);
			EXPECT_FALSE(buffer.requested(interests));
		}
	}

	for (int i = 0; i < poolSize; ++i)
	{
		VideoFramePacket vp = getVideoFramePacket();
		std::vector<VideoFrameSegment> segments = sliceFrame(vp);

		Name n(frameName);
		n.appendSequenceNumber(i);
		std::vector<boost::shared_ptr<ndn::Data>> dataObjects = dataFromSegments(n.toUri(), segments);

		std::random_shuffle(dataObjects.begin(), dataObjects.end());

		int idx = 0;
		for (auto d:dataObjects)
		{
			boost::function<void(const BufferReceipt&)> checkFrame = [](const BufferReceipt& r){
				VideoFrameSlot vs;
				bool recovered = false;
				if (r.slot_->getState() == BufferSlot::Ready)
					EXPECT_TRUE(vs.readPacket(*(r.slot_), recovered).get());
			};

			boost::shared_ptr<ndn::Interest> interest(boost::make_shared<ndn::Interest>(n,1000));
			int nonce = 0;
			interest->setNonce(Blob((uint8_t*)&(nonce), sizeof(int)));

			boost::shared_ptr<WireData<VideoFrameSegmentHeader>> wd(boost::make_shared<WireData<VideoFrameSegmentHeader>>(d, interest));
			EXPECT_CALL(observer1, onNewData(_))
				.Times(1);
			EXPECT_CALL(observer2, onNewData(_))
				.Times(1)
				.WillOnce(Invoke(checkFrame));
			BufferReceipt rcpt = buffer.received(wd);
			idx++;
			if (idx == dataObjects.size())
				EXPECT_EQ(BufferSlot::Ready, rcpt.slot_->getState());
			else
				EXPECT_EQ(1, buffer.getSlotsNum(Name(frameName), BufferSlot::Assembling));
		}

		EXPECT_EQ(i+1, buffer.getSlotsNum(Name(frameName), BufferSlot::Ready));
		EXPECT_EQ(poolSize-i-1, buffer.getSlotsNum(Name(frameName), BufferSlot::New));
	}

    EXPECT_EQ(poolSize, (*storage)[Indicator::AssembledNum]);
}

//******************************************************************************
int main(int argc, char **argv) {
	::testing::InitGoogleTest(&argc, argv);
	return RUN_ALL_TESTS();
}


text:
require 'sensu-plugin/metric/cli'
require 'net/http'
require 'net/https'
require 'json'
require 'uri'

class SpringBootMetrics < Sensu::Plugin::Metric::CLI::Graphite
  option :url,
         short: '-u URL',
         long: '--url URL',
         description: 'The url for your app metrics',
         required: false

  option :host,
         short: '-h HOST',
         long: '--host HOST',
         description: 'Your spring boot actuator endpoint',
         required: false,
         default: 'localhost'

  option :port,
         short: '-P PORT',
         long: '--port PORT',
         description: 'Your app port',
         required: false,
         default: 8080

  option :path,
         short: '-e PATH',
         long: '--path PATH',
         description: 'Metrics endpoint path',
         required: false,
         default: '/metrics'

  option :protocol,
         short: '-l PROTO',
         long: '--protocol PROTO',
         description: 'The protocol used to make requests',
         in:  %w(http https),
         default: 'http'

  option :insecure,
         short: '-k',
         long: '--insecure',
         description: 'Insecure SSL Certificate',
         boolean: true,
         default: false

  option :username,
         short: '-u USERNAME',
         long: '--username USERNAME',
         description: 'Your app username',
         required: false

  option :password,
         short: '-p PASSWORD',
         long: '--password PASSWORD',
         description: 'Your app password',
         required: false

  option :scheme,
         description: 'Metric naming scheme, text to prepend to metric',
         short: '-s SCHEME',
         long: '--scheme SCHEME',
         required: true,
         default: "#{Socket.gethostname}.springboot_metrics"

  option :counters,
         description: 'Include counters',
         short: '-c',
         long: '--counters',
         boolean: true,
         default: false

  option :gauges,
         description: 'Include gauges',
         short: '-g',
         long: '--gauges',
         boolean: true,
         default: false

  def json_valid?(str)
    JSON.parse(str)
    return true
  rescue JSON::ParserError
    return false
  end

  def run
    unless config[:url]
      config[:url] = "#{config[:protocol]}://#{config[:host]}:#{config[:port]}#{config[:path]}"
    end

    uri = URI.parse(config[:url])

    verify_mode = config[:insecure] ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER

    begin
      res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', verify_mode: verify_mode) do |http|
        req = Net::HTTP::Get.new(uri.path)
        if config[:username] && config[:password]
          req.basic_auth(config[:username], config[:password])
        end
        http.request(req)
      end
    rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET,
           EOFError, Net::HTTPBadResponse,
           Net::HTTPHeaderSyntaxError, Net::ProtocolError,
           Errno::ECONNREFUSED => e
      critical e
    end

    if json_valid?(res.body)
      json = JSON.parse(res.body)
      json.each do |key, val|
        if key.to_s =~ /^counter\.(.+)/
          output(config[:scheme] + '.' + key, val) if config[:counters]
        elsif key.to_s =~ /^gauge\.(.+)/
          output(config[:scheme] + '.' + key, val) if config[:gauges]
        else
          output(config[:scheme] + '.' + key, val)
        end
      end
    else
      critical 'Response contains invalid JSON'
    end

    ok
  end
end

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>Predef: include/Predef/Version.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Predef

Predefined macros for compiler, OS, architecture, language, and standards.

Main Page

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

Version.h

Go to the documentation of this file.

    1

   22

   23 /*

   24 Copyright Rene Rivera 2014

   25 Distributed under the Boost Software License, Version 1.0.

   26 (See accompanying file LICENSE_1_0.txt or copy at

   27 http://www.boost.org/LICENSE_1_0.txt)

   28 */

   29

   38 #ifndef PREDEF_VERSION_H

   39 #define PREDEF_VERSION_H

   40

   41 #include "../VersionNumber.h"

   42

   44 #define PREDEF_VERSION_MAJOR 0

   45 #define PREDEF_VERSION_MINOR 1

   47 #define PREDEF_VERSION_PATCH 0

   49

   51 #define PREDEF_VERSION PREDEF_VERSION_NUMBER( PREDEF_VERSION_MAJOR, PREDEF_VERSION_MINOR, PREDEF_VERSION_PATCH )

   52

   53 #endif // PREDEF_VERSION_H

include

Predef

Version.h

Generated on Fri Apr 24 2015 23:34:09 for Predef by

     1.8.9.1


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace EdityMcEditface.HtmlRenderer.Filesystem
{
    public class FileStreamManager : IFileStreamManager
    {
        /// <summary>
        /// Open a read stream. If you need to customize the stream
        /// to read from, override this function. The default returns the file directly
        /// from the file system.
        /// This function does not chain.
        /// </summary>
        /// <param name="file">The original requested path to the file.</param>
        /// <param name="physicalFile">The path to the file on the physical drive.</param>
        /// <returns></returns>
        public virtual Stream OpenReadStream(String file, String physicalFile)
        {
            return File.Open(physicalFile, FileMode.Open, FileAccess.Read, FileShare.Read);
        }

        /// <summary>
        /// Copy a file from source to dest.
        /// </summary>
        /// <param name="source"></param>
        /// <param name="physicalSource"></param>
        /// <param name="physicalDest"></param>
        public virtual void CopyFile(String source, String physicalSource, String physicalDest)
        {
            File.Copy(physicalSource, physicalDest);
        }
    }
}


text:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Catch : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = Context.Items["test"].ToString();
    }
}


text:
package loon.action.camera;

import loon.LSystem;
import loon.geom.Matrix4;

public class EmptyCamera extends BaseCamera {

	protected Matrix4 _projMatrix4;

	protected Matrix4 _viewMatrix4;

	public EmptyCamera() {
		this(LSystem.viewSize.getMatrix().cpy(), new Matrix4());
	}

	public EmptyCamera(Matrix4 p, Matrix4 v) {
		_projMatrix4 = p;
		_viewMatrix4 = v;
	}

	@Override
	public Matrix4 getView() {
		return _viewMatrix4;
	}

	@Override
	public Matrix4 getProjection() {
		return _projMatrix4;
	}

	@Override
	public Matrix4 getCombine() {
		return _projMatrix4.mul(_viewMatrix4);
	}

}


text:
package play.api.libs.streams

import org.specs2.mutable._

import scala.concurrent.duration.Duration
import scala.concurrent.duration.SECONDS
import scala.concurrent.Await
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import scala.language.reflectiveCalls
import scala.util.Try

class ExecutionSpec extends Specification {
  import Execution.trampoline

  val waitTime = Duration(5, SECONDS)

  "trampoline" should {
    "execute code in the same thread" in {
      val f = Future(Thread.currentThread())(trampoline)
      Await.result(f, waitTime) must equalTo(Thread.currentThread())
    }

    "not overflow the stack" in {
      def executeRecursively(ec: ExecutionContext, times: Int): Unit = {
        if (times > 0) {
          ec.execute(() => executeRecursively(ec, times - 1))
        }
      }

      // Work out how deep to go to cause an overflow
      val overflowingExecutionContext = new ExecutionContext {
        def execute(runnable: Runnable): Unit = {
          runnable.run()
        }
        def reportFailure(t: Throwable): Unit = t.printStackTrace()
      }

      var overflowTimes = 1 << 10
      try {
        while (overflowTimes > 0) {
          executeRecursively(overflowingExecutionContext, overflowTimes)
          overflowTimes = overflowTimes << 1
        }
        sys.error("Can't get the stack to overflow")
      } catch {
        case _: StackOverflowError => ()
      }

      // Now verify that we don't overflow
      Try(executeRecursively(trampoline, overflowTimes)) must beSuccessfulTry[Unit]
    }

    "execute code in the order it was submitted" in {
      val runRecord = scala.collection.mutable.Buffer.empty[Int]
      case class TestRunnable(id: Int, children: Runnable*) extends Runnable {
        def run(): Unit = {
          runRecord += id
          for (c <- children) trampoline.execute(c)
        }
      }

      trampoline.execute(
        TestRunnable(
          0,
          TestRunnable(1),
          TestRunnable(2, TestRunnable(4, TestRunnable(6), TestRunnable(7)), TestRunnable(5, TestRunnable(8))),
          TestRunnable(3)
        )
      )

      runRecord must equalTo(0 to 8)
    }
  }
}


text:
<!DOCTYPE html>

	<meta name="description" content="Aurora console website" />
	<meta name="keywords" content="open-source, programming, electronic, embedded, games, aurora, console, retrogaming, dspic, scart" />
	<meta name="author" content="Fr&eacuted&eacuteric Meslin" />
	<meta name="robots" content="noindex, nofollow" />
	<meta name="revisit-after" content="3 month" />
	<link rel="icon" type="image/png" href="../favicon.png">
	<title>Aurora SDK</title>
	<link rel='stylesheet' href='../css/style.css' />

				Home

				Get started

				Hardware

				Software

        Tools

				FAQ

				Contact

Video

Audio

Gamepads

USB

Bluetooth

Internal flash

External flash

Aurora software: Bluetooth library

	This website regroups all documents you need to start developing games for Aurora.

General routines:

    void blueInit()
    Initialise serial over Bluetooth peripheral.

    void blueConfigure()
    Set default Bluetooth configuration (not mandatory). It configures:

Device name to: Aurora-SERIAL_NUMBER

Device password to: 1234

Baudrate to: 230400 bauds

    Warning: a couple of seconds are needed to change bluetooth configuration.

Configuration routines:

    void blueSetMode(int mode)

int mode

Bluetooth operating mode

Communication (BLUE_MODE_COM) or configuration (BLUE_MODE_AT)

    Set the operating mode.

    void blueSetRole(int role)

int role

Bluetooth communication role

Slave (BLUE_ROLE_SLAVE) or master(BLUE_ROLE_MASTER)

    Set the communication role. Bluetooth must be in configuration (AT) mode.

    void blueSetName(const char * name)

const char * name

Device name (null-terminated string)

    Set the device name. Bluetooth must be in configuration (AT) mode.

    void blueSetPassword(const char * pass)

const char * pass

Device password (null-terminated string)

A string made of four consecutive figures

    Set the device password. Bluetooth must be in configuration (AT) mode.

    void blueSetRate(int baudrate)

int baud

Serial baudrate

    Set the communication baudrate.

Communication routines:

    int blueRead(void * buffer, int size)

void * buffer

pointer to a receive buffer

int size

size of buffer in bytes

return

quantity of data read in bytes

    Read data from the Bluetooth receive FIFO.

    int blueWrite(const void * buffer, int size)

const void * buffer

pointer to a transmit buffer

int size

size of buffer in bytes

return

quantity of data written in bytes

    Write data to the Bluetooth transmit FIFO.

    int blueWriteString(const char * string)

const char * string

pointer to a null-terminated string

return

number of character written

    Write a string to the Bluetooth transmit FIFO.

Debugging support:

    void blueSetDebug(int enable)

int enable

enable debugging

    Enable debugging support for development tools.

	Follow @MarzacDev


text:
<?php

namespace App\Http\Controllers;

class CheckoutControllerTest extends \TestCase
{
    use \UsesCart;

    /** @test **/
    public function it_shows_the_checkout_page()
    {
        $product = $this->putProductInCart();
        $this->visit('checkout')
             ->see($product->name);
    }
}


text:
[![Build Status](https://travis-ci.org/mmllr/MMLayerAccessibility.png?branch=master)](https://travis-ci.org/mmllr/MMLayerAccessibility)  [![Coverage Status](https://coveralls.io/repos/mmllr/MMLayerAccessibility/badge.png)](https://coveralls.io/r/mmllr/MMLayerAccessibility)

Sometimes you need to build a user interface in a custom view from CoreAnimation layers. Unfortunately they don't support NSAccessibility and renders the UI useless for your disabled users.

So I developed a solution which adds NSAccessibility support to CALayer and all its subclasses (via a category) and provides an easy to use, block based API:

```objective-c
-(void)setReadableAccessibilityAttribute:(NSString*)attribute withBlock:(id(^)(void))handler;

	CATextLayer *layer...
	__weak CATextLayer *weakLayer = layer;

	[layer setReadableAccessibilityAttribute:NSAccessibilityTitleAttribute
							   withBlock:^id{
									CATextLayer *strongLayer = weakLayer;
									return strongLayer.string;
									}];
```
With this method you set an accessibility attribute to a CALayer, the handler block must return a value specific for the attribute (such as a NSString, NSValue, NSArray...see the [NSAccessibility Documentation](https://developer.apple.com/librarY/mac/documentation/Cocoa/Conceptual/Accessibility/cocoaAXIntro/cocoaAXintro.html) on Apples developer website.

```objective-c
-(void)setWritableAccessibilityAttribute:(NSString*)attribute readBlock:(id(^)(void))getter writeBlock:(void(^)(id value))setter;

	CATextLayer *layer = ...*
	[layer setWritableAccessibilityAttribute:NSAccessibilityTitleAttribute readBlock:^id{
		return weakLayer.string;
		} writeBlock:^(NSString *value) {
		weakLayer.string = value;
	}];
```
This method will provide a settable attribute to the CALayer. Because every settable attribute needs to be readable, too, you must provide a getter block.
```objective-c
-(void)setParameterizedAccessibilityAttribute:(NSString*)parameterizedAttribute withBlock:(id(^)(id))handler;

	[layer setParameterizedAccessibilityAttribute:NSAccessibilityLineForIndexParameterizedAttribute
										withBlock:^id(id param) {
											return @0;
										}];
```
Same principle here, you provide a block, which will be invoked when the system ax-service asks the layer for a parameterized accessibility value (such as the current cursor position in a text field).

```objective-c
-(void)setAccessibilityAction:(NSString*)actionName withBlock:(void(^)(void))handler

	[layer setAccessibilityAction:NSAccessibilityPressAction
						withBlock:^{
							NSLog(@"action pressed");
						}];
```
Since the handler blocks are stored on the individual layers, you need to be careful to avoid retain-cycles, when you back reference the layer in these blocks. Always use a weak self reference inside the block and transform it back to a strong reference in the block.

For a detailed example how to use the library, have a look in the LayerView class.

Since the library implements a lot of default NSAccessibility attributes, you only need to provide the attributes which are specific to your UI. The build in attributes are the following:

**NSAccessibilityRoleAttribute**
**NSAccessibilityParentAttribute**
**NSAccessibilitySizeAttribute**
**NSAccessibilityPositionAttribute**
**NSAccessibilityWindowAttribute**
**NSAccessibilityTopLevelUIElementAttribute**
**NSAccessibilityRoleDescriptionAttribute**
**NSAccessibilityEnabledAttribute**
**NSAccessibilityFocusedAttribute**

The default value for **NSAccessibilityRoleAttribute** is **NSAccessibilityUnknownRole**, so you should provide your own handler which returns a more specific role, such as NSAccessibilityButtonRole or NSAccessibilityTextFieldRole. See the sample project for details.

Every layer without at least one user defined handler is ignored per default. To provide the default handlers for the layers size, position, parent etc, it is needed to call one additional method in your custom NSView when you set the views layer:
```objective-c
 	CALayer *layer = [self createBackgroundLayer];
	[self setAccessiblityEnabledLayer:layer];
```

Then you need to implement only two stub methods from the NSAccessibility protocol in your custom view:
```objective-c
	-(NSArray*)accessibilityAttributeNames
	{
		static NSMutableArray *attributes = nil;
		if (!attributes) {
			attributes = [[super accessibilityAttributeNames] mutableCopy];
			NSArray *appendedAttributes = @[NSAccessibilityChildrenAttribute];

			for (NSString *attribute in appendedAttributes) {
				if (![attributes containsObject:attributes]) {
					[attributes addObject:attribute];
				}
			}
		}
		return attributes;
	}

	-(id)accessibilityAttributeValue:(NSString *)attribute
	{
		if ([attribute isEqualToString:NSAccessibilityChildrenAttribute]) {
			return NSAccessibilityUnignoredChildren(@[self.layer]);
		}
		return [super accessibilityAttributeValue:attribute];
	}
```
Have a look in the LayerView class of the provided example.

The library is fully unit tested with [Kiwi](https://github.com/allending/Kiwi) specs.
## Usage

To run the example project; clone the repo, and run `pod install` from the Example directory first.
Then enable accessibility in system settings and start the accessibility inspector afterwards.
![Enable AX](https://raw.github.com/mmllr/MMLayerAccessibility/master/Resources/enableax.png)
![AX Inspector](https://raw.github.com/mmllr/MMLayerAccessibility/master/Resources/Xcode.png)
You can examine your CALayer based ui in the inspector.
![examine ui](https://raw.github.com/mmllr/MMLayerAccessibility/master/Resources/screenshot01.png)

## Requirements

Minimum requirements are Mac OSX 10.7 and ARC.

## Installation

MMLayerAccessibility is available through [CocoaPods](http://cocoapods.org), to install
it simply add the following line to your Podfile:

	pod "MMLayerAccessibility"

## Author

Markus Mueller, mmlr@gmx.net

## License

MMLayerAccessibility is available under the MIT license. See the LICENSE file for more info.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/title_red_bg" >

        <ImageButton
            android:id="@+id/btn_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="5dp"
            android:background="@null"
            android:src="@drawable/back" />

        <ImageButton
            android:id="@+id/btn_share"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="5dp"
            android:background="@null"
            android:src="@drawable/icon_share" />

        <ImageButton
            android:id="@+id/btn_size"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="5dp"
            android:layout_toLeftOf="@id/btn_share"
            android:background="@null"
            android:src="@drawable/icon_textsize" />
    </RelativeLayout>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >

        <WebView
            android:id="@+id/wv_web"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ProgressBar
            android:id="@+id/pb_progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:indeterminateDrawable="@drawable/custom_progress" />
    </FrameLayout>

</LinearLayout>


text:
package mesosphere.marathon.state

import scala.collection.JavaConverters._
import mesosphere.marathon.Protos
import org.apache.mesos.{ Protos => MesosProtos }

case class DiscoveryInfo(ports: Seq[DiscoveryInfo.Port] = Seq.empty) {
  def toProto: Protos.DiscoveryInfo = {
    Protos.DiscoveryInfo.newBuilder
      .addAllPorts(ports.map(_.toProto).asJava)
      .build
  }
}

object DiscoveryInfo {
  def empty: DiscoveryInfo = DiscoveryInfo()

  def fromProto(proto: Protos.DiscoveryInfo): DiscoveryInfo = {
    DiscoveryInfo(
      proto.getPortsList.asScala.map(Port.fromProto).toList
    )
  }

  case class Port(number: Int, name: String, protocol: String) {
    require(Port.AllowedProtocols(protocol), "protocol can only be 'tcp' or 'udp'")

    def toProto: MesosProtos.Port = {
      MesosProtos.Port.newBuilder
        .setNumber(number)
        .setName(name)
        .setProtocol(protocol)
        .build
    }
  }

  object Port {
    val AllowedProtocols: Set[String] = Set("tcp", "udp")

    def fromProto(proto: MesosProtos.Port): Port = {
      Port(
        number = proto.getNumber,
        name = proto.getName,
        protocol = proto.getProtocol
      )
    }
  }
}


text:
package com.sfl.pms.services.order.impl;

import com.sfl.pms.persistence.repositories.order.OrderRepository;
import com.sfl.pms.persistence.repositories.order.payment.OrderPaymentChannelRepository;
import com.sfl.pms.persistence.utility.PersistenceUtilityService;
import com.sfl.pms.services.customer.CustomerService;
import com.sfl.pms.services.customer.model.Customer;
import com.sfl.pms.services.order.dto.OrderDto;
import com.sfl.pms.services.order.dto.OrderStateChangeDto;
import com.sfl.pms.services.order.dto.OrderStateChangeHistoryRecordDto;
import com.sfl.pms.services.order.dto.payment.provider.OrderProviderPaymentChannelDto;
import com.sfl.pms.services.order.event.OrderPaidEvent;
import com.sfl.pms.services.order.event.OrderStateChangedEvent;
import com.sfl.pms.services.order.exception.OrderAlreadyExistsForUuIdException;
import com.sfl.pms.services.order.exception.OrderNotFoundForIdException;
import com.sfl.pms.services.order.exception.OrderNotFoundForUuIdException;
import com.sfl.pms.services.order.exception.payment.OrderAlreadyPaidException;
import com.sfl.pms.services.order.impl.payment.provider.OrderProviderPaymentChannelHandler;
import com.sfl.pms.services.order.model.Order;
import com.sfl.pms.services.order.model.OrderState;
import com.sfl.pms.services.order.model.OrderStateChangeHistoryRecord;
import com.sfl.pms.services.order.model.payment.OrderPaymentChannel;
import com.sfl.pms.services.order.model.payment.provider.OrderProviderPaymentChannel;
import com.sfl.pms.services.system.event.ApplicationEventDistributionService;
import com.sfl.pms.services.test.AbstractServicesUnitTest;
import org.apache.commons.lang3.SerializationUtils;
import org.easymock.EasyMock;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.Assert;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.Date;
import java.util.UUID;

import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;

/**
 * User: Ruben Dilanyan
 * Company: SFL LLC
 * Date: 11/12/14
 * Time: 12:51 PM
 */
public class OrderServiceImplTest extends AbstractServicesUnitTest {

    /* Test subject and mock */
    @TestSubject
    private OrderServiceImpl orderService = new OrderServiceImpl();

    @Mock
    private OrderRepository orderRepository;

    @Mock
    private CustomerService customerService;

    @Mock
    private OrderProviderPaymentChannelHandler orderProviderPaymentChannelHandler;

    @Mock
    private OrderPaymentChannelRepository orderPaymentChannelRepository;

    @Mock
    private PersistenceUtilityService persistenceUtilityService;

    @Mock
    private ApplicationEventDistributionService applicationEventDistributionService;

    /* Constructors */
    public OrderServiceImplTest() {
    }

    /* Test methods */
    @Test
    public void testCreateOrderWithInvalidArguments() {
        // Test data
        final Long customerId = 1L;
        final OrderDto orderDto = getServicesImplTestHelper().createOrderDto();
        // Reset
        resetAll();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.createOrder(null, orderDto);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        try {
            orderService.createOrder(customerId, null);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        try {
            orderService.createOrder(customerId, new OrderDto(null, orderDto.getPaymentTotalWithVat(), orderDto.getCurrency()));
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        try {
            orderService.createOrder(customerId, new OrderDto(orderDto.getUuId(), null, orderDto.getCurrency()));
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        try {
            orderService.createOrder(customerId, new OrderDto(orderDto.getUuId(), orderDto.getPaymentTotalWithVat(), null));
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testCreateOrderWithExistingUuId() {
        // Test data
        final Long customerId = 1L;
        final Customer customer = getServicesImplTestHelper().createCustomer();
        customer.setId(customerId);
        // Order
        final OrderDto orderDto = getServicesImplTestHelper().createOrderDto();
        final Long existingOrderId = 2L;
        final Order existingOrder = getServicesImplTestHelper().createOrder();
        existingOrder.setId(existingOrderId);
        // Reset
        resetAll();
        // Expectations
        expect(customerService.getCustomerById(eq(customerId))).andReturn(customer).once();
        expect(orderRepository.findByUuId(eq(orderDto.getUuId()))).andReturn(existingOrder).once();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.createOrder(customerId, orderDto);
            fail("Exception should be thrown");
        } catch (final OrderAlreadyExistsForUuIdException ex) {
            // Expected
            assertOrderAlreadyExistsForUuIdException(ex, existingOrderId, orderDto.getUuId());
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testCreateOrder() {
        // Test data
        final Long customerId = 1L;
        final Customer customer = getServicesImplTestHelper().createCustomer();
        customer.setId(customerId);
        // Order
        final OrderDto orderDto = getServicesImplTestHelper().createOrderDto();
        // Reset
        resetAll();
        // Expectations
        expect(customerService.getCustomerById(eq(customerId))).andReturn(customer).once();
        expect(orderRepository.findByUuId(eq(orderDto.getUuId()))).andReturn(null).once();
        expect(orderRepository.save(isA(Order.class))).andAnswer(() -> (Order) getCurrentArguments()[0]).once();
        // Replay
        replayAll();
        // Run test scenario
        final Order result = orderService.createOrder(customerId, orderDto);
        getServicesImplTestHelper().assertOrder(result, orderDto);
        assertNotNull(result.getCustomer());
        assertEquals(customer, result.getCustomer());
        // Verify
        verifyAll();
    }

    @Test
    public void testCheckIfOrdersIsPaidWithInvalidArguments() {
        // Reset
        resetAll();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.checkIfOrderIsPaid(null);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testCheckIfOrdersIsPaidWithNotExistingOrderId() {
        // Test data
        final Long orderId = 1L;
        // Reset
        resetAll();
        // Expectations
        expect(orderRepository.findOne(eq(orderId))).andReturn(null).once();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.checkIfOrderIsPaid(orderId);
            fail("Exception should be thrown");
        } catch (final OrderNotFoundForIdException ex) {
            // Expected
            assertOrderNotFoundForIdException(ex, orderId);
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testCheckIfOrdersIsPaidWhenItIsNotPaidYet() {
        // Test data
        final Long orderId = 1L;
        final Order order = getServicesImplTestHelper().createOrder();
        order.setId(orderId);
        // Reset
        resetAll();
        // Expectations
        expect(orderRepository.findOne(eq(orderId))).andReturn(order).once();
        expect(orderPaymentChannelRepository.findByOrder(eq(order))).andReturn(null).once();
        // Replay
        replayAll();
        // Run test scenario
        final boolean result = orderService.checkIfOrderIsPaid(orderId);
        assertFalse(result);
        // Verify
        verifyAll();
    }

    @Test
    public void testCheckIfOrdersIsPaidWhenItIsAlreadyPaid() {
        // Test data
        final Long orderId = 1L;
        final Order order = getServicesImplTestHelper().createOrder();
        order.setId(orderId);
        final Long orderPaymentChanelId = 2L;
        final OrderPaymentChannel orderPaymentChannel = getServicesImplTestHelper().createOrderProviderPaymentChannel();
        orderPaymentChannel.setId(orderPaymentChanelId);
        // Reset
        resetAll();
        // Expectations
        expect(orderRepository.findOne(eq(orderId))).andReturn(order).once();
        expect(orderPaymentChannelRepository.findByOrder(eq(order))).andReturn(orderPaymentChannel).once();
        // Replay
        replayAll();
        // Run test scenario
        final boolean result = orderService.checkIfOrderIsPaid(orderId);
        assertTrue(result);
        // Verify
        verifyAll();
    }

    @Test
    public void testGetTotalAmountOrderedForCustomerWithInvalidArguments() {
        // Reset
        resetAll();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.getTotalAmountOrderedForCustomer(null);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testGetTotalAmountOrderedForCustomer() {
        // Test data
        final Long customerId = 1L;
        final Customer customer = getServicesImplTestHelper().createCustomer();
        customer.setId(customerId);
        // Reset
        resetAll();
        // Expectations
        expect(customerService.getCustomerById(eq(customerId))).andReturn(customer).once();
        expect(orderRepository.getTotalAmountPaidForCustomer(eq(customerId))).andReturn(BigDecimal.ONE).once();
        // Replay
        replayAll();
        // Run test scenario
        final BigDecimal result = orderService.getTotalAmountOrderedForCustomer(customerId);
        assertEquals(result, BigDecimal.ONE);
        // Verify
        verifyAll();
    }

    @Test
    public void testGetOrdersCountForCustomerWithInvalidArguments() {
        // Reset
        resetAll();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.getOrdersCountForCustomer(null);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testGetOrdersCountForCustomer() {
        // Test data
        final Long customerId = 1L;
        final Customer customer = getServicesImplTestHelper().createCustomer();
        customer.setId(customerId);
        final Long ordersCount = 101L;
        // Reset
        resetAll();
        // Expectations
        expect(customerService.getCustomerById(eq(customerId))).andReturn(customer).once();
        expect(orderRepository.countByCustomer(eq(customer))).andReturn(ordersCount).once();
        // Replay
        replayAll();
        // Run test scenario
        final Long result = orderService.getOrdersCountForCustomer(customerId);
        assertEquals(ordersCount, result);
        // Verify
        verifyAll();
    }

    @Test
    public void testMarkOrderPaidWithInvalidArguments() {
        // Test data
        final Long orderId = 1L;
        final OrderProviderPaymentChannelDto orderProviderPaymentChannelDto = getServicesImplTestHelper().createOrderProviderPaymentChannelDto();
        // Reset
        resetAll();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.markOrderPaid(null, orderProviderPaymentChannelDto);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        try {
            orderService.markOrderPaid(orderId, null);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testMarkOrderPaidWithNotExistingOrderId() {
        // Test data
        final Long orderId = 1L;
        final OrderProviderPaymentChannelDto orderProviderPaymentChannelDto = getServicesImplTestHelper().createOrderProviderPaymentChannelDto();
        // Reset
        resetAll();
        // Expectations
        orderProviderPaymentChannelHandler.assertOrderPaymentChannel(eq(orderProviderPaymentChannelDto));
        expectLastCall();
        expect(orderRepository.findByIdWithWriteLockFlushedAndFreshData(eq(orderId))).andReturn(null).once();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.markOrderPaid(orderId, orderProviderPaymentChannelDto);
            fail("Exception should be thrown");
        } catch (final OrderNotFoundForIdException ex) {
            // Expected
            assertOrderNotFoundForIdException(ex, orderId);
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testMarkOrderPaidWhenPaymentChannelAlreadyExists() {
        // Test data
        final Long orderId = 1L;
        final Order order = getServicesImplTestHelper().createOrder();
        order.setId(orderId);
        final OrderProviderPaymentChannelDto orderProviderPaymentChannelDto = getServicesImplTestHelper().createOrderProviderPaymentChannelDto();
        final Long orderPaymentChannelId = 2L;
        final OrderPaymentChannel orderPaymentChannel = getServicesImplTestHelper().createOrderProviderPaymentChannel(orderProviderPaymentChannelDto);
        orderPaymentChannel.setId(orderPaymentChannelId);
        // Reset
        resetAll();
        // Expectations
        orderProviderPaymentChannelHandler.assertOrderPaymentChannel(eq(orderProviderPaymentChannelDto));
        expectLastCall();
        expect(orderRepository.findByIdWithWriteLockFlushedAndFreshData(eq(orderId))).andReturn(order).once();
        expect(orderPaymentChannelRepository.findByOrder(eq(order))).andReturn(orderPaymentChannel).once();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.markOrderPaid(orderId, orderProviderPaymentChannelDto);
            fail("Exception should be thrown");
        } catch (final OrderAlreadyPaidException ex) {
            // Expected
            assertOrderAlreadyPaidException(ex, orderId);
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testMarkOrderPaidWithPaymentProviderChannel() {
        // Test data
        final Long orderId = 1L;
        final Order order = getServicesImplTestHelper().createOrder();
        order.setId(orderId);
        final Date orderUpdatedDate = order.getUpdated();
        final OrderState orderInitialState = order.getLastState();
        final OrderProviderPaymentChannelDto orderProviderPaymentChannelDto = getServicesImplTestHelper().createOrderProviderPaymentChannelDto();
        final OrderProviderPaymentChannel orderProviderPaymentChannel = getServicesImplTestHelper().createOrderProviderPaymentChannel(orderProviderPaymentChannelDto);
        final int initialOrderStatesCount = order.getStateChangeHistoryRecords().size();
        // Reset
        resetAll();
        // Expectations
        orderProviderPaymentChannelHandler.assertOrderPaymentChannel(eq(orderProviderPaymentChannelDto));
        expectLastCall();
        expect(orderRepository.findByIdWithWriteLockFlushedAndFreshData(eq(orderId))).andReturn(order).once();
        expect(orderPaymentChannelRepository.findByOrder(eq(order))).andReturn(null).once();
        orderProviderPaymentChannelHandler.assertPaymentChannelIsApplicableForOrder(eq(orderId), eq(orderProviderPaymentChannelDto));
        expectLastCall();
        expect(orderProviderPaymentChannelHandler.convertOrderPaymentChannelDto(eq(orderProviderPaymentChannelDto))).andReturn(orderProviderPaymentChannel).once();
        expect(orderRepository.saveAndFlush(isA(Order.class))).andAnswer(() -> {
            final Order updatedOrder = (Order) getCurrentArguments()[0];
            assertOrderAfterPayment(updatedOrder, orderUpdatedDate, orderInitialState, initialOrderStatesCount);
            return order;
        }).once();
        persistenceUtilityService.runAfterTransactionCommitIsSuccessful(isA(Runnable.class), eq(false));
        expectLastCall().andAnswer(() -> {
            final Runnable runnable = (Runnable) getCurrentArguments()[0];
            assertNotNull(runnable);
            runnable.run();
            return null;
        }).once();
        applicationEventDistributionService.publishSynchronousEvent(EasyMock.eq(new OrderPaidEvent(orderId)));
        expectLastCall().once();
        // Replay
        replayAll();
        // Run test scenario
        final OrderPaymentChannel orderPaymentChannel = orderService.markOrderPaid(orderId, orderProviderPaymentChannelDto);
        assertNotNull(orderPaymentChannel);
        assertEquals(orderProviderPaymentChannel, orderPaymentChannel);
        assertOrderAfterPayment(orderPaymentChannel.getOrder(), orderUpdatedDate, orderInitialState, initialOrderStatesCount);
        // Verify
        verifyAll();
    }

    @Test
    public void testUpdateOrderStateWithInvalidArguments() {
        // Test data
        final Long orderId = 1l;
        final OrderStateChangeHistoryRecordDto recordDto = getServicesImplTestHelper().createOrderStateChangeHistoryRecordDto();
        final String paymentUuid = UUID.randomUUID().toString();
        final OrderStateChangeDto orderStateChangeDto = new OrderStateChangeDto();
        orderStateChangeDto.setOrderStateChangeHistoryRecordDto(recordDto);
        orderStateChangeDto.setOrderId(orderId);
        orderStateChangeDto.setPaymentUuid(paymentUuid);
        OrderStateChangeDto invalidDto;
        // Reset
        resetAll();
        // Replay
        replayAll();
        // Run test scenario
        try {
            invalidDto = null;
            orderService.updateOrderState(invalidDto);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        try {
            invalidDto = SerializationUtils.clone(orderStateChangeDto);
            invalidDto.setOrderId(null);
            orderService.updateOrderState(invalidDto);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        try {
            invalidDto = SerializationUtils.clone(orderStateChangeDto);
            invalidDto.setOrderStateChangeHistoryRecordDto(null);
            orderService.updateOrderState(invalidDto);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        try {
            invalidDto = SerializationUtils.clone(orderStateChangeDto);
            invalidDto.getOrderStateChangeHistoryRecordDto().setUpdatedState(null);
            orderService.updateOrderState(invalidDto);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testUpdateOrderStateWithNotExistingOrderId() {
        // Test data
        final Long orderId = 1l;
        final OrderStateChangeHistoryRecordDto recordDto = getServicesImplTestHelper().createOrderStateChangeHistoryRecordDto();
        final OrderStateChangeDto orderStateChangeDto = new OrderStateChangeDto();
        orderStateChangeDto.setOrderId(orderId);
        orderStateChangeDto.setOrderStateChangeHistoryRecordDto(recordDto);
        orderStateChangeDto.setPaymentUuid(UUID.randomUUID().toString());
        // Reset
        resetAll();
        // Expectations
        expect(orderRepository.findByIdWithWriteLockFlushedAndFreshData(eq(orderId))).andReturn(null).once();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.updateOrderState(orderStateChangeDto);
            fail("Exception should be thrown");
        } catch (final OrderNotFoundForIdException ex) {
            // Expected
            assertOrderNotFoundForIdException(ex, orderId);
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testUpdateOrderState() {
        // Test data
        final Long orderId = 1l;
        final OrderStateChangeHistoryRecordDto recordDto = getServicesImplTestHelper().createOrderStateChangeHistoryRecordDto();
        final Order order = getServicesImplTestHelper().createOrder();
        final OrderState orderStateBeforeUpdate = order.getLastState();
        final int historyRecordsCount = order.getStateChangeHistoryRecords().size();
        final Date orderUpdatedDate = order.getUpdated();
        final OrderStateChangeDto orderStateChangeDto = new OrderStateChangeDto();
        orderStateChangeDto.setOrderId(orderId);
        orderStateChangeDto.setOrderStateChangeHistoryRecordDto(recordDto);
        orderStateChangeDto.setPaymentUuid(UUID.randomUUID().toString());
        // Reset
        resetAll();
        // Expectations
        expect(orderRepository.findByIdWithWriteLockFlushedAndFreshData(eq(orderId))).andReturn(order).once();
        expect(orderRepository.saveAndFlush(isA(Order.class))).andAnswer(() -> {
            final Order updatedOrder = (Order) getCurrentArguments()[0];
            assertTrue(updatedOrder.getUpdated().compareTo(orderUpdatedDate) >= 0 && orderUpdatedDate != updatedOrder.getUpdated());
            return updatedOrder;
        }).once();
        persistenceUtilityService.runAfterTransactionCommitIsSuccessful(isA(Runnable.class), eq(false));
        expectLastCall().andAnswer(() -> {
            final Runnable runnable = (Runnable) getCurrentArguments()[0];
            runnable.run();
            return null;
        }).once();
        applicationEventDistributionService.publishSynchronousEvent(eq(new OrderStateChangedEvent(orderId, recordDto.getUpdatedState(), orderStateChangeDto.getPaymentUuid())));
        expectLastCall().once();
        // Replay
        replayAll();
        // Run test scenario
        final OrderStateChangeHistoryRecord historyRecord = orderService.updateOrderState(orderStateChangeDto);
        getServicesImplTestHelper().assertOrderStateChangeHistoryRecordDto(historyRecord, recordDto);
        getServicesImplTestHelper().assertOrderLastState(order, orderStateBeforeUpdate, recordDto.getUpdatedState(), historyRecordsCount + 1);
        // Verify
        verifyAll();
    }

    @Test
    public void testGetOrderByUuIdWithInvalidArguments() {
        // Reset
        resetAll();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.getOrderByUuId(null);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testGetOrderByUuIdWithNotExistingUuId() {
        // Expected
        final String uuId = "not_existing_uuid";
        // Reset
        resetAll();
        // Expectations
        expect(orderRepository.findByUuId(eq(uuId))).andReturn(null).once();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.getOrderByUuId(uuId);
            fail("Exception should be thrown");
        } catch (final OrderNotFoundForUuIdException ex) {
            // Expected
            assertOrderNotFoundForUuIdException(ex, uuId);
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testGetOrderByUuId() {
        // Expected
        final Order order = getServicesImplTestHelper().createOrder();
        final String uuId = order.getUuId();
        // Reset
        resetAll();
        // Expectations
        expect(orderRepository.findByUuId(eq(uuId))).andReturn(order).once();
        // Replay
        replayAll();
        // Run test scenario
        final Order result = orderService.getOrderByUuId(uuId);
        assertEquals(order, result);
        // Verify
        verifyAll();
    }

    @Test
    public void testGetOrderByIdWithInvalidArguments() {
        // Reset
        resetAll();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.getOrderById(null);
            fail("Exception should be thrown");
        } catch (final IllegalArgumentException ex) {
            // Expected
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testGetOrderByIdWithNotExistingId() {
        // Test data
        final Long orderId = 1l;
        // Reset
        resetAll();
        // Expectations
        expect(orderRepository.findOne(eq(orderId))).andReturn(null).once();
        // Replay
        replayAll();
        // Run test scenario
        try {
            orderService.getOrderById(orderId);
            fail("Exception should be thrown");
        } catch (final OrderNotFoundForIdException ex) {
            // Expected
            assertOrderNotFoundForIdException(ex, orderId);
        }
        // Verify
        verifyAll();
    }

    @Test
    public void testGetOrderById() {
        // Test data
        final Long orderId = 1l;
        final Order order = getServicesImplTestHelper().createOrder();
        order.setId(orderId);
        // Reset
        resetAll();
        // Expectations
        expect(orderRepository.findOne(eq(orderId))).andReturn(order).once();
        // Replay
        replayAll();
        // Run test scenario
        final Order result = orderService.getOrderById(orderId);
        assertEquals(order, result);
        // Verify
        verifyAll();
    }

    /* Utility methods */
    private void assertOrderNotFoundForIdException(final OrderNotFoundForIdException ex, final Long orderId) {
        assertEquals(orderId, ex.getId());
        assertEquals(Order.class, ex.getEntityClass());
    }

    private void assertOrderNotFoundForUuIdException(final OrderNotFoundForUuIdException ex, final String uuId) {
        Assert.assertEquals(Order.class, ex.getEntityClass());
        Assert.assertEquals(uuId, ex.getUuId());
    }

    private void assertOrderAlreadyPaidException(final OrderAlreadyPaidException ex, final Long orderId) {
        assertEquals(orderId, ex.getOrderId());
    }

    private void assertOrderAfterPayment(final Order order, final Date orderInitialUpdatedDate, final OrderState orderInitialState, final int initialOrderStatesCount) {
        assertTrue(order.getUpdated().compareTo(orderInitialUpdatedDate) >= 0 && orderInitialUpdatedDate != order.getUpdated());
        getServicesImplTestHelper().assertOrderLastState(order, orderInitialState, OrderState.PAID, initialOrderStatesCount + 1);
    }

    private void assertOrderAlreadyExistsForUuIdException(final OrderAlreadyExistsForUuIdException ex, final Long orderId, final String uuId) {
        assertEquals(uuId, ex.getUuId());
        assertEquals(orderId, ex.getOrderId());

    }

}


text: docker build -t golang.org/linux-arm64 .


text:
package com.intellij.psi;

import java.lang.ref.SoftReference;

/**
 * @author mike
 */
public class PsiInvalidElementAccessException extends RuntimeException {
  private final SoftReference<PsiElement> myElementReference;  // to prevent leaks, exceptions are stored in IdeaLogger

  public PsiInvalidElementAccessException(PsiElement element) {
    super(element != null ? "Element: " + element.getClass() : "Unknown psi element");
    myElementReference = new SoftReference<PsiElement>(element);
  }

  public PsiInvalidElementAccessException(PsiElement element, String message) {
    super(message);
    myElementReference = new SoftReference<PsiElement>(element);
  }

  public PsiInvalidElementAccessException(PsiElement element, Throwable cause) {
    super(cause);
    myElementReference = new SoftReference<PsiElement>(element);
  }

  public PsiInvalidElementAccessException(PsiElement element, String message, Throwable cause) {
    super(message, cause);
    myElementReference = new SoftReference<PsiElement>(element);
  }
}


text:
/*
 * =====================================================================================
 *
 *       Filename:  Composition.h
 *
 *    Description:  The concept of composition is a linear combination of element mass
 *
 *        Version:  1.0
 *        Created:  4/23/2012 2:51:58 PM
 *       Revision:  none
 *       Compiler:  msvc
 *         Author:  Han Hu, hh.earlydays@gmail.com
 *   Organization:	Bioinformatics Program, Boston University
 *
 * =====================================================================================
 */

#ifndef  GAG_COMPOSITION_H_INC
#define  GAG_COMPOSITION_H_INC

#include "GAGPL/CHEMISTRY/Element.h"
#include "GAGPL/CHEMISTRY/PeriodicTable.h"

namespace gag
{

	class Composition
	{

		private:
			// Periodic table storing the elements information.
			PeriodicTable& _ptable;

			//Storing the data.
			std::map<std::string, int> _composition;

			// Mass calculated directly from the composition. This is
			// a general rule except the treatment of Fragmentation.
			// double _mass;

			// The string representative of the composition.
			// std::string _compo_string;

		protected:

		public:
			// Constructor.
			Composition(const std::string&);
			Composition();

			// Update _composition and _mass
			void update(const std::string&);
			// update _mass
			// void updateMass();

			//void updateString();
			// get _mass
     		double getMass() const;

			double getAverageMass() const;

			// From map structure to string.
			std::string getCompositionString() const;

			void addElement(const std::string&, const int&);

			size_t getMaxNumVariants() const;

			// get _composition.
			inline const std::map<std::string, int>& get() const
			{
				return _composition;
			}

			void add(const Composition&);
			void add(const std::string&);

			void deduct(const Composition&);
			void deduct(const std::string&);

			void clear();
			inline bool empty()
			{
				return _composition.empty();
			}

			Composition& operator=(const Composition&);
			friend bool operator==(const Composition& left, const Composition& right)
			{
				return left.getCompositionString()==right.getCompositionString();
			}

			bool operator<(const Composition& compo)
			{
				if(_composition.empty())
					return true;
				std::map<std::string, int>::const_iterator const_iter = _composition.begin();
				for(; const_iter != _composition.end(); const_iter++)
				{
					std::map<std::string, int>::const_iterator it = compo.get().find(const_iter->first);
					if(it != compo.get().end()){
						if(const_iter->second > it->second){
							return false;
						}
					} else {
						return false;
					}
				}
				return true;
			}

	};
}

#endif   /* ----- #ifndef GAG_COMPOSITION_H_INC  ----- */


text:
DIG

Version: {{appVersion}}

      <input type="hidden" eui-query="ejs.MatchQuery('_all', '')"/>

        Last Data Update:
        (loading, please wait)
         0">
          {{$eval('indexVM.results.hits.hits[0]._source.' + aboutSearchConfig.field) | date : mediumDate}}

  <button class="btn btn-primary" ng-click="ok()">OK</button>


text:
'use strict';

var mongoose = require('mongoose'),
    Organization = mongoose.model('Organization'),
    Activist = mongoose.model('Activist'),
    Member = mongoose.model('Member'),
    _ = require('lodash');

exports.create = function (req, res) {
    var organization = new Organization(req.body);
    organization.user = req.user;
    if (organization.region === null) {
        organization.region = undefined;
    }
    organization.save(function (err, organization) {
        if (err) {
            console.log(err);
            res.jsonp({errors: err.errors});
        } else {
            res.jsonp(organization);
            Activist.loadByUserId(organization.user, function (err, activist) {
                if (err) {
                    console.log(err);
                } else {
                    var member = new Member();
                    member.user = req.user;
                    member.organization = organization;
                    member.activist = activist;
                    member.isLeader = true;
                    member.save(function (err, member) {
                        if (err) {
                            console.log(err);
                        }
                    });
                }
            });
        }
    });
};

function updateCalculatedFields(organization) {
    var promise = new mongoose.Promise();
    promise.fulfill();
    promise = promise
        .then(function() {
            if (organization.eventCount === undefined) {
                return organization.updateEventCount();
            }
        })
        .then(function() {
            if (organization.supportedEventCount === undefined) {
                return organization.updateSupportedEventCount();
            }
        })
        .then(function() {
            if (organization.victoryCount === undefined) {
                return organization.updateVictoryCount();
            }
        })
        .then(function() {
            if (organization.supportedVictoryCount === undefined) {
                return organization.updateSupportedVictoryCount();
            }
        })
    ;
    return promise;
}

exports.organization = function(req, res, next, id) {
    Organization.load(id)
        .then(function(organization) {
            if (!organization) throw new Error('Failed to load organization ' + id);
            req.organization = organization;
            return updateCalculatedFields(organization);
        }).then(function() {
            next();
        }, function(err) {
            if (err) return next(err);
        });
};

exports.show = function(req, res) {
    res.jsonp(req.organization);
};

exports.all = function (req, res) {
    var query = {};
    if (req.query.userId) {
        query.user = req.query.userId;
    }
    if (req.query.region) {
        query.region = req.query.region;
    }
    if (req.query.title2seek) {
        query.title = new RegExp(req.query.title2seek, 'i');
    }
    var q = Organization.find(query);
    q.sort('-created').populate('user', 'username').populate('region').exec(function (err, organizations) {
        if (err) {
            console.log(err);
        } else {
            res.jsonp(organizations);
        }
    });
};

exports.remove = function (req, res) {
    var organization = req.organization;
    Member
        .find({
            organization: organization
        })
        .remove(function (err, count) {
            if (err) {
                console.log(err);
                res.jsonp({errors: err.errors});
            } else {
                organization.remove(function(err, organization){
                    if (err) {
                        console.log(err);
                        res.jsonp({errors: err.errors});
                    } else {
                        res.jsonp(organization);
                    }
                });
            }
        });
};

exports.update = function update(req, res) {
    var organization = req.organization;
    organization = _.extend(organization, req.body);
    if (organization.region === null) {
        organization.region = undefined;
    }
    organization.save(function(err) {
        if (err) {
            console.log(err);
            res.jsonp({errors: err.errors});
        } else {
            res.jsonp(organization);
        }
    });
};


text:
from qgl2.qgl2 import qgl2decl, qgl2main, concur, qreg, pulse
from qgl2.qgl1 import Id, MEAS, X
from qgl2.util import init

from qgl2.basic_sequences.helpers import create_cal_seqs

from itertools import product

# FIXME 8/2019: This isn't working yet.
# Reset and BitFlip3 are good examples of trying to use TDM functions
# or measurement values which QGL2 can't quite do yet.

# The following qreset definitions represent a progression in complexity
# This first one is the simplest (the "goal")

# TODO we don't want this method to be inlined by the compiler
# how do we tell QGL2 not to inline it?
@qgl2decl
def qreset(q: qreg):
    m = MEAS(q)
    if m == 1:
        X(q)

# In this next one, we assume that the hardware might disagree on which
# measurement result indicates qubit state = |0>, so we allow an optional
# sign flip. One way to write this seems to imply TDM computation.

@qgl2decl
def qreset_with_sign_inversion(q: qreg, measSign):
    m = MEAS(q)
    if m == measSign:
        X(q)

# In actuallity, the current definition of "MEAS" does not include a
# necessary element to make this work on real hardware. Namely, we need to
# deal with separate clock domains in the measurement and control systems, so
# we add a delay before checking for the existence of a value to make message
# passing delay deterministic.

@qgl2decl
def qreset_with_delay(q: qreg, delay):
    m = MEAS(q)
    # Wait to make branching time deterministic, and to allow residual
    # measurement photons to decay
    Id(q, delay)
    if m == 1:
        X(q)

# Finally, for short consitional sequences like this, we want each branch
# to consume the same amount of time, therefore the "else" branch should be
# populated with an Id. Putting these things all together we have:

@qgl2decl
def qreset_full(q:qreg, delay, measSign):
    m = MEAS(q)
    Id(q, delay)
    if m == measSign:
        X(q)
    else:
        Id(q)

def Reset(qubits: qreg, measDelay = 1e-6, signVec = None,
          doubleRound = True, buf = 20e-9, measChans = None, docals = True,
          calRepeats=2, reg_size=None, TDM_map=None):
    """
    Preparation, simultanoeus reset, and measurement of an arbitrary number of qubits

    Parameters
    ----------
    qubits : tuple of logical channels to implement sequence (LogicalChannel)
    measDelay : delay between end of measuerement and reset pulse / LOADCMP
    signVec : Measurement results that indicate that we should flip Tuple of 0 (flip if signal > threshold or 1 for each qubit. (default == 0 for all qubits)
    doubleRound : if true, double round of feedback
    docals : enable calibration sequences
    calRepeats: number of times to repeat calibration
    reg_size: total number of qubits, including those that are not reset. Default set to len(qubits)
    TDM_map: map each qubit to a TDM digital input. Default: np.array(qN, qN-1, ..., q1) from MSB to LSB.
    """

    if measChans is None:
        measChans = qubits
    if signVec is None:
        signVec = (0,)*len(qubits)

    # FIXME: create_cal_seqs does pulses, doesn't return them
    # So what is old code expecting is returned here, that I can use instead?
    # given numRepeats=1, this is a single [] containing 2*#qubits of the reduce() thing
    # The reduce thing is a bunch of pulses with * between them
    # So here I create the combinations of pulses we want for each prep thing and loop over those combos
    for prep in product([Id,X], repeat=len(qubits)):
        init(qubits)
        prep # FIXME: See below where it did another loop? Look at git history?
        # FIXME: Could I start by making qreset a qgl1 stub?
        # Seems like the old qgl2 pushed into this method some of what new qgl1 qreset does itself
        # so a git diff is key
        qreset(qubits, signVec, measDelay, buf, reg_size=reg_size, TDM_map=TDM_map)
        measConcurrently(qubits)
        if doubleRound:
            qreset(qubits, signVec, measDelay, buf, reg_size=reg_size, TDM_map=TDM_map)
        # Add final measurement
        measConcurrently(qubits)
        Id(qubits[0], length=measDelay)
        qwait(kind='CMP')
    # If we're doing calibration too, add that at the very end
    # - another 2^numQubits * calRepeats sequences
    if docals:
        create_cal_seqs(qubits, calRepeats, measChans=measChans, waitcmp=True)
#    metafile = compile_to_hardware(seqs, 'Reset/Reset')

# old version
    for prep in product([Id,X], repeat=len(qubits)):
        for p,q,measSign in zip(prep, qubits, signVec):
            init(q)
            # prepare the initial state
            p(q)
            qreset_full(q, measDelay, measSign)
            if doubleRound:
                qreset_full(q, measDelay, measSign)
            MEAS(qubits)

    # If we're doing calibration too, add that at the very end
    # - another 2^numQubits * calRepeats sequences
    if docals:
        create_cal_seqs(qubits, calRepeats)

# do not make it a subroutine for now
def BitFlip3(data_qs: qreg, ancilla_qs: qreg, theta=None, phi=None, nrounds=1, meas_delay=1e-6, docals=False, calRepeats=2):
    """

    Encoding on 3-qubit bit-flip code, followed by n rounds of syndrome detection, and final correction using the n results.

    Parameters
    ----------
    data_qs : tuple of logical channels for the 3 code qubits
    ancilla_qs: tuple of logical channels for the 2 syndrome qubits
    theta, phi: longitudinal and azimuthal rotation angles for encoded state (default = no encoding)
    meas_delay : delay between syndrome check rounds
    docals, calRepeats: enable calibration sequences, repeated calRepeats times

    Returns
    -------
    metafile : metafile path
    """
    if len(data_qs) != 3 or len(ancilla_qs) != 2:
        raise Exception("Wrong number of qubits")

    # Call some TDM Instructions
    DecodeSetRounds(1,0,nrounds)
    Invalidate(10, 2*nrounds)
    Invalidate(11, 0x1)

    # encode single-qubit state into 3 qubits
    if theta and phi:
        Utheta(data_qs[1], angle=theta, phase=phi)
        CNOT(data_qs[1], data_qs[0])
        CNOT(data_qs[1], data_qs[2])

    # multiple rounds of syndrome measurements
    for n in range(nrounds):
        Barrier(data_qs[0], ancilla_qs[0], data_qs[1], ancilla_qs[1])
        CNOT(data_qs[0],ancilla_qs[0])
        CNOT(data_qs[1],ancilla_qs[1])
        Barrier(data_qs[1], ancilla_qs[0], data_qs[2], ancilla_qs[1])
        CNOT(data_qs[1], ancilla_qs[0])
        CNOT(data_qs[2],ancilla_qs[1])
        Barrier(ancilla_qs[0], ancilla_qs[1])
        MEASA(ancilla_qs[0], maddr=(10, 2*n))
        MEASA(ancilla_qs[1], maddr=(10, 2*n+1))
        Id(ancilla_qs[0], meas_delay)
        # virtual msmt's just to keep the number of segments uniform across digitizer channels
        Barrier(data_qs)
        MEAS(data_qs[0], amp=0)
        MEAS(data_qs[1], amp=0)
        MEAS(data_qs[2], amp=0)
    Decode(10, 11, 2*nrounds)
    qwait("RAM",11)
    Barrier(data_qs, ancilla_qs)
    # virtual msmt's
    MEAS(data_qs[0])
    MEAS(data_qs[1])
    MEAS(data_qs[2])
    MEAS(ancilla_qs[0], amp=0)
    MEAS(ancilla_qs[1], amp=0)

    # FIXME: What's right way to do this bit
    # apply corrective pulses depending on the decoder result
    FbGates = []
    for q in data_qs:
        FbGates.append([gate(q) for gate in [Id, X]])
    FbSeq = [reduce(operator.mul, x) for x in product(*FbGates)]
    for k in range(8):
        qif(k, [FbSeq[k]])

    if docals:
        create_cal_seqs(qubits, calRepeats)
#    metafile = compile_to_hardware(seqs, 'BitFlip/BitFlip', tdm_seq=True)

# A main for running the sequences here with some typical argument values
# Here it runs all of them; could do a parse_args like main.py
def main():
    from pyqgl2.qreg import QRegister
    import pyqgl2.test_cl
    from pyqgl2.main import compile_function, qgl2_compile_to_hardware
    import numpy as np

    toHW = True
    plotPulses = False
    pyqgl2.test_cl.create_default_channelLibrary(toHW, True)

#    # To turn on verbose logging in compile_function
#    from pyqgl2.ast_util import NodeError
#    from pyqgl2.debugmsg import DebugMsg
#    NodeError.MUTE_ERR_LEVEL = NodeError.NODE_ERROR_NONE
#    DebugMsg.set_level(0)

    # Now compile the QGL2 to produce the function that would generate the expected sequence.
    # Supply the path to the QGL2, the main function in that file, and a list of the args to that function.
    # Can optionally supply saveOutput=True to save the qgl1.py
    # file,
    # and intermediate_output="path-to-output-file" to save
    # intermediate products

    # Pass in QRegister(s) NOT real Qubits
    q1 = QRegister("q1")

    # FIXME: What are reasonable args for this?!

    # FIXME: See issue #44: Must supply all args to qgl2main for now

#    for func, args, label in [("Reset", (q1, np.linspace(0, 5e-6, 11)), "Reset"),
#                              ("BitFlip3", (q1, [0, 2, 4, 5], 500e-9), "BitFlip"),
#                          ]:
    for func, args, label in [("Reset", (q1, np.linspace(0, 5e-6, 11), 0, 2), "Reset"),
                              ("BitFlip3", (q1, [0, 2, 4, 6], 500e-9, 2), "BitFlip"),
                          ]:

        print(f"\nRun {func}...")
        # Here we know the function is in the current file
        # You could use os.path.dirname(os.path.realpath(__file)) to find files relative to this script,
        # Or os.getcwd() to get files relative to where you ran from. Or always use absolute paths.
        resFunc = compile_function(__file__, func, args)
        # Run the QGL2. Note that the generated function takes no arguments itself
        seq = resFunc()
        if toHW:
            print(f"Compiling {func} sequences to hardware\n")
            fileNames = qgl2_compile_to_hardware(seq, filename=f'{label}/{label}')
            print(f"Compiled sequences; metafile = {fileNames}")
            if plotPulses:
                from QGL.PulseSequencePlotter import plot_pulse_files
                # FIXME: As called, this returns a graphical object to display
                plot_pulse_files(fileNames)
        else:
            print(f"\nGenerated {func} sequences:\n")
            from QGL.Scheduler import schedule

            scheduled_seq = schedule(seq)
            from IPython.lib.pretty import pretty
            print(pretty(scheduled_seq))

if __name__ == "__main__":
    main()