text:
#include "rtabmap/core/CameraRGBD.h"
#include "rtabmap/core/util3d.h"

#include <rtabmap/utilite/UEventsManager.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UStl.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UFile.h>
#include <rtabmap/utilite/UDirectory.h>
#include <rtabmap/utilite/UTimer.h>
#include <rtabmap/utilite/UMath.h>

#include <pcl/io/openni_grabber.h>
#include <pcl/io/oni_grabber.h>

#ifdef WITH_FREENECT
#include <libfreenect.h>
#ifdef FREENECT_DASH_INCLUDES
#include <libfreenect-registration.h>
#else
#include <libfreenect_registration.h>
#endif
#endif

#ifdef WITH_FREENECT2
#include <libfreenect2/libfreenect2.hpp>
#include <libfreenect2/frame_listener_impl.h>
#include <libfreenect2/registration.h>
#include <libfreenect2/packet_pipeline.h>
#endif

#ifdef WITH_DC1394
#include <dc1394/dc1394.h>
#endif

#ifdef WITH_OPENNI2
#include <OniVersion.h>
#include <OpenNI.h>
#endif

#ifdef WITH_FLYCAPTURE2
#include <triclops.h>
#include <fc2triclops.h>
#endif

namespace rtabmap
{

CameraRGBD::CameraRGBD(float imageRate, const Transform & localTransform) :
	_imageRate(imageRate),
	_localTransform(localTransform),
	_mirroring(false),
	_colorOnly(false),
	_frameRateTimer(new UTimer())
{
}

CameraRGBD::~CameraRGBD()
{
	if(_frameRateTimer)
	{
		delete _frameRateTimer;
	}
}

void CameraRGBD::takeImage(cv::Mat & rgb, cv::Mat & depth, float & fx, float & fy, float & cx, float & cy)
{
	bool warnFrameRateTooHigh = false;
	float actualFrameRate = 0;
	float imageRate = _imageRate==0.0f?20.0f:_imageRate; // limit to 20Hz if infinity
	if(imageRate>0)
	{
		int sleepTime = (1000.0f/imageRate - 1000.0f*_frameRateTimer->getElapsedTime());
		if(sleepTime > 2)
		{
			uSleep(sleepTime-2);
		}
		else if(sleepTime < 0)
		{
			warnFrameRateTooHigh = true;
			actualFrameRate = 1.0/(_frameRateTimer->getElapsedTime());
		}

		// Add precision at the cost of a small overhead
		while(_frameRateTimer->getElapsedTime() < 1.0/double(imageRate)-0.000001)
		{
			//
		}

		double slept = _frameRateTimer->getElapsedTime();
		_frameRateTimer->start();
		UDEBUG("slept=%fs vs target=%fs", slept, 1.0/double(imageRate));
	}

	UTimer timer;
	this->captureImage(rgb, depth, fx, fy, cx, cy);
	if(_colorOnly)
	{
		depth = cv::Mat();
	}
	if(_mirroring)
	{
		if(!rgb.empty())
		{
			cv::flip(rgb,rgb,1);
			if(cx != 0.0f)
			{
				cx = float(rgb.cols) - cx;
			}
		}
		if(!depth.empty())
		{
			cv::flip(depth,depth,1);
		}
	}
	if(warnFrameRateTooHigh)
	{
		UWARN("Camera: Cannot reach target image rate %f Hz, current rate is %f Hz and capture time = %f s.",
				imageRate, actualFrameRate, timer.ticks());
	}
	else
	{
		UDEBUG("Time capturing image = %fs", timer.ticks());
	}
}

/////////////////////////
// CameraOpenNIPCL
/////////////////////////
CameraOpenni::CameraOpenni(const std::string & deviceId, float imageRate, const Transform & localTransform) :
		CameraRGBD(imageRate, localTransform),
		interface_(0),
		deviceId_(deviceId),
		depthConstant_(0.0f)
{
}

CameraOpenni::~CameraOpenni()
{
	UDEBUG("");
	if(connection_.connected())
	{
		connection_.disconnect();
	}

	if(interface_)
	{
		interface_->stop();
		uSleep(1000); // make sure it is stopped
		delete interface_;
		interface_ = 0;
	}
}

void CameraOpenni::image_cb (
		const boost::shared_ptr<openni_wrapper::Image>& rgb,
		const boost::shared_ptr<openni_wrapper::DepthImage>& depth,
		float constant)
{
	UScopeMutex s(dataMutex_);

	bool notify = rgb_.empty();

	cv::Mat rgbFrame(rgb->getHeight(), rgb->getWidth(), CV_8UC3);
	rgb->fillRGB(rgb->getWidth(), rgb->getHeight(), rgbFrame.data);
	cv::cvtColor(rgbFrame, rgb_, CV_RGB2BGR);

	depth_ = cv::Mat(rgb->getHeight(), rgb->getWidth(), CV_16UC1);
	depth->fillDepthImageRaw(rgb->getWidth(), rgb->getHeight(), (unsigned short*)depth_.data);

	depthConstant_ = constant;

	if(notify)
	{
		dataReady_.release();
	}
}

bool CameraOpenni::init(const std::string & calibrationFolder)
{
	if(interface_)
	{
		interface_->stop();
		uSleep(100); // make sure it is stopped
		delete interface_;
		interface_ = 0;
	}

	try
	{
		if(UFile::getExtension(deviceId_).compare("oni") == 0)
		{
			interface_ = new pcl::ONIGrabber(deviceId_, false, true);
		}
		else
		{
			interface_ = new pcl::OpenNIGrabber(deviceId_);
		}

		boost::function<void (
				const boost::shared_ptr<openni_wrapper::Image>&,
				const boost::shared_ptr<openni_wrapper::DepthImage>&,
				float)> f = boost::bind (&CameraOpenni::image_cb, this, _1, _2, _3);
		connection_ = interface_->registerCallback (f);

		interface_->start ();
	}
	catch(const pcl::IOException& ex)
	{
		UERROR("OpenNI exception: %s", ex.what());
		if(interface_)
		{
			delete interface_;
			interface_ = 0;
		}
		return false;
	}
	return true;
}

bool CameraOpenni::isCalibrated() const
{
	return true;
}

std::string CameraOpenni::getSerial() const
{
	if(interface_)
	{
		return interface_->getName();
	}
	return "";
}

void CameraOpenni::captureImage(cv::Mat & rgb, cv::Mat & depth, float & fx, float & fy, float & cx, float & cy)
{
	rgb = cv::Mat();
	depth = cv::Mat();
	fx=0.0f;
	fy=0.0f;
	cx=0.0f;
	cy=0.0f;
	if(interface_ && interface_->isRunning())
	{
		if(!dataReady_.acquire(1, 2000))
		{
			UWARN("Not received new frames since 2 seconds, end of stream reached!");
		}
		else
		{
			UScopeMutex s(dataMutex_);
			if(depthConstant_)
			{
				depth = depth_;
				rgb = rgb_;
				fx = 1.0f/depthConstant_;
				fy = 1.0f/depthConstant_;
				cx = float(depth_.cols/2) - 0.5f;
				cy = float(depth_.rows/2) - 0.5f;
			}

			depth_ = cv::Mat();
			rgb_ = cv::Mat();
			depthConstant_ = 0.0f;
		}
	}
}

/////////////////////////
// CameraOpenNICV
/////////////////////////
bool CameraOpenNICV::available()
{
	return cv::getBuildInformation().find("OpenNI:                      YES") != std::string::npos;
}

CameraOpenNICV::CameraOpenNICV(bool asus, float imageRate, const rtabmap::Transform & localTransform) :
	CameraRGBD(imageRate, localTransform),
	_asus(asus),
	_depthFocal(0.0f)
{

}

CameraOpenNICV::~CameraOpenNICV()
{
	_capture.release();
}

bool CameraOpenNICV::init(const std::string & calibrationFolder)
{
	if(_capture.isOpened())
	{
		_capture.release();
	}

	ULOGGER_DEBUG("CameraRGBD::init()");
	_capture.open( _asus?CV_CAP_OPENNI_ASUS:CV_CAP_OPENNI );
	if(_capture.isOpened())
	{
		_capture.set( CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE, CV_CAP_OPENNI_VGA_30HZ );
		_depthFocal = _capture.get( CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH );
		// Print some avalible device settings.
		UINFO("Depth generator output mode:");
		UINFO("FRAME_WIDTH        %f", _capture.get( CV_CAP_PROP_FRAME_WIDTH ));
		UINFO("FRAME_HEIGHT       %f", _capture.get( CV_CAP_PROP_FRAME_HEIGHT ));
		UINFO("FRAME_MAX_DEPTH    %f mm", _capture.get( CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH ));
		UINFO("BASELINE           %f mm", _capture.get( CV_CAP_PROP_OPENNI_BASELINE ));
		UINFO("FPS                %f", _capture.get( CV_CAP_PROP_FPS ));
		UINFO("Focal              %f", _capture.get( CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH ));
		UINFO("REGISTRATION       %f", _capture.get( CV_CAP_PROP_OPENNI_REGISTRATION ));
		if(_capture.get( CV_CAP_PROP_OPENNI_REGISTRATION ) == 0.0)
		{
			UERROR("Depth registration is not activated on this device!");
		}
		if( _capture.get( CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT ) )
		{
			UINFO("Image generator output mode:");
			UINFO("FRAME_WIDTH    %f", _capture.get( CV_CAP_OPENNI_IMAGE_GENERATOR+CV_CAP_PROP_FRAME_WIDTH ));
			UINFO("FRAME_HEIGHT   %f", _capture.get( CV_CAP_OPENNI_IMAGE_GENERATOR+CV_CAP_PROP_FRAME_HEIGHT ));
			UINFO("FPS            %f", _capture.get( CV_CAP_OPENNI_IMAGE_GENERATOR+CV_CAP_PROP_FPS ));
		}
		else
		{
			UERROR("CameraRGBD: Device doesn't contain image generator.");
			_capture.release();
			return false;
		}
	}
	else
	{
		ULOGGER_ERROR("CameraRGBD: Failed to create a capture object!");
		_capture.release();
		return false;
	}
	return true;
}

bool CameraOpenNICV::isCalibrated() const
{
	return _depthFocal > 0.0f;
}

void CameraOpenNICV::captureImage(cv::Mat & rgb, cv::Mat & depth, float & fx, float & fy, float & cx, float & cy)
{
	if(_capture.isOpened())
	{
		_capture.grab();
		_capture.retrieve( depth, CV_CAP_OPENNI_DEPTH_MAP );
		_capture.retrieve( rgb, CV_CAP_OPENNI_BGR_IMAGE );

		depth = depth.clone();
		rgb = rgb.clone();
		UASSERT(_depthFocal > 0.0f);
		fx = _depthFocal;
		fy = _depthFocal;
		cx = float(depth.cols/2) - 0.5f;
		cy = float(depth.rows/2) - 0.5f;
	}
	else
	{
		ULOGGER_WARN("The camera must be initialized before requesting an image.");
	}
}

/////////////////////////
// CameraOpenNI2
/////////////////////////
bool CameraOpenNI2::available()
{
#ifdef WITH_OPENNI2
	return true;
#else
	return false;
#endif
}

bool CameraOpenNI2::exposureGainAvailable()
{
#if ONI_VERSION_MAJOR > 2 || (ONI_VERSION_MAJOR==2 && ONI_VERSION_MINOR >= 2)
	return true;
#else
	return false;
#endif
}

CameraOpenNI2::CameraOpenNI2(
		const std::string & deviceId,
		float imageRate,
		const rtabmap::Transform & localTransform) :
	CameraRGBD(imageRate, localTransform),
#ifdef WITH_OPENNI2
	_device(new openni::Device()),
	_color(new openni::VideoStream()),
	_depth(new openni::VideoStream()),
#else
	_device(0),
	_color(0),
	_depth(0),
#endif
	_depthFx(0.0f),
	_depthFy(0.0f),
	_deviceId(deviceId)
{
}

CameraOpenNI2::~CameraOpenNI2()
{
#ifdef WITH_OPENNI2
	_color->stop();
	_color->destroy();
	_depth->stop();
	_depth->destroy();
	_device->close();
	openni::OpenNI::shutdown();

	delete _device;
	delete _color;
	delete _depth;
#endif
}

bool CameraOpenNI2::setAutoWhiteBalance(bool enabled)
{
#ifdef WITH_OPENNI2
	if(_color && _color->getCameraSettings())
	{
		return _color->getCameraSettings()->setAutoWhiteBalanceEnabled(enabled) == openni::STATUS_OK;
	}
#else
	UERROR("CameraOpenNI2: RTAB-Map is not built with OpenNI2 support!");
#endif
	return false;
}

bool CameraOpenNI2::setAutoExposure(bool enabled)
{
#ifdef WITH_OPENNI2
	if(_color && _color->getCameraSettings())
	{
		return _color->getCameraSettings()->setAutoExposureEnabled(enabled) == openni::STATUS_OK;
	}
#else
	UERROR("CameraOpenNI2: RTAB-Map is not built with OpenNI2 support!");
#endif
	return false;
}

bool CameraOpenNI2::setExposure(int value)
{
#ifdef WITH_OPENNI2
#if ONI_VERSION_MAJOR > 2 || (ONI_VERSION_MAJOR==2 && ONI_VERSION_MINOR >= 2)
	if(_color && _color->getCameraSettings())
	{
		return _color->getCameraSettings()->setExposure(value) == openni::STATUS_OK;
	}
#else
	UERROR("CameraOpenNI2: OpenNI >= 2.2 required to use this method.");
#endif
#else
	UERROR("CameraOpenNI2: RTAB-Map is not built with OpenNI2 support!");
#endif
	return false;
}

bool CameraOpenNI2::setGain(int value)
{
#ifdef WITH_OPENNI2
#if ONI_VERSION_MAJOR > 2 || (ONI_VERSION_MAJOR==2 && ONI_VERSION_MINOR >= 2)
	if(_color && _color->getCameraSettings())
	{
		return _color->getCameraSettings()->setGain(value) == openni::STATUS_OK;
	}
#else
	UERROR("CameraOpenNI2: OpenNI >= 2.2 required to use this method.");
#endif
#else
	UERROR("CameraOpenNI2: RTAB-Map is not built with OpenNI2 support!");
#endif
	return false;
}

bool CameraOpenNI2::setMirroring(bool enabled)
{
#ifdef WITH_OPENNI2
	if(_color->isValid() && _depth->isValid())
	{
		return _depth->setMirroringEnabled(enabled) == openni::STATUS_OK &&
				_color->setMirroringEnabled(enabled) == openni::STATUS_OK;
	}
#endif
	return false;
}

bool CameraOpenNI2::init(const std::string & calibrationFolder)
{
#ifdef WITH_OPENNI2
	openni::OpenNI::initialize();

	if(_device->open(_deviceId.empty()?openni::ANY_DEVICE:_deviceId.c_str()) != openni::STATUS_OK)
	{
		if(!_deviceId.empty())
		{
			UERROR("CameraOpenNI2: Cannot open device \"%s\".", _deviceId.c_str());
		}
		else
		{
			UERROR("CameraOpenNI2: Cannot open device.");
		}
		_device->close();
		openni::OpenNI::shutdown();
		return false;
	}

	if(UFile::getExtension(_deviceId).compare("oni")==0)
	{
		if(_device->getPlaybackControl() &&
		   _device->getPlaybackControl()->setRepeatEnabled(false) != openni::STATUS_OK)
		{
			UERROR("CameraOpenNI2: Cannot set repeat mode to false.");
			_device->close();
			openni::OpenNI::shutdown();
			return false;
		}
	}
	else if(!_device->isImageRegistrationModeSupported(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR))
	{
		UERROR("CameraOpenNI2: Device doesn't support depth/color registration.");
		_device->close();
		openni::OpenNI::shutdown();
		return false;
	}

	if(_device->getSensorInfo(openni::SENSOR_DEPTH) == NULL ||
	  _device->getSensorInfo(openni::SENSOR_COLOR) == NULL)
	{
		UERROR("CameraOpenNI2: Cannot get sensor info for depth and color.");
		_device->close();
		openni::OpenNI::shutdown();
		return false;
	}

	if(_depth->create(*_device, openni::SENSOR_DEPTH) != openni::STATUS_OK)
	{
		UERROR("CameraOpenNI2: Cannot create depth stream.");
		_device->close();
		openni::OpenNI::shutdown();
		return false;
	}

	if(_color->create(*_device, openni::SENSOR_COLOR) != openni::STATUS_OK)
	{
		UERROR("CameraOpenNI2: Cannot create color stream.");
		_depth->destroy();
		_device->close();
		openni::OpenNI::shutdown();
		return false;
	}

	if(_device->setImageRegistrationMode(openni::IMAGE_REGISTRATION_DEPTH_TO_COLOR ) != openni::STATUS_OK)
	{
		UERROR("CameraOpenNI2: Failed to set depth/color registration.");
	}

	if (_device->setDepthColorSyncEnabled(true) != openni::STATUS_OK)
	{
		UERROR("CameraOpenNI2: Failed to set depth color sync");
	}

	_depth->setMirroringEnabled(false);
	_color->setMirroringEnabled(false);

	const openni::Array<openni::VideoMode>& depthVideoModes = _depth->getSensorInfo().getSupportedVideoModes();
	for(int i=0; i<depthVideoModes.getSize(); ++i)
	{
		UINFO("CameraOpenNI2: Depth video mode %d: fps=%d, pixel=%d, w=%d, h=%d",
				i,
				depthVideoModes[i].getFps(),
				depthVideoModes[i].getPixelFormat(),
				depthVideoModes[i].getResolutionX(),
				depthVideoModes[i].getResolutionY());
	}

	const openni::Array<openni::VideoMode>& colorVideoModes = _color->getSensorInfo().getSupportedVideoModes();
	for(int i=0; i<colorVideoModes.getSize(); ++i)
	{
		UINFO("CameraOpenNI2: Color video mode %d: fps=%d, pixel=%d, w=%d, h=%d",
				i,
				colorVideoModes[i].getFps(),
				colorVideoModes[i].getPixelFormat(),
				colorVideoModes[i].getResolutionX(),
				colorVideoModes[i].getResolutionY());
	}

	openni::VideoMode mMode;
	mMode.setFps(30);
	mMode.setResolution(640,480);
	mMode.setPixelFormat(openni::PIXEL_FORMAT_DEPTH_1_MM);
	_depth->setVideoMode(mMode);

	openni::VideoMode mModeColor;
	mModeColor.setFps(30);
	mModeColor.setResolution(640,480);
	mModeColor.setPixelFormat(openni::PIXEL_FORMAT_RGB888);
	_color->setVideoMode(mModeColor);

	UINFO("CameraOpenNI2: Using depth video mode: fps=%d, pixel=%d, w=%d, h=%d, H-FOV=%f rad, V-FOV=%f rad",
			_depth->getVideoMode().getFps(),
			_depth->getVideoMode().getPixelFormat(),
			_depth->getVideoMode().getResolutionX(),
			_depth->getVideoMode().getResolutionY(),
			_depth->getHorizontalFieldOfView(),
			_depth->getVerticalFieldOfView());

	if(_color->getCameraSettings())
	{
		UINFO("CameraOpenNI2: AutoWhiteBalanceEnabled = %d", _color->getCameraSettings()->getAutoWhiteBalanceEnabled()?1:0);
		UINFO("CameraOpenNI2: AutoExposureEnabled = %d", _color->getCameraSettings()->getAutoExposureEnabled()?1:0);
#if ONI_VERSION_MAJOR > 2 || (ONI_VERSION_MAJOR==2 && ONI_VERSION_MINOR >= 2)
		UINFO("CameraOpenNI2: Exposure = %d", _color->getCameraSettings()->getExposure());
		UINFO("CameraOpenNI2: GAIN = %d", _color->getCameraSettings()->getGain());
#endif
	}

	bool registered = true;
	if(registered)
	{
		_depthFx = float(_color->getVideoMode().getResolutionX()/2) / std::tan(_color->getHorizontalFieldOfView()/2.0f);
		_depthFy = float(_color->getVideoMode().getResolutionY()/2) / std::tan(_color->getVerticalFieldOfView()/2.0f);
	}
	else
	{
		_depthFx = float(_depth->getVideoMode().getResolutionX()/2) / std::tan(_depth->getHorizontalFieldOfView()/2.0f);
		_depthFy = float(_depth->getVideoMode().getResolutionY()/2) / std::tan(_depth->getVerticalFieldOfView()/2.0f);
	}
	UINFO("depth fx=%f fy=%f", _depthFx, _depthFy);

	UINFO("CameraOpenNI2: Using color video mode: fps=%d, pixel=%d, w=%d, h=%d, H-FOV=%f rad, V-FOV=%f rad",
			_color->getVideoMode().getFps(),
			_color->getVideoMode().getPixelFormat(),
			_color->getVideoMode().getResolutionX(),
			_color->getVideoMode().getResolutionY(),
			_color->getHorizontalFieldOfView(),
			_color->getVerticalFieldOfView());

	if(_depth->start() != openni::STATUS_OK ||
	   _color->start() != openni::STATUS_OK)
	{
		UERROR("CameraOpenNI2: Cannot start depth and/or color streams.");
		_depth->stop();
		_color->stop();
		_depth->destroy();
		_color->destroy();
		_device->close();
		openni::OpenNI::shutdown();
		return false;
	}

	uSleep(1000); // just to make sure the sensor is correctly initialized

	return true;
#else
	UERROR("CameraOpenNI2: RTAB-Map is not built with OpenNI2 support!");
	return false;
#endif
}

bool CameraOpenNI2::isCalibrated() const
{
	return _depthFx > 0.0f && _depthFy > 0.0f;
}

std::string CameraOpenNI2::getSerial() const
{
#ifdef WITH_OPENNI2
	if(_device)
	{
		return _device->getDeviceInfo().getName();
	}
#endif
	return "";
}

void CameraOpenNI2::captureImage(cv::Mat & rgb, cv::Mat & depth, float & fx, float & fy, float & cx, float & cy)
{
#ifdef WITH_OPENNI2
	rgb = cv::Mat();
	depth = cv::Mat();
	fx = 0.0f;
	fy = 0.0f;
	cx = 0.0f;
	cy = 0.0f;

	int readyStream = -1;
	if(_device->isValid() &&
		_depth->isValid() &&
		_color->isValid() &&
		_device->getSensorInfo(openni::SENSOR_DEPTH) != NULL &&
		_device->getSensorInfo(openni::SENSOR_COLOR) != NULL)
	{
		openni::VideoStream* depthStream[] = {_depth};
		openni::VideoStream* colorStream[] = {_color};
		if(openni::OpenNI::waitForAnyStream(depthStream, 1, &readyStream, 2000) != openni::STATUS_OK ||
		   openni::OpenNI::waitForAnyStream(colorStream, 1, &readyStream, 2000) != openni::STATUS_OK)
		{
			UWARN("No frames received since the last 2 seconds, end of stream is reached!");
		}
		else
		{
			openni::VideoFrameRef depthFrame, colorFrame;
			_depth->readFrame(&depthFrame);
			_color->readFrame(&colorFrame);
			if(depthFrame.isValid() && colorFrame.isValid())
			{
				int h=depthFrame.getHeight();
				int w=depthFrame.getWidth();
				depth = cv::Mat(h, w, CV_16U, (void*)depthFrame.getData()).clone();

				h=colorFrame.getHeight();
				w=colorFrame.getWidth();
				cv::Mat tmp(h, w, CV_8UC3, (void *)colorFrame.getData());
				cv::cvtColor(tmp, rgb, CV_RGB2BGR);
			}
			UASSERT(_depthFx != 0.0f && _depthFy != 0.0f);
			fx = _depthFx;
			fy = _depthFy;
			cx = float(depth.cols/2) - 0.5f;
			cy = float(depth.rows/2) - 0.5f;
		}
	}
	else
	{
		ULOGGER_WARN("The camera must be initialized before requesting an image.");
	}
#else
	UERROR("CameraOpenNI2: RTAB-Map is not built with OpenNI2 support!");
#endif
}

#ifdef WITH_FREENECT
//
// FreenectDevice
//
class FreenectDevice : public UThread {
  public:
	FreenectDevice(freenect_context * ctx, int index) :
		index_(index),
		ctx_(ctx),
		device_(0),
		depthFocal_(0.0f)
	{
		UASSERT(ctx_ != 0);
	}

	~FreenectDevice()
	{
		this->join(true);
		if(device_ && freenect_close_device(device_) < 0){} //FN_WARNING("Device did not shutdown in a clean fashion");
	}

	const std::string & getSerial() const {return serial_;}

	bool init()
	{
		if(device_)
		{
			this->join(true);
			freenect_close_device(device_);
			device_ = 0;
		}
		serial_.clear();
		std::vector<std::string> deviceSerials;
		freenect_device_attributes* attr_list;
		freenect_device_attributes* item;
		freenect_list_device_attributes(ctx_, &attr_list);
		for (item = attr_list; item != NULL; item = item->next) {
			deviceSerials.push_back(std::string(item->camera_serial));
		}
		freenect_free_device_attributes(attr_list);

		if(freenect_open_device(ctx_, &device_, index_) < 0)
		{
			UERROR("FreenectDevice: Cannot open Kinect");
			return false;
		}

		if(index_ >= 0 && index_ < (int)deviceSerials.size())
		{
			serial_ = deviceSerials[index_];
		}
		else
		{
			UERROR("Could not get serial for index %d", index_);
		}

		freenect_set_user(device_, this);
		freenect_set_video_mode(device_, freenect_find_video_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_VIDEO_RGB));
		freenect_set_depth_mode(device_, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_REGISTERED));
		depthBuffer_ = cv::Mat(cv::Size(640,480),CV_16UC1);
		rgbBuffer_ = cv::Mat(cv::Size(640,480), CV_8UC3);
		freenect_set_depth_buffer(device_, depthBuffer_.data);
		freenect_set_video_buffer(device_, rgbBuffer_.data);
		freenect_set_depth_callback(device_, freenect_depth_callback);
		freenect_set_video_callback(device_, freenect_video_callback);

		bool registered = true;
		float rgb_focal_length_sxga = 1050.0f;
		float width_sxga = 1280.0f;
		float width = freenect_get_current_depth_mode(device_).width;
		float scale = width / width_sxga;
		if(registered)
		{
			depthFocal_ =  rgb_focal_length_sxga * scale;
		}
		else
		{
			freenect_registration reg = freenect_copy_registration(device_);
			float depth_focal_length_sxga = reg.zero_plane_info.reference_distance / reg.zero_plane_info.reference_pixel_size;
			freenect_destroy_registration(&reg);

			depthFocal_ =  depth_focal_length_sxga * scale;
		}

		UINFO("FreenectDevice: Depth focal = %f", depthFocal_);
		return true;
	}

	float getDepthFocal() const {return depthFocal_;}

	void getData(cv::Mat & rgb, cv::Mat & depth)
	{
		if(this->isRunning())
		{
			if(!dataReady_.acquire(1, 2000))
			{
				UERROR("Not received any frames since 2 seconds, try to restart the camera again.");
			}
			else
			{
				UScopeMutex s(dataMutex_);
				rgb = rgbLastFrame_;
				depth = depthLastFrame_;
				rgbLastFrame_ = cv::Mat();
				depthLastFrame_= cv::Mat();
			}
		}
	}

private:
	// Do not call directly even in child
	void VideoCallback(void* rgb)
	{
		UASSERT(rgbBuffer_.data == rgb);
		UScopeMutex s(dataMutex_);
		bool notify = rgbLastFrame_.empty();
		cv::cvtColor(rgbBuffer_, rgbLastFrame_, CV_RGB2BGR);
		if(!depthLastFrame_.empty() && notify)
		{
			dataReady_.release();
		}
	}

	// Do not call directly even in child
	void DepthCallback(void* depth)
	{
		UASSERT(depthBuffer_.data == depth);
		UScopeMutex s(dataMutex_);
		bool notify = depthLastFrame_.empty();
		depthLastFrame_ = depthBuffer_.clone();
		if(!rgbLastFrame_.empty() && notify)
		{
			dataReady_.release();
		}
	}

	void startVideo() {
		if(device_ && freenect_start_video(device_) < 0) UERROR("Cannot start RGB callback");
	}
	void stopVideo() {
		if(device_ && freenect_stop_video(device_) < 0) UERROR("Cannot stop RGB callback");
	}
	void startDepth() {
		if(device_ && freenect_start_depth(device_) < 0) UERROR("Cannot start depth callback");
	}
	void stopDepth() {
		if(device_ && freenect_stop_depth(device_) < 0) UERROR("Cannot stop depth callback");
	}

	virtual void mainLoopBegin()
	{
		this->startDepth();
		this->startVideo();
	}

	virtual void mainLoop()
	{
		timeval t;
		t.tv_sec = 0;
		t.tv_usec = 10000;
		if(freenect_process_events_timeout(ctx_, &t) < 0)
		{
			UERROR("FreenectDevice: Cannot process freenect events");
			this->kill();
		}
	}

	virtual void mainLoopEnd()
	{
		this->stopDepth();
		this->stopVideo();
		dataReady_.release();
	}

	static void freenect_depth_callback(freenect_device *dev, void *depth, uint32_t timestamp) {
		FreenectDevice* device = static_cast<FreenectDevice*>(freenect_get_user(dev));
		device->DepthCallback(depth);
	}
	static void freenect_video_callback(freenect_device *dev, void *video, uint32_t timestamp) {
		FreenectDevice* device = static_cast<FreenectDevice*>(freenect_get_user(dev));
		device->VideoCallback(video);
	}

	//noncopyable
	FreenectDevice( const FreenectDevice& );
	const FreenectDevice& operator=( const FreenectDevice& );

  private:
	int index_;
	std::string serial_;
	freenect_context * ctx_;
	freenect_device * device_;
	cv::Mat depthBuffer_;
	cv::Mat rgbBuffer_;
	UMutex dataMutex_;
	cv::Mat depthLastFrame_;
	cv::Mat rgbLastFrame_;
	float depthFocal_;
	USemaphore dataReady_;
};
#endif

//
// CameraFreenect
//
bool CameraFreenect::available()
{
#ifdef WITH_FREENECT
	return true;
#else
	return false;
#endif
}

CameraFreenect::CameraFreenect(int deviceId, float imageRate, const Transform & localTransform) :
		CameraRGBD(imageRate, localTransform),
		deviceId_(deviceId),
		ctx_(0),
		freenectDevice_(0)
{
#ifdef WITH_FREENECT
	if(freenect_init(&ctx_, NULL) < 0) UERROR("Cannot initialize freenect library");
	// claim camera
	freenect_select_subdevices(ctx_, static_cast<freenect_device_flags>(FREENECT_DEVICE_CAMERA));
#endif
}

CameraFreenect::~CameraFreenect()
{
#ifdef WITH_FREENECT
	if(freenectDevice_)
	{
		freenectDevice_->join(true);
		delete freenectDevice_;
		freenectDevice_ = 0;
	}
	if(ctx_)
	{
		if(freenect_shutdown(ctx_) < 0){} //FN_WARNING("Freenect did not shutdown in a clean fashion");
	}
#endif
}

bool CameraFreenect::init(const std::string & calibrationFolder)
{
#ifdef WITH_FREENECT
	if(freenectDevice_)
	{
		freenectDevice_->join(true);
		delete freenectDevice_;
		freenectDevice_ = 0;
	}

	if(ctx_ && freenect_num_devices(ctx_) > 0)
	{
		freenectDevice_ = new FreenectDevice(ctx_, deviceId_);
		if(freenectDevice_->init())
		{
			freenectDevice_->start();
			uSleep(3000);
			return true;
		}
		else
		{
			UERROR("CameraFreenect: Init failed!");
		}
		delete freenectDevice_;
		freenectDevice_ = 0;
	}
	else
	{
		UERROR("CameraFreenect: No devices connected!");
	}
#else
	UERROR("CameraFreenect: RTAB-Map is not built with Freenect support!");
#endif
	return false;
}

bool CameraFreenect::isCalibrated() const
{
#ifdef WITH_FREENECT
	return freenectDevice_ != 0 && freenectDevice_->getDepthFocal() > 0.0f;
#endif
	return false;
}

std::string CameraFreenect::getSerial() const
{
#ifdef WITH_FREENECT
	if(freenectDevice_)
	{
		return freenectDevice_->getSerial();
	}
#endif
	return "";
}

void CameraFreenect::captureImage(cv::Mat & rgb, cv::Mat & depth, float & fx, float & fy, float & cx, float & cy)
{
#ifdef WITH_FREENECT
	rgb = cv::Mat();
	depth = cv::Mat();
	fx = 0.0f;
	fy = 0.0f;
	cx = 0.0f;
	cy = 0.0f;
	if(ctx_ && freenectDevice_)
	{
		if(freenectDevice_->isRunning())
		{
			freenectDevice_->getData(rgb, depth);
			if(!rgb.empty() && !depth.empty())
			{
				UASSERT(freenectDevice_->getDepthFocal() != 0.0f);
				fx = freenectDevice_->getDepthFocal();
				fy = freenectDevice_->getDepthFocal();
				cx = float(depth.cols/2) - 0.5f;
				cy = float(depth.rows/2) - 0.5f;
			}
		}
		else
		{
			UERROR("CameraFreenect: Re-initialization needed!");
			delete freenectDevice_;
			freenectDevice_ = 0;
		}
	}
#else
	UERROR("CameraFreenect: RTAB-Map is not built with Freenect support!");
#endif
}

//
// CameraFreenect2
//
bool CameraFreenect2::available()
{
#ifdef WITH_FREENECT2
	return true;
#else
	return false;
#endif
}

CameraFreenect2::CameraFreenect2(int deviceId, Type type, float imageRate, const Transform & localTransform) :
		CameraRGBD(imageRate, localTransform),
		deviceId_(deviceId),
		type_(type),
		freenect2_(0),
		dev_(0),
		pipeline_(0),
		listener_(0),
		reg_(0)
{
#ifdef WITH_FREENECT2
	freenect2_ = new libfreenect2::Freenect2();
	switch(type_)
	{
	case kTypeRGBIR:
		listener_ = new libfreenect2::SyncMultiFrameListener(libfreenect2::Frame::Color | libfreenect2::Frame::Ir);
		break;
	case kTypeRGBDepthSD:
	case kTypeRGBDepthHD:
	default:
		listener_ = new libfreenect2::SyncMultiFrameListener(libfreenect2::Frame::Color  | libfreenect2::Frame::Depth);
		break;
	}

#ifdef LIBFREENECT2_WITH_OPENGL_SUPPORT
	pipeline_ = new libfreenect2::OpenGLPacketPipeline();
#else
#ifdef LIBFREENECT2_WITH_OPENCL_SUPPORT
	pipeline_ = new libfreenect2::OpenCLPacketPipeline();
#else
	pipeline_ = new libfreenect2::CpuPacketPipeline();
#endif
#endif
	//default
	//MinDepth(0.5f),
	//MaxDepth(4.5f),
	//EnableBilateralFilter(true),
	//EnableEdgeAwareFilter(true)
	libfreenect2::DepthPacketProcessor::Config config;
	config.EnableBilateralFilter = true;
	config.EnableEdgeAwareFilter = true;
	config.MinDepth = 0.1;
	config.MaxDepth = 12;
	pipeline_->getDepthPacketProcessor()->setConfiguration(config);

#endif
}

CameraFreenect2::~CameraFreenect2()
{
#ifdef WITH_FREENECT2
	if(dev_)
	{
		dev_->stop();
		dev_->close();
	}
	if(listener_)
	{
		delete listener_;
	}

	if(reg_)
	{
		delete reg_;
		reg_ = 0;
	}
	// commented, it seems released in freenect2_
	//if(pipeline_)
	//{
	//	delete pipeline_;
	//}

	if(freenect2_)
	{
		delete freenect2_;
	}
	UDEBUG("");
#endif
}

bool CameraFreenect2::init(const std::string & calibrationFolder)
{
#ifdef WITH_FREENECT2
	if(dev_)
	{
		dev_->stop();
		dev_->close();
		dev_ = 0;
	}

	if(reg_)
	{
		delete reg_;
		reg_ = 0;
	}

	if(deviceId_ <= 0)
	{
		dev_ = freenect2_->openDefaultDevice(pipeline_);
	}
	else
	{
		dev_ = freenect2_->openDevice(deviceId_, pipeline_);
	}

	if(dev_)
	{
		dev_->setColorFrameListener(listener_);
		dev_->setIrAndDepthFrameListener(listener_);

		dev_->start();

		UINFO("CameraFreenect2: device serial: %s", dev_->getSerialNumber().c_str());
		UINFO("CameraFreenect2: device firmware: %s", dev_->getFirmwareVersion().c_str());

		//default registration params
		libfreenect2::Freenect2Device::IrCameraParams depthParams = dev_->getIrCameraParams();
		libfreenect2::Freenect2Device::ColorCameraParams colorParams = dev_->getColorCameraParams();
		reg_ = new libfreenect2::Registration(&depthParams, &colorParams);

		// look for calibration files
		if(!calibrationFolder.empty())
		{
			if(!stereoModel_.load(calibrationFolder, dev_->getSerialNumber()))
			{
				UWARN("Missing calibration files for camera \"%s\" in \"%s\" folder, default calibration used.",
						dev_->getSerialNumber().c_str(), calibrationFolder.c_str());
			}
			else
			{
				// downscale color image by 2
				cv::Mat colorP = stereoModel_.right().P();
				cv::Size colorSize = stereoModel_.right().imageSize();
				if(type_ == kTypeRGBDepthSD)
				{
					colorP.at<double>(0,0)/=2.0f; //fx
					colorP.at<double>(1,1)/=2.0f; //fy
					colorP.at<double>(0,2)/=2.0f; //cx
					colorP.at<double>(1,2)/=2.0f; //cy
					colorSize.width/=2;
					colorSize.height/=2;
				}
				cv::Mat depthP = stereoModel_.left().P();
				cv::Size depthSize = stereoModel_.left().imageSize();
				float ratioY = float(colorSize.height)/float(depthSize.height);
				float ratioX = float(colorSize.width)/float(depthSize.width);
				depthP.at<double>(0,0)*=ratioX; //fx
				depthP.at<double>(1,1)*=ratioY; //fy
				depthP.at<double>(0,2)*=ratioX; //cx
				depthP.at<double>(1,2)*=ratioY; //cy
				depthSize.width*=ratioX;
				depthSize.height*=ratioY;
				const CameraModel & l = stereoModel_.left();
				const CameraModel & r = stereoModel_.right();
				stereoModel_ = StereoCameraModel(stereoModel_.name(),
						depthSize, l.K(), l.D(), l.R(), depthP,
						colorSize, r.K(), r.D(), r.R(), colorP,
						stereoModel_.R(), stereoModel_.T(), stereoModel_.E(), stereoModel_.F());
			}
		}

		return true;
	}
	else
	{
		UERROR("CameraFreenect2: no device connected or failure opening the default one!");
	}
#else
	UERROR("CameraFreenect2: RTAB-Map is not built with Freenect2 support!");
#endif
	return false;
}

bool CameraFreenect2::isCalibrated() const
{
	return true;
}

std::string CameraFreenect2::getSerial() const
{
#ifdef WITH_FREENECT2
	if(dev_)
	{
		return dev_->getSerialNumber();
	}
#endif
	return "";
}

void CameraFreenect2::captureImage(cv::Mat & rgb, cv::Mat & depth, float & fx, float & fy, float & cx, float & cy)
{
#ifdef WITH_FREENECT2
	rgb = cv::Mat();
	depth = cv::Mat();
	fx = 0.0f;
	fy = 0.0f;
	cx = 0.0f;
	cy = 0.0f;
	if(dev_ && listener_)
	{
		libfreenect2::FrameMap frames;
		if(listener_->waitForNewFrame(frames, 1000))
		{
			libfreenect2::Frame *rgbFrame = 0;
			libfreenect2::Frame *irFrame = 0;
			libfreenect2::Frame *depthFrame = 0;

			switch(type_)
			{
			case kTypeRGBIR:
				rgbFrame = uValue(frames, libfreenect2::Frame::Color, (libfreenect2::Frame*)0);
				irFrame = uValue(frames, libfreenect2::Frame::Ir, (libfreenect2::Frame*)0);
				break;
			case kTypeRGBDepthSD:
			case kTypeRGBDepthHD:
			default:
				rgbFrame = uValue(frames, libfreenect2::Frame::Color, (libfreenect2::Frame*)0);
				depthFrame = uValue(frames, libfreenect2::Frame::Depth, (libfreenect2::Frame*)0);
				break;
			}

			cv::Mat rgbMat(rgbFrame->height, rgbFrame->width, CV_8UC3, rgbFrame->data);
			cv::flip(rgbMat, rgb, 1);

			if(stereoModel_.isValid())
			{
				//rectify color
				rgb = stereoModel_.right().rectifyImage(rgb);
				if(irFrame)
				{
					//rectify IR
					cv::Mat(irFrame->height, irFrame->width, CV_32FC1, irFrame->data).convertTo(depth, CV_16U, 1);
					cv::flip(depth, depth, 1);
					depth = stereoModel_.left().rectifyImage(depth);
				}
				else
				{
					//rectify depth
					cv::Mat(depthFrame->height, depthFrame->width, CV_32FC1, depthFrame->data).convertTo(depth, CV_16U, 1);
					cv::flip(depth, depth, 1);
					depth = stereoModel_.left().rectifyDepth(depth);

					bool registered = true;
					if(registered)
					{
						depth = util3d::registerDepth(
								depth,
								stereoModel_.left().P().colRange(0,3).rowRange(0,3), //scaled depth K
								stereoModel_.right().P().colRange(0,3).rowRange(0,3), //scaled color K
								stereoModel_.transform());
						util3d::fillRegisteredDepthHoles(depth, true, false);
						fx = stereoModel_.right().fx();
						fy = stereoModel_.right().fy();
						cx = stereoModel_.right().cx();
						cy = stereoModel_.right().cy();
					}
					else
					{
						fx = stereoModel_.left().fx();
						fy = stereoModel_.left().fy();
						cx = stereoModel_.left().cx();
						cy = stereoModel_.left().cy();
					}
				}
			}
			else
			{
				//use data from libfreenect2
				if(irFrame)
				{
					cv::Mat(irFrame->height, irFrame->width, CV_32FC1, irFrame->data).convertTo(depth, CV_16U, 1);
				}
				else
				{
					cv::Mat(depthFrame->height, depthFrame->width, CV_32FC1, depthFrame->data).convertTo(depth, CV_16U, 1);

					//registration of the depth
					if(reg_)
					{
						if(type_ == kTypeRGBDepthSD)
						{
							cv::Mat tmp;
							cv::resize(rgb, tmp, cv::Size(), 0.5, 0.5, cv::INTER_AREA);
							rgb = tmp;
						}
						cv::Mat depthFrameMat = cv::Mat(depthFrame->height, depthFrame->width, CV_32FC1, depthFrame->data);
						depth = cv::Mat::zeros(rgb.rows, rgb.cols, CV_16U);
						for(int dx=0; dx<depthFrameMat.cols-1; ++dx)
						{
							for(int dy=0; dy<depthFrameMat.rows-1; ++dy)
							{
								float dz = depthFrameMat.at<float>(dy,dx);
								float dz1 = depthFrameMat.at<float>(dy,dx+1);
								float dz2 = depthFrameMat.at<float>(dy+1,dx);
								float dz3 = depthFrameMat.at<float>(dy+1,dx+1);
								if(dz && dz1 && dz2 && dz3)
								{
									float avg = (dz + dz1 + dz2 + dz3) / 4;
									float thres = 0.01 * avg;
									if( fabs(dz - avg) < thres &&
										fabs(dz1 - avg) < thres &&
										fabs(dz2 - avg) < thres &&
										fabs(dz3 - avg) < thres)
									{
										float cx=-1,cy=-1;
										reg_->apply(dx, dy, dz, cx, cy);
										if(type_==kTypeRGBDepthSD)
										{
											cx/=2.0f;
											cy/=2.0f;
										}
										int rcx = cvRound(cx);
										int rcy = cvRound(cy);
										if(uIsInBounds(rcx, 0, depth.cols) && uIsInBounds(rcy, 0, depth.rows))
										{
											unsigned short & zReg = depth.at<unsigned short>(rcy, rcx);
											if(zReg == 0 || zReg > (unsigned short)dz)
											{
												zReg = (unsigned short)dz;
											}
										}
									}
								}
							}
						}
						util3d::fillRegisteredDepthHoles(depth, true, true, type_==kTypeRGBDepthHD);
						util3d::fillRegisteredDepthHoles(depth, type_==kTypeRGBDepthSD, type_==kTypeRGBDepthHD);//second pass
						libfreenect2::Freenect2Device::ColorCameraParams params = dev_->getColorCameraParams();
						fx = params.fx*(type_==kTypeRGBDepthSD?0.5:1.0f);
						fy = params.fy*(type_==kTypeRGBDepthSD?0.5:1.0f);
						cx = params.cx*(type_==kTypeRGBDepthSD?0.5:1.0f);
						cy = params.cy*(type_==kTypeRGBDepthSD?0.5:1.0f);
					}
					else
					{
						libfreenect2::Freenect2Device::IrCameraParams params = dev_->getIrCameraParams();
						fx = params.fx;
						fy = params.fy;
						cx = params.cx;
						cy = params.cy;
					}
				}
				cv::flip(depth, depth, 1);
			}
			listener_->release(frames);
		}
		else
		{
			UWARN("CameraFreenect2: Failed to get frames! rtabmap should link on libusb of "
					"libfreenect2, this can be done by setting LD_LIBRARY_PATH to "
					"\"libfreenect2/depends/libusb/lib\"");
		}
	}
#else
	UERROR("CameraFreenect2: RTAB-Map is not built with Freenect2 support!");
#endif
}

//
// CameraStereoDC1394
// Inspired from ROS camera1394stereo package
//

#ifdef WITH_DC1394
class DC1394Device
{
public:
	DC1394Device() :
		camera_(0),
		context_(0)
	{

	}
	~DC1394Device()
	{
		if (camera_)
		{
			if (DC1394_SUCCESS != dc1394_video_set_transmission(camera_, DC1394_OFF) ||
				DC1394_SUCCESS != dc1394_capture_stop(camera_))
			{
				UWARN("unable to stop camera");
			}

			// Free resources
			dc1394_capture_stop(camera_);
			dc1394_camera_free(camera_);
			camera_ = NULL;
		}
		if(context_)
		{
			dc1394_free(context_);
			context_ = NULL;
		}
	}

	const std::string & guid() const {return guid_;}

	bool init()
	{
		if(camera_)
		{
			// Free resources
			dc1394_capture_stop(camera_);
			dc1394_camera_free(camera_);
			camera_ = NULL;
		}

		// look for a camera
		int err;
		if(context_ == NULL)
		{
			context_ = dc1394_new ();
			if (context_ == NULL)
			{
				UERROR(    "Could not initialize dc1394_context.\n"
				"Make sure /dev/raw1394 exists, you have access permission,\n"
				"and libraw1394 development package is installed.");
				return false;
			}
		}

		dc1394camera_list_t *list;
		err = dc1394_camera_enumerate(context_, &list);
		if (err != DC1394_SUCCESS)
		{
			UERROR("Could not get camera list");
			return false;
		}

		if (list->num == 0)
		{
			UERROR("No cameras found");
			dc1394_camera_free_list (list);
			return false;
		}
		uint64_t guid = list->ids[0].guid;
		dc1394_camera_free_list (list);

		// Create a camera
		camera_ = dc1394_camera_new (context_, guid);
		if (!camera_)
		{
			UERROR("Failed to initialize camera with GUID [%016lx]", guid);
			return false;
		}

		uint32_t value[3];
		value[0]= camera_->guid & 0xffffffff;
		value[1]= (camera_->guid >>32) & 0x000000ff;
		value[2]= (camera_->guid >>40) & 0xfffff;
		guid_ = uFormat("%06x%02x%08x", value[2], value[1], value[0]);

		UINFO("camera model: %s %s", camera_->vendor, camera_->model);

		// initialize camera
		// Enable IEEE1394b mode if the camera and bus support it
		bool bmode = camera_->bmode_capable;
		if (bmode
			&& (DC1394_SUCCESS !=
			dc1394_video_set_operation_mode(camera_,
									DC1394_OPERATION_MODE_1394B)))
		{
			bmode = false;
			UWARN("failed to set IEEE1394b mode");
		}

		// start with highest speed supported
		dc1394speed_t request = DC1394_ISO_SPEED_3200;
		int rate = 3200;
		if (!bmode)
		{
			// not IEEE1394b capable: so 400Mb/s is the limit
			request = DC1394_ISO_SPEED_400;
			rate = 400;
		}

		// round requested speed down to next-lower defined value
		while (rate > 400)
		{
			if (request <= DC1394_ISO_SPEED_MIN)
			{
				// get current ISO speed of the device
				dc1394speed_t curSpeed;
				if (DC1394_SUCCESS == dc1394_video_get_iso_speed(camera_, &curSpeed) && curSpeed <= DC1394_ISO_SPEED_MAX)
				{
					// Translate curSpeed back to an int for the parameter
					// update, works as long as any new higher speeds keep
					// doubling.
					request = curSpeed;
					rate = 100 << (curSpeed - DC1394_ISO_SPEED_MIN);
				}
				else
				{
					UWARN("Unable to get ISO speed; assuming 400Mb/s");
					rate = 400;
					request = DC1394_ISO_SPEED_400;
				}
				break;
			}
			// continue with next-lower possible value
			request = (dc1394speed_t) ((int) request - 1);
			rate = rate / 2;
		}

		// set the requested speed
		if (DC1394_SUCCESS != dc1394_video_set_iso_speed(camera_, request))
		{
			UERROR("Failed to set iso speed");
			return false;
		}

		// set video mode
		dc1394video_modes_t vmodes;
		err = dc1394_video_get_supported_modes(camera_, &vmodes);
		if (err != DC1394_SUCCESS)
		{
			UERROR("unable to get supported video modes");
			return (dc1394video_mode_t) 0;
		}

		// see if requested mode is available
		bool found = false;
		dc1394video_mode_t videoMode = DC1394_VIDEO_MODE_FORMAT7_3; // bumblebee
		for (uint32_t i = 0; i < vmodes.num; ++i)
		{
			if (vmodes.modes[i] == videoMode)
			{
				found = true;
			}
		}
		if(!found)
		{
			UERROR("unable to get video mode %d", videoMode);
			return false;
		}

		if (DC1394_SUCCESS != dc1394_video_set_mode(camera_, videoMode))
		{
			UERROR("Failed to set video mode %d", videoMode);
			return false;
		}

		// special handling for Format7 modes
		if (dc1394_is_video_mode_scalable(videoMode) == DC1394_TRUE)
		{
			if (DC1394_SUCCESS != dc1394_format7_set_color_coding(camera_, videoMode, DC1394_COLOR_CODING_RAW16))
			{
				UERROR("Could not set color coding");
				return false;
			}
			uint32_t packetSize;
			if (DC1394_SUCCESS != dc1394_format7_get_recommended_packet_size(camera_, videoMode, &packetSize))
			{
				UERROR("Could not get default packet size");
				return false;
			}

			if (DC1394_SUCCESS != dc1394_format7_set_packet_size(camera_, videoMode, packetSize))
			{
				UERROR("Could not set packet size");
				return false;
			}
		}
		else
		{
			UERROR("Video is not in mode scalable");
		}

		// start the device streaming data
		// Set camera to use DMA, improves performance.
		if (DC1394_SUCCESS != dc1394_capture_setup(camera_, 4, DC1394_CAPTURE_FLAGS_DEFAULT))
		{
			UERROR("Failed to open device!");
			return false;
		}

		// Start transmitting camera data
		if (DC1394_SUCCESS != dc1394_video_set_transmission(camera_, DC1394_ON))
		{
			UERROR("Failed to start device!");
			return false;
		}

		return true;
	}

	bool getImages(cv::Mat & left, cv::Mat & right)
	{
		if(camera_)
		{
			dc1394video_frame_t * frame = NULL;
			UDEBUG("[%016lx] waiting camera", camera_->guid);
			dc1394_capture_dequeue (camera_, DC1394_CAPTURE_POLICY_WAIT, &frame);
			if (!frame)
			{
				UERROR("Unable to capture frame");
				return false;
			}
			dc1394video_frame_t frame1 = *frame;
			// deinterlace frame into two images one on top the other
			size_t frame1_size = frame->total_bytes;
			frame1.image = (unsigned char *) malloc(frame1_size);
			frame1.allocated_image_bytes = frame1_size;
			frame1.color_coding = DC1394_COLOR_CODING_RAW8;
			int err = dc1394_deinterlace_stereo_frames(frame, &frame1, DC1394_STEREO_METHOD_INTERLACED);
			if (err != DC1394_SUCCESS)
			{
				free(frame1.image);
				dc1394_capture_enqueue(camera_, frame);
				UERROR("Could not extract stereo frames");
				return false;
			}

			uint8_t* capture_buffer = reinterpret_cast<uint8_t *>(frame1.image);
			UASSERT(capture_buffer);

			cv::Mat image(frame->size[1], frame->size[0], CV_8UC3);
			cv::Mat image2 = image.clone();

			//DC1394_COLOR_CODING_RAW16:
			//DC1394_COLOR_FILTER_BGGR
			cv::cvtColor(cv::Mat(frame->size[1], frame->size[0], CV_8UC1, capture_buffer), left, CV_BayerRG2BGR);
			cv::cvtColor(cv::Mat(frame->size[1], frame->size[0], CV_8UC1, capture_buffer+image.total()), right, CV_BayerRG2GRAY);

			dc1394_capture_enqueue(camera_, frame);

			free(frame1.image);

			return true;
		}
		return false;
	}

private:
	dc1394camera_t *camera_;
	dc1394_t *context_;
	std::string guid_;
};
#endif

bool CameraStereoDC1394::available()
{
#ifdef WITH_DC1394
	return true;
#else
	return false;
#endif
}

CameraStereoDC1394::CameraStereoDC1394(float imageRate, const Transform & localTransform) :
		CameraRGBD(imageRate, localTransform),
		device_(0)
{
#ifdef WITH_DC1394
	device_ = new DC1394Device();
#endif
}

CameraStereoDC1394::~CameraStereoDC1394()
{
#ifdef WITH_DC1394
	if(device_)
	{
		delete device_;
	}
#endif
}

bool CameraStereoDC1394::init(const std::string & calibrationFolder)
{
#ifdef WITH_DC1394
	if(device_)
	{
		bool ok = device_->init();
		if(ok)
		{
			// look for calibration files
			if(!calibrationFolder.empty())
			{
				if(!stereoModel_.load(calibrationFolder, device_->guid()))
				{
					UWARN("Missing calibration files for camera \"%s\" in \"%s\" folder, you should calibrate the camera!",
							device_->guid().c_str(), calibrationFolder.c_str());
				}
				else
				{
					UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f",
							stereoModel_.left().fx(),
							stereoModel_.left().cx(),
							stereoModel_.left().cy(),
							stereoModel_.baseline());
				}
			}
		}
		return ok;
	}
#else
	UERROR("CameraDC1394: RTAB-Map is not built with dc1394 support!");
#endif
	return false;
}

bool CameraStereoDC1394::isCalibrated() const
{
	return stereoModel_.isValid();
}

std::string CameraStereoDC1394::getSerial() const
{
#ifdef WITH_DC1394
	if(device_)
	{
		return device_->guid();
	}
#endif
	return "";
}

void CameraStereoDC1394::captureImage(cv::Mat & left, cv::Mat & right, float & fx, float & baseline, float & cx, float & cy)
{
#ifdef WITH_DC1394
	left = cv::Mat();
	right = cv::Mat();
	fx = 0.0f;
	baseline = 0.0f;
	cx = 0.0f;
	cy = 0.0f;
	if(device_)
	{
		device_->getImages(left, right);

		// Rectification
		left = stereoModel_.left().rectifyImage(left);
		right = stereoModel_.right().rectifyImage(right);
		fx = stereoModel_.left().fx();
		cx = stereoModel_.left().cx();
		cy = stereoModel_.left().cy();
		baseline = stereoModel_.baseline();
	}
#else
	UERROR("CameraDC1394: RTAB-Map is not built with dc1394 support!");
#endif
}

//
// CameraTriclops
//
CameraStereoFlyCapture2::CameraStereoFlyCapture2(float imageRate, const Transform & localTransform) :
		CameraRGBD(imageRate, localTransform),
		camera_(0),
		triclopsCtx_(0)
{
#ifdef WITH_FLYCAPTURE2
	camera_ = new FlyCapture2::Camera();
#endif
}

CameraStereoFlyCapture2::~CameraStereoFlyCapture2()
{
#ifdef WITH_FLYCAPTURE2
	// Close the camera
	camera_->StopCapture();
	camera_->Disconnect();

	// Destroy the Triclops context
	triclopsDestroyContext( triclopsCtx_ ) ;

	delete camera_;
#endif
}

bool CameraStereoFlyCapture2::available()
{
#ifdef WITH_FLYCAPTURE2
	return true;
#else
	return false;
#endif
}

bool CameraStereoFlyCapture2::init(const std::string & calibrationFolder)
{
#ifdef WITH_FLYCAPTURE2
	if(camera_)
	{
		// Close the camera
		camera_->StopCapture();
		camera_->Disconnect();
	}
	if(triclopsCtx_)
	{
		triclopsDestroyContext(triclopsCtx_);
		triclopsCtx_ = 0;
	}

	// connect camera
	FlyCapture2::Error fc2Error = camera_->Connect();
	if(fc2Error != FlyCapture2::PGRERROR_OK)
	{
		UERROR("Failed to connect the camera.");
		return false;
	}

	// configure camera
	Fc2Triclops::StereoCameraMode mode = Fc2Triclops::TWO_CAMERA_NARROW;
	if(Fc2Triclops::setStereoMode(*camera_, mode ))
	{
		UERROR("Failed to set stereo mode.");
		return false;
	}

	// generate the Triclops context
	FlyCapture2::CameraInfo camInfo;
	if(camera_->GetCameraInfo(&camInfo) != FlyCapture2::PGRERROR_OK)
	{
		UERROR("Failed to get camera info.");
		return false;
	}

	float dummy;
	unsigned packetSz;
	FlyCapture2::Format7ImageSettings imageSettings;
	int maxWidth = 640;
	int maxHeight = 480;
	if(camera_->GetFormat7Configuration(&imageSettings, &packetSz, &dummy) == FlyCapture2::PGRERROR_OK)
	{
		maxHeight = imageSettings.height;
		maxWidth = imageSettings.width;
	}

	// Get calibration from th camera
	if(Fc2Triclops::getContextFromCamera(camInfo.serialNumber, &triclopsCtx_))
	{
		UERROR("Failed to get calibration from the camera.");
		return false;
	}

	float fx, cx, cy, baseline;
	triclopsGetFocalLength(triclopsCtx_, &fx);
	triclopsGetImageCenter(triclopsCtx_, &cy, &cx);
	triclopsGetBaseline(triclopsCtx_, &baseline);
	UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f", fx, cx, cy, baseline);

	triclopsSetCameraConfiguration(triclopsCtx_, TriCfg_2CAM_HORIZONTAL_NARROW );
	UASSERT(triclopsSetResolutionAndPrepare(triclopsCtx_, maxHeight, maxWidth, maxHeight, maxWidth) == Fc2Triclops::ERRORTYPE_OK);

	if(camera_->StartCapture() != FlyCapture2::PGRERROR_OK)
	{
		UERROR("Failed to start capture.");
		return false;
	}

	return true;
#else
	UERROR("CameraStereoFlyCapture2: RTAB-Map is not built with Triclops support!");
#endif
	return false;
}

bool CameraStereoFlyCapture2::isCalibrated() const
{
#ifdef WITH_FLYCAPTURE2
	if(triclopsCtx_)
	{
		float fx, cx, cy, baseline;
		triclopsGetFocalLength(triclopsCtx_, &fx);
		triclopsGetImageCenter(triclopsCtx_, &cy, &cx);
		triclopsGetBaseline(triclopsCtx_, &baseline);
		return fx > 0.0f && cx > 0.0f && cy > 0.0f && baseline > 0.0f;
	}
#endif
	return false;
}

std::string CameraStereoFlyCapture2::getSerial() const
{
#ifdef WITH_FLYCAPTURE2
	if(camera_ && camera_->IsConnected())
	{
		FlyCapture2::CameraInfo camInfo;
		if(camera_->GetCameraInfo(&camInfo) == FlyCapture2::PGRERROR_OK)
		{
			return uNumber2Str(camInfo.serialNumber);
		}
	}
#endif
	return "";
}

// struct containing image needed for processing
#ifdef WITH_FLYCAPTURE2
struct ImageContainer
{
	FlyCapture2::Image tmp[2];
    FlyCapture2::Image unprocessed[2];
} ;
#endif

void CameraStereoFlyCapture2::captureImage(cv::Mat & left, cv::Mat & right, float & fx, float & baseline, float & cx, float & cy)
{
#ifdef WITH_FLYCAPTURE2
	left = cv::Mat();
	right = cv::Mat();
	fx = 0.0f;
	baseline = 0.0f;
	cx = 0.0f;
	cy = 0.0f;

	if(camera_ && triclopsCtx_ && camera_->IsConnected())
	{
		// grab image from camera.
		// this image contains both right and left images
		FlyCapture2::Image grabbedImage;
		if(camera_->RetrieveBuffer(&grabbedImage) == FlyCapture2::PGRERROR_OK)
		{
			// right and left image extracted from grabbed image
			ImageContainer imageCont;

			// generate triclops input from grabbed image
			FlyCapture2::Image imageRawRight;
			FlyCapture2::Image imageRawLeft;
			FlyCapture2::Image * unprocessedImage = imageCont.unprocessed;

			// Convert the pixel interleaved raw data to de-interleaved and color processed data
			if(Fc2Triclops::unpackUnprocessedRawOrMono16Image(
										   grabbedImage,
										   true /*assume little endian*/,
										   imageRawLeft /* right */,
										   imageRawRight /* left */) == Fc2Triclops::ERRORTYPE_OK)
			{
				// convert to color
				FlyCapture2::Image srcImgRightRef(imageRawRight);
				FlyCapture2::Image srcImgLeftRef(imageRawLeft);

				bool ok = true;;
				if ( srcImgRightRef.SetColorProcessing(FlyCapture2::HQ_LINEAR) != FlyCapture2::PGRERROR_OK ||
				     srcImgLeftRef.SetColorProcessing(FlyCapture2::HQ_LINEAR) != FlyCapture2::PGRERROR_OK)
				{
					ok = false;
				}

				if(ok)
				{
					FlyCapture2::Image imageColorRight;
					FlyCapture2::Image imageColorLeft;
					if ( srcImgRightRef.Convert(FlyCapture2::PIXEL_FORMAT_MONO8, &imageColorRight) != FlyCapture2::PGRERROR_OK ||
						 srcImgLeftRef.Convert(FlyCapture2::PIXEL_FORMAT_BGRU, &imageColorLeft) != FlyCapture2::PGRERROR_OK)
					{
						ok = false;
					}

					if(ok)
					{
						//RECTIFY RIGHT
						TriclopsInput triclopsColorInputs;
						triclopsBuildRGBTriclopsInput(
							grabbedImage.GetCols(),
							grabbedImage.GetRows(),
							imageColorRight.GetStride(),
							(unsigned long)grabbedImage.GetTimeStamp().seconds,
							(unsigned long)grabbedImage.GetTimeStamp().microSeconds,
							imageColorRight.GetData(),
							imageColorRight.GetData(),
							imageColorRight.GetData(),
							&triclopsColorInputs);

						triclopsRectify(triclopsCtx_, const_cast<TriclopsInput *>(&triclopsColorInputs) );
						// Retrieve the rectified image from the triclops context
						TriclopsImage rectifiedImage;
						triclopsGetImage( triclopsCtx_,
							TriImg_RECTIFIED,
							TriCam_REFERENCE,
							&rectifiedImage );

						right = cv::Mat(rectifiedImage.nrows, rectifiedImage.ncols, CV_8UC1, rectifiedImage.data).clone();

						//RECTIFY LEFT COLOR
						triclopsBuildPackedTriclopsInput(
							grabbedImage.GetCols(),
							grabbedImage.GetRows(),
							imageColorLeft.GetStride(),
							(unsigned long)grabbedImage.GetTimeStamp().seconds,
							(unsigned long)grabbedImage.GetTimeStamp().microSeconds,
							imageColorLeft.GetData(),
							&triclopsColorInputs );

						cv::Mat pixelsLeftBuffer( grabbedImage.GetRows(), grabbedImage.GetCols(), CV_8UC4);
						TriclopsPackedColorImage colorImage;
						triclopsSetPackedColorImageBuffer(
							triclopsCtx_,
							TriCam_LEFT,
							(TriclopsPackedColorPixel*)pixelsLeftBuffer.data );

						triclopsRectifyPackedColorImage(
							triclopsCtx_,
							TriCam_LEFT,
							&triclopsColorInputs,
							&colorImage );

						cv::cvtColor(pixelsLeftBuffer, left, CV_RGBA2RGB);

						// Set calibration stuff
						triclopsGetFocalLength(triclopsCtx_, &fx);
						triclopsGetImageCenter(triclopsCtx_, &cy, &cx);
						triclopsGetBaseline(triclopsCtx_, &baseline);
					}
				}
			}
		}
	}

#else
	UERROR("CameraStereoFlyCapture2: RTAB-Map is not built with Triclops support!");
#endif
}

} // namespace rtabmap


text:
<bill session="110" type="h" number="3190" updated="2009-01-08T23:29:25-05:00">
	<status><introduced date="1185422400" datetime="2007-07-26"/></status>

	<introduced date="1185422400" datetime="2007-07-26"/>
	<titles>
		<title type="short" as="introduced">Opt Out of Iraq War Act of 2007</title>
		<title type="official" as="introduced">To amend the Internal Revenue Code of 1986 to allow individuals to designate that their income, estate, or gift tax payments be spent other than for purposes of supporting the war in Iraq and to provide that amounts so designated shall be used to provide funding for Head Start, to reduce the national debt, and to provide college funding for children of Iraq war veterans.</title>
	</titles>
	<sponsor id="400416"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1185422400" datetime="2007-07-26"><text>Referred to the Committee on Ways and Means, and in addition to the Committee on Education and Labor, for a period to be subsequently determined by the Speaker, in each case for consideration of such provisions as fall within the jurisdiction of the committee concerned.</text></action>
		<action date="1185422400" datetime="2007-07-26"><text>Referred to House Ways and Means</text></action>
		<action date="1185422400" datetime="2007-07-26"><text>Referred to House Education and Labor</text></action>
		<action date="1190174400" datetime="2007-09-19"><committee name="House Education and Labor"/><text>Referred to the Subcommittee on Early Childhood, Elementary, and Secondary Education.</text></action>
		<action date="1190174400" datetime="2007-09-19"><committee name="House Education and Labor"/><text>Referred to the Subcommittee on Higher Education, Lifelong Learning, and Competitiveness.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	7/26/2007--Introduced.
Opt Out of Iraq War Act of 2007 - Amends the Internal Revenue Code of 1986 to allow taxpayers to designate that the percentage of their income, estate, or gift tax payments that would otherwise be used to fund the Iraq war be paid into a Future Fund from which funding will be provided, in equal amounts, to the Head Start program, to reduce the national debt, and for a Children of Iraq War Veterans College Fund. Requires amounts in the College Fund to be used to pay the college costs of students that had a parent in the Armed Forces who served in the Iraq war for at least 180 days, died as the result of service in such war, or was hospitalized and unable to return to duty due to such service.

</bill>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace dface\container;

use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;

class FactoryContainerTest extends TestCase
{

	public function testPlainValue() : void
	{
		$c = new FactoryContainer(new ArrayDefinitionSource([
			'a' => 1,
		]));
		self::assertEquals(1, $c->get('a'));
	}

	public function testNewInstances() : void
	{
		$i = 0;
		$c = new FactoryContainer(new ArrayDefinitionSource([
			'a' => static function () use (&$i) {
				return $i++;
			},
		]));
		self::assertEquals(0, $c->get('a'));
		self::assertEquals(1, $c->get('a'));
		self::assertEquals(2, $c->get('a'));
	}

	public function testHasItem() : void
	{
		$c = new FactoryContainer(new ArrayDefinitionSource([
			'a' => static function () {
				return 1;
			},
		]));
		self::assertTrue($c->has('a'));
		self::assertFalse($c->has('b'));
	}

	/**
	 * @throws ContainerException
	 * @throws NotFoundException
	 */
	public function testGetItem() : void
	{
		$c = new FactoryContainer(new ArrayDefinitionSource([
			'a' => static function () {
				return 1;
			},
		]));
		self::assertEquals(1, $c->get('a'));
		$this->expectException(NotFoundException::class);
		$c->get('b');
	}

	/**
	 * @throws ContainerException
	 * @throws NotFoundException
	 */
	public function testCyclicDependency() : void
	{
		$c = new FactoryContainer(new ArrayDefinitionSource([
			'a' => static function (ContainerInterface $c) {
				return $c->get('a');
			},
		]));
		$this->expectException(ContainerException::class);
		$c->get('a');
	}

	public function testLocalLookup() : void
	{
		$i = 1;
		$c = new FactoryContainer(new ArrayDefinitionSource([
			'b' => static function () use (&$i) {
				return $i++;
			},
			'a' => static function (ContainerInterface $c) {
				return $c->get('b');
			},
		]));
		self::assertEquals(1, $c->get('a'));
		self::assertEquals(2, $c->get('a'));
	}

	public function testExternalLookup() : void
	{
		$i = 1;
		$c1 = new FactoryContainer(new ArrayDefinitionSource([
			'a' => static function () use (&$i) {
				return $i++;
			},
		]));
		$c2 = new FactoryContainer(new ArrayDefinitionSource([
			'a' => static function (ContainerInterface $c) {
				return $c->get('a');
			},
		]), $c1);
		self::assertEquals(1, $c2->get('a'));
		self::assertEquals(2, $c2->get('a'));
	}

}


text: This page has a data URL iframe.


text:
/*!
 * Start Bootstrap - Heroic Features HTML Template (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

body {
    padding-top: 70px; /* Required padding for .navbar-fixed-top. Remove if using .navbar-static-top. Change if height of navigation changes. */
}

.hero-spacer {
    margin-top: 30px;
}

.hero-feature {
    margin-bottom: 30px;
}

footer {
    margin: 50px 0;
}

.h1, .h5, .h6, h1, h5, h6 {
    font-family: inherit;
    font-weight: 300;
    line-height: 1.1;
    color: #ffffff !important;

}

.h4, h4.{
    font-weight: 300;
    background-color: #FFFFFF;
}

.h3, h3.{
    font-weight: 300;
}

.h2, h2{
    line-height: 1.1;

}

p {
    display: block;
    -webkit-margin-before: 1em;
    -webkit-margin-after: 1em;
    -webkit-margin-start: 0px;
    -webkit-margin-end: 0px;
}

.thumbnail-1 {
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-image: url('../img/products/product1.png');
    background-repeat:no-repeat;
    background-position: right;
 	display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;
}

.thumbnail-2 {
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-image: url('../img/products/product2.png');
    background-repeat:no-repeat;
    background-position: right;
 	display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;
    /* text-shadow: -1px 0 black, 0 0.2px black, 0.2px 0 black, 0 -0.2px black; */
}

.thumbnail-3 {
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-image: url('../img/products/product3.png');
    background-repeat:no-repeat;
    background-position: right;
 	display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;
}

.thumbnail-4 {
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-image: url('../img/products/product4.png');
    background-repeat:no-repeat;
    background-position: right;
    display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;
}

.thumbnail-5 {
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-image: url('../img/products/product5.png');
    background-repeat:no-repeat;
    background-position: right;
    display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;
}

.thumbnail-6 {
    background-image: url('../img/products/product6.png');
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-repeat:no-repeat;
    background-position: right;
    display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;
}

.thumbnail-7 {
    background-image: url('../img/products/product7.png');
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-repeat:no-repeat;
    background-position: right;
    display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;
}

.thumbnail-8 {
    background-image: url('../img/products/product8.png');
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-repeat:no-repeat;
    background-position: right;
    display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;
}

.thumbnail-9 {
    background-image: url('../img/products/product9.png');
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-repeat:no-repeat;
    background-position: right;
    display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;
}

.thumbnail-10 {
    background-image: url('../img/products/product10.png');
    display: block;
    padding: 4px;
    margin-bottom: 20px;
    line-height: 1.42857143;
    text-align: left;
    padding: 20px 60px 20px 60px;
    background-color: #fff;
    background-repeat:no-repeat;
    background-position: right;
    display: compact;
    border: 0px solid #ddd;
    border-radius: 4px;
    -webkit-transition: border .2s ease-in-out;
    -o-transition: border .2s ease-in-out;
    transition: border .2s ease-in-out;
    color: #FDFDFD;

}

.container {
    width: 90% !important;
}


text:
<!DOCTYPE html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>{{ site.title }} - {{ page.title }}</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="{{ site.description }}">
    {% feed_meta %}
    <link rel="stylesheet" href="{{ "/stylesheets/bootstrap.min.css" | prepend: site.baseurl }}" media="screen">
    <link rel="stylesheet" href='https://fonts.googleapis.com/css?family=Open+Sans:400,700'>
    <link rel="stylesheet" href="{{ "/stylesheets/stylesheet.css" | prepend: site.baseurl }}" media="screen">
    <link rel="stylesheet" href="{{ "/stylesheets/github-light.css" | prepend: site.baseurl }}" media="screen">
    <link rel="stylesheet" href="{{ "/stylesheets/font-awesome.min.css" | prepend: site.baseurl }}">
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body id="page-top" class="index">
    {{ content }}
    <script src="{{ "/scripts/jquery.min.js" | prepend: site.baseurl }}"></script>
    <script src="{{ "/scripts/jquery.easing.min.js" | prepend: site.baseurl }}"></script>
    <script src="{{ "/scripts/bootstrap.min.js" | prepend: site.baseurl }}"></script>
    <script src="{{ "/scripts/page.js" | prepend: site.baseurl }}"></script>
  </body>
</html>


text:
package ananas.waymq.droid.offline;

import com.alibaba.fastjson.JSONObject;

public class SignImpl implements ISign {

	private String _id;
	private String _name;
	private int _count;
	private int _money;
	private long _time;

	public void load(JSONObject json) {
		if (json == null)
			return;
		this._id = json.getString(Key.phone_id);
		this._name = json.getString(Key.nickname);
		this._money = json.getIntValue(Key.amount);
		this._count = json.getIntValue(Key.weight);
		this._time = json.getLongValue(Key.timestamp);
	}

	@Override
	public String id() {
		return this._id;
	}

	@Override
	public String name() {
		return this._name;
	}

	@Override
	public int count() {
		return this._count;
	}

	@Override
	public int money() {
		return this._money;
	}

	@Override
	public long timestamp() {
		return this._time;
	}

}


text:
using UnityEngine;
using System.Collections;

public class RandomizeRotation : MonoBehaviour
{
	void Start ()
	{
	    var eulerAngles = transform.localRotation;
	    var yAmount = Random.Range(20f, 160f);
        transform.localRotation = Quaternion.Euler(eulerAngles.x, yAmount, eulerAngles.z);
	}
}


text:
drop table Users;
drop table Groups;
drop table Group_Members;
drop table Programs;
drop table Program_Members;
drop table Council;
drop table Council_Members;
drop table Programming_Weeks;
drop table Attendance;
drop table Audit;

create table Users (
email varchar(30) not null primary key,
eagle_id int(8) not null,
first_name varchar(30) not null,
last_name varchar(30) not null,
sex varchar(6) not null check(sex in ('Male', 'Female')),
class int(4) not null,
school varchar(4) not null check(school in ('MCAS', 'CSOM', 'CSON', 'LSOE')),
major varchar(70) not null,
minor varchar(70),
hometown varchar(30) not null,
state_country varchar(20) not null,
international varchar(3) not null check(international in ('Yes', 'No')),
ahana varchar(3) not null check(ahana in ('Yes', 'No')),
transfer varchar(3) not null check(transfer in ('Yes', 'No')),
phone varchar(15) not null,
local_address varchar(100),
password varchar(40) not null,
applied_tours int(1),
applied_panels int(1),
applied_council int(1),
applied_summer int(1),
status varchar(25) not null check(status in ('Active', 'Inactive', 'Abroad', 'Prac/Clinical', 'Graduated')),
last_login datetime
);

create table Groups (
	group_id int(10) not null auto_increment primary key,
	group_name varchar(20) not null
);

create table Group_Members (
	group_member_id int(10) not null auto_increment primary key,
	user varchar(30) not null references Users(email),
	group_id int(10) not null references Groups(group_id),
	access varchar(5) not null check(access in ('view', 'edit'))
);

create table Council (
	council_id int(10) not null auto_increment primary key,
	fall_year int(4) not null,
	spring_year int(4) not null
);

create table Council_Members (
	council_member_id int(10) not null auto_increment primary key,
	user varchar(30) not null references Users(email),
	council_id int(10) not null references Council(council_id),
	position varchar(40) not null
);

create table Programs (
	program_id int(10) not null auto_increment primary key,
	program_name varchar(30) not null,
	coordinator int(10) not null references Council_Members(council_member_id),
	semester varchar(6) not null check(semester in('Fall', 'Spring')),
	year int(4) not null,
	requirements text not null
);

create table Program_Members (
	member_id int(10) not null auto_increment primary key,
	user varchar(30) not null references Users(email),
	program int(10) not null references Programs(program_id),
	shift_day varchar(10),
	shift_time varchar(10),
	credit_status varchar(10) not null check(credit_staus in('Complete', 'Pending', 'Incomplete')),
	requirements_status text,
	comments text,
	week_color varchar(6) check(week_color in('Maroon', 'Gold'))
);

create table Programming_Weeks (
	week_id int(10) not null auto_increment primary key,
	week_number int(2) not null,
	semester varchar(6) not null check(semester in('Fall', 'Spring')),
	year int(4) not null,
	current_week varchar(3) not null check(current_week in('Yes', 'No')),
	sunday_date varchar(10) not null,
	monday_date varchar(10) not null,
	tuesday_date varchar(10) not null,
	wednesday_date varchar(10) not null,
	thursday_date varchar(10) not null,
	friday_date varchar(10) not null,
	saturday_date varchar(10) not null
);

create table Attendance (
	attendance_id int(10) not null auto_increment primary key,
	user varchar(30) not null references Users(email),
	program int(10) not null references Programs(program_id),
	present varchar(10) check(present in('Present', 'Excused', 'No Show')),
	week int(10) not null references Programming_Weeks(week_id),
	note varchar(100),
	shift_day varchar(10) not null,
	shift_time varchar(10) not null,
	alternate_number varchar(10),
	gave_panel_tour varchar(3) check(gave_panel_tour in('Yes', 'No')),
	week_color varchar(6) check(week_color in('Maroon', 'Gold'))
);

create table Audit (
	audit_id int(10) not null auto_increment primary key,
	table_value varchar(25) not null,
	field_value varchar(25) not null,
	old_value varchar(70) not null,
	new_value varchar(70) not null,
	updated datetime not null,
	updated_by varchar(30) not null references Users(email)
);

create table Credit_History (
	credit_id int(10) not null auto_increment primary key,
	user varchar(30) not null references Users(email),
	panels int(1) not null,
	tours int(1) not null,
	greeting int(1) not null,
	om int(1) not null,
	efad int(1) not null,
	aed int(1) not null,
	outreach int(1) not null,
	hsvisits int(1) not null,
	ahana int(1) not null,
	io int(1) not null,
	transfer int(1) not null,
	media int(1) not null
);

create table Numbers_Location (
	numbers_location_id int(10) not null auto_increment primary key,
	week int(10) not null references Programming_Weeks(week_id),
	day varchar(10) not null,
	time varchar(15) not null,
	numbers int(3) not null,
	location varchar(50),
	session varchar(50) not null,
	notes varchar(100)
);


text:
package org.ovirt.engine.core.common.queries;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "ImportCandidateTypeEnum")
public enum ImportCandidateTypeEnum {
    VM,
    TEMPLATE;

    public int getValue() {
        return this.ordinal();
    }

    public static ImportCandidateTypeEnum forValue(int value) {
        return values()[value];
    }
}


text:
<?php

use app\core\helpers\Html;
use app\core\helpers\Url;
use app\core\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\modules\shop\models\search\MixRel */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::searchBegin(); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'category_id') ?>

    <?= $form->field($model, 'goods_id') ?>

    <?= $form->field($model, 'mix_id') ?>

    <?= $form->field($model, 'measure') ?>

    <?php // echo $form->field($model, 'type') ?>

    <?php // echo $form->field($model, 'status') ?>

        <?= Html::submitButton('  查找', ['class' => 'btn btn-primary btn-sm']) ?>
        <?= Html::a('  重置',Url::toRoute(['index']),['class'=>'btn btn-danger btn-sm']);?>

    <?php ActiveForm::end(); ?>


text:
class AddUserIdToRecords < ActiveRecord::Migration
  def change
    add_column :records, :user_id, :integer
  end
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>io.github.jhipster-ide.xdocker.dsl</groupId>
		<artifactId>xdockerdsl.parent</artifactId>
		<version>2.3.3-SNAPSHOT</version>
		<relativePath>../xdockerdsl.parent</relativePath>
	</parent>

	<artifactId>xdockerdsl.web</artifactId>
	<name>Xdocker DSL Server WAR</name>
	<packaging>war</packaging>

	<build>
		<sourceDirectory>src</sourceDirectory>
		<resources>
			<resource>
				<directory>src</directory>
				<excludes>
					<exclude>**/*.java</exclude>
					<exclude>**/*.xtend</exclude>
				</excludes>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.eclipse.xtend</groupId>
				<artifactId>xtend-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.3</version>
				<configuration>
					<warSourceDirectory>WebRoot</warSourceDirectory>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>9.4.14.v20181114</version>
				<configuration>
					<webAppSourceDirectory>WebRoot</webAppSourceDirectory>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>build-helper-maven-plugin</artifactId>
				<version>3.0.0</version>
				<executions>
					<execution>
						<id>add-source</id>
						<phase>initialize</phase>
						<goals>
							<goal>add-source</goal>
							<goal>add-resource</goal>
						</goals>
						<configuration>
							<sources>
								<source>src-gen</source>
							</sources>
							<resources>
								<resource>
									<directory>src-gen</directory>
									<excludes>
										<exclude>**/*.java</exclude>
									</excludes>
								</resource>
							</resources>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

	<dependencies>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>xdockerdsl</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>${project.groupId}</groupId>
			<artifactId>xdockerdsl.ide</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.xtext</groupId>
			<artifactId>org.eclipse.xtext.xbase.web</artifactId>
			<version>${xtextVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.xtext</groupId>
			<artifactId>org.eclipse.xtext.web.servlet</artifactId>
			<version>${xtextVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.xtend</groupId>
			<artifactId>org.eclipse.xtend.lib</artifactId>
			<version>${xtextVersion}</version>
		</dependency>
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>requirejs</artifactId>
			<version>2.3.6</version>
		</dependency>
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.4.1</version>
		</dependency>
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>ace</artifactId>
			<version>1.3.3</version>
		</dependency>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-annotations</artifactId>
			<version>9.4.14.v20181114</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>1.7.21</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
</project>


text:
var documentoPaginatedList = function () {

};
documentoPaginatedList.prototype = new pListModule();

documentoPaginatedList.prototype.loadButtons = function (rowValues, strClass) {
    var botonera = "";
    botonera += '

';
    botonera += '';
    botonera += '';
    botonera += '';
    botonera += '';
    botonera += '

';
    return botonera;
};

documentoPaginatedList.prototype.bind = function () {
    pListModule.prototype.bind.call(this);
    $('.btn.btn-default.abc').unbind('click');
    $('.btn.btn-default.abc').click(function (event) {

        ausiasFLOW.getComponentByModuleName('view').strParams['id'] = parseInt($(this).attr('id'));

        //ausiasFLOW.viewModule_paramsObject['id'] = parseInt($(this).attr('id'));
        //ausiasFLOW.flowRender();
        ausiasFLOW.dataRenderFillAndBind(ausiasFLOW.getComponentByModuleName('view'));
        return false;
    });
}


text:
//
//  PXCameraViewController.h
//
//  Created by Daniel Blakemore on 9/17/13.
//
//  Copyright (c) 2015 Pixio
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

#import "PXCamera.h"

#import <PXPinnedRotation/PXPinnedRotationViewController.h>

@interface PXCameraViewController : PXPinnedRotationViewController

/**
 *  Shared singleton view controller to use.
 */
+ (PXCameraViewController*)sharedCamera;

/**
 *  The text for the shutter delay in the camera.  The default is @"shutter delay".
 */
@property (nonatomic) NSString * shutterDelayText;

/**
 *  Get an image using the camera and report back when done.
 *
 *  The completion you specify also takes a completion as an argument.  This second block should be
 *  called when you are ready to dismiss the spinner in the camera.
 *
 *  @param vc         the presenting view controller for the camera
 *  @param completion a completion called with the resulting image, the source, and a block to call when it's complete
 */
+ (void)getImageInViewController:(UIViewController*)vc completion:(void(^)(UIImage*, PXCameraImageSource, void (^completion)()))completion;

/**
 *  Set completion for image capture.  Caller is responsible for navigation stack
 *
 *  @param completion block to call when image is captured
 */
- (void)setCompletion:(void (^)(UIImage*, PXCameraImageSource, void (^completion)()))completion;

- (instancetype)init __attribute__((unavailable("use the singleton")));

@end


text:
<?xml version="1.0" encoding="utf-8"?>

<set xmlns:android="http://schemas.android.com/apk/res/android">
    android:interpolator="@anim/accelerate_interpolator">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0%"
        android:toXDelta="-75%" />
    <alpha
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromAlpha="1.0"
        android:toAlpha="0" />
</set>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

	<title>Basic error handing</title>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>

Add row

Remove Selected Row


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;

namespace Microsoft.AspNet.WebHooks
{
    /// <summary>
    /// Provides context for an incoming WebHook request. The context is passed to registered <see cref="IWebHookHandler"/> implementations
    /// which can process the incoming request accordingly.
    /// </summary>
    public class WebHookHandlerContext
    {
        private List<string> _actions;

        /// <summary>
        /// Initializes a new instance of the <see cref="WebHookHandlerContext"/> with the given set of <paramref name="actions"/>.
        /// </summary>
        public WebHookHandlerContext(IEnumerable<string> actions)
        {
            if (actions == null)
            {
                throw new ArgumentNullException("actions");
            }
            _actions = actions.ToList();
        }

        /// <summary>
        /// Gets or sets a (potentially empty) ID of a particular configuration for this WebHook. This ID can be
        /// used to differentiate between WebHooks from multiple senders registered with the same receiver.
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// Provides the set of actions that caused the WebHook to be fired.
        /// </summary>
        public ICollection<string> Actions
        {
            get
            {
                return _actions;
            }
        }

        /// <summary>
        /// Gets or sets the optional data associated with this WebHook. The data typically represents the
        /// HTTP request entity body of the incoming WebHook but can have been processed in various ways
        /// by the corresponding <see cref="IWebHookReceiver"/>.
        /// </summary>
        public object Data { get; set; }

        /// <summary>
        /// Gets or sets the <see cref="HttpRequestMessage"/> containing the WebHook.
        /// </summary>
        public HttpRequestMessage Request { get; set; }

        /// <summary>
        /// Gets or sets the <see cref="HttpRequestContext"/> for the incoming
        /// </summary>
        public HttpRequestContext RequestContext { get; set; }

        /// <summary>
        /// Gets or sets an optional <see cref="HttpResponseMessage"/> for the WebHook. If set by an <see cref="IWebHookHandler"/>
        /// then the execution of handlers will stop and that response will be used in response to the WebHook request.
        /// If a response is not set then a default HTTP response will be sent.
        /// </summary>
        public HttpResponseMessage Response { get; set; }
    }
}


text:
"""Implementation of the ipaddres-based network types adaptation
"""

# psycopg/_ipaddress.py - Ipaddres-based network types adaptation
#
# Copyright (C) 2016 Daniele Varrazzo  <daniele.varrazzo@gmail.com>
#
# psycopg2 is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# In addition, as a special exception, the copyright holders give
# permission to link this program with the OpenSSL library (or with
# modified versions of OpenSSL that use the same license as OpenSSL),
# and distribute linked combinations including the two.
#
# You must obey the GNU Lesser General Public License in all respects for
# all of the code used other than OpenSSL.
#
# psycopg2 is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
# License for more details.

from psycopg2.extensions import (
    new_type, new_array_type, register_type, register_adapter, QuotedString)

# The module is imported on register_ipaddress
ipaddress = None

# The typecasters are created only once
_casters = None

def register_ipaddress(conn_or_curs=None):
    """
    Register conversion support between `ipaddress` objects and `network types`__.

    :param conn_or_curs: the scope where to register the type casters.
        If `!None` register them globally.

    After the function is called, PostgreSQL :sql:`inet` values will be
    converted into `~ipaddress.IPv4Interface` or `~ipaddress.IPv6Interface`
    objects, :sql:`cidr` values into into `~ipaddress.IPv4Network` or
    `~ipaddress.IPv6Network`.

    .. __: https://www.postgresql.org/docs/current/static/datatype-net-types.html
    """
    global ipaddress
    import ipaddress

    global _casters
    if _casters is None:
        _casters = _make_casters()

    for c in _casters:
        register_type(c, conn_or_curs)

    for t in [ipaddress.IPv4Interface, ipaddress.IPv6Interface,
              ipaddress.IPv4Network, ipaddress.IPv6Network]:
        register_adapter(t, adapt_ipaddress)

def _make_casters():
    inet = new_type((869,), 'INET', cast_interface)
    ainet = new_array_type((1041,), 'INET[]', inet)

    cidr = new_type((650,), 'CIDR', cast_network)
    acidr = new_array_type((651,), 'CIDR[]', cidr)

    return [inet, ainet, cidr, acidr]

def cast_interface(s, cur=None):
    if s is None:
        return None
    # Py2 version force the use of unicode. meh.
    return ipaddress.ip_interface(unicode(s))

def cast_network(s, cur=None):
    if s is None:
        return None
    return ipaddress.ip_network(unicode(s))

def adapt_ipaddress(obj):
    return QuotedString(str(obj))


text:
<!DOCTYPE html>

		<meta charset="utf-8" />
		<base href="../../../" />

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

		[page:Curve] →

[name]

			Create a smooth 3d
			cubic bezier curve,
			defined by a start point, endpoint and two control points.

Example

var curve = new THREE.CubicBezierCurve3(
	new THREE.Vector3( -10, 0, 0 ),
	new THREE.Vector3( -5, 15, 0 ),
	new THREE.Vector3( 20, 15, 0 ),
	new THREE.Vector3( 10, 0, 0 )
);

var points = curve.getPoints( 50 );
var geometry = new THREE.BufferGeometry().setFromPoints( points );

var material = new THREE.LineBasicMaterial( { color : 0xff0000 } );

// Create the final object to add to the scene
var curveObject = new THREE.Line( geometry, material );

Constructor

[name]( [param:Vector3 v0], [param:Vector3 v1], [param:Vector3 v2], [param:Vector3 v3] )

			[page:Vector3 v0] – The starting point.

			[page:Vector3 v1] – The first control point.

			[page:Vector3 v2] – The second control point.

			[page:Vector3 v3] – The ending point.

Properties

See the base [page:Curve] class for common properties.

[property:Boolean isCubicBezierCurve3]

			Used to check whether this or derived classes are CubicBezierCurve3s. Default is *true*.

			You should not change this, as it used internally for optimisation.

[property:Vector2 v0]

The starting point.

[property:Vector2 v1]

The first control point.

[property:Vector2 v2]

The second control point.

[property:Vector2 v3]

The ending point.

Methods

See the base [page:Curve] class for common Methods.

Source

		[link:https://github.com/mrdoob/three.js/blob/master/src/[path].js src/[path].js]


text:
I've noticed that I have a lot of LaTeX code duplication between different versions of my lecture
notes, and so I've made this directory to unify everything, so I only have to access it in one
place. I did something similar for my problem set template, but for notes it's a little more
nuanced: I have the following constraints/goals:

- I would like a "rich base class" that contains all the modifications that I tend to apply to my
  lecture notes, including stylistic modifications.
  	* Ideally, it will be possible to use this class with things like title pages or other
	  modifications ad lib.
	* Since I've taken lecture notes using both the amsart and amsbook document classes, I would
	  like this class to support both an article-like class and a book-like class (so, without
	  chapters and with chapters). This is less essential.
- I would like a "minimal base class" which contains only the macros that I consider necessary for
  live-TeXing, and all of the packages I use to set this up, but with no stylistic changes.
  	* This is a better choice for notes that other people might edit or help write.
	* It's OK if this one only supports a book-like base class.
- I would like to avoid duplicating code.

Given this, I use the following layout:

- `style.tex`, which includes packages and applies settings that produce the typical style of my
   lecture notes.
- `packages.tex`, which includes packages that aren't style-focused, e.g. `inputenc`.
- `macros.tex`, which contains shortcuts I define for ease of TeXing.
	- `xy_macros.tex` for those macros specific to Xy.
	- `letters.tex` will contain shortcuts for commands I use involving \mathbb, \mathcal, \mathscr,
	   etc.
	- `theorems.tex` will contain all definitions of theorem environments.
- A `notes_d` document class, which includes everything.
- A `minnotes_d` document class which includes `macros.tex`.
- A `lightnotes_d` document class which adds a few small personal style changes to `minnotes_d`.
  So far I've been using `lightnotes_d` to take notes in seminars, whereas `notes_d` will be used for classes.

### Current Status

- The class files in this directory can be used in your TeX documents; they were built out of the files in
  the `src/` directory using the Makefile.
- I've used `minnotes_d`, `lightnotes_d`, and `notes_d` extensively and am pretty happy with them.
- I will likely be updating my macros whenever I discover new useful ones.
- `.cls` files are not allowed to include files through relative class names, so in order to share code
  between these classes, I used `cpp` to process these files into the finalized document classes. This
  is obviously out of the intended scope of `cpp`, and so imposes a few quirky constraints on the TeX code,
  but these are surmountable.
- These classes aren't compatible with the `\VerbatimFootnotes` command from the `fancyvrb` command. I do not
  know why this is, but I'll be debugging it.
- If you want to use Hood's [`spectralsequences`](https://github.com/hoodmane/spectralsequences) package, you should
  enable the `no_quotes` option in these document classes, or you'll get difficult-to-Google errors.
- If you need to use the double acute accent `\H{`-`}` (e.g. in the name "Erdős"), you will need to pass the
  `no_redefine_H` option to these document classes. Confusingly, this is still true if you use the `inputenc`
  package to avoid wriitng `\H`. Then you won't be able to use `\H` for the quaternions.
- I also added a package "adamsmacros" for collecting a bunch of TikZ shortcuts I find useful when typesetting
  A(1)-resolutions, etc. Some of these macros are adapted from Agnès Beaudry and Jonathan Campbell's macros in the
  source code of [this paper](https://arxiv.org/abs/1801.07530).


text:
<?php

$this->load->view('templates/header', $bandeau);

echo $titre ;

?>

					<a href="<?php echo base_url('index.php/home/about/');?>" title="<?php echo lang('nav_under_construction') ; ?>"><img src="<?php echo base_url('resource/img/nav/menu_bank.png');?>" width="280" height="110" alt="menu_bank" />

<?php

$this->load->view('templates/footer');


text:
module Spree
  module Blogit
    class Post < ActiveRecord::Base

      self.table_name = "blogit_posts"

      require "kaminari"
      require "acts-as-taggable-on"

      acts_as_taggable
      ActsAsTaggableOn.force_parameterize = true

      self.paginates_per(SpreeBlogit.configuration.posts_per_page)

      # ===============
      # = Validations =
      # ===============

      validates :title, presence: true, length: { minimum: 10, maximum: 66 }

      validates :body,  presence: true, length: { minimum: 10 }

      validates :slug,  presence: true, length: { minimum: 5 }

      validates :description, presence: SpreeBlogit.configuration.show_post_description

      validates :blogger_id, presence: true

      validates :state, presence: true

      # ================
      # = Associations =
      # ================

      ##
      # The blogger (User, Admin, etc.) who wrote this Post
      #
      # Returns a Blogger (polymorphic type)
      belongs_to :blogger, :polymorphic => true

      ##
      # The {Comment Comments} written on this Post
      #
      # Returns an ActiveRecord::Relation instance
      has_many :comments, :class_name => 'Spree::Blogit::Comment'

      # ==========
      # = Scopes =
      # ==========

      scope :for_index, lambda { |page_no = 1|
        active.order("created_at DESC").page(page_no) }

      scope :active, lambda { where(state:  SpreeBlogit.configuration.active_states ) }

      # The posts to be displayed for RSS and XML feeds/sitemaps
      #
      # Returns an ActiveRecord::Relation
      def self.for_feed
        active.order('created_at DESC')
      end

      # Raises ActiveRecord::RecordNotFound if no post found
      def self.active_with_id(title)
        active.find_by!(slug: title)
      end

      # ====================
      # = Instance Methods =
      # ====================

      # TODO: Get published at working properly!
      def published_at
        created_at
      end

      def to_param
        if Spree::Admin
          id
        else
          slug
        end
      end

      # The content of the Post to be shown in the RSS feed.
      #
      # Returns description when Blogit.configuration.show_post_description is true
      # Returns body when Blogit.configuration.show_post_description is false
      def short_body
        if SpreeBlogit.configuration.show_post_description
          description
        else
          body
        end
      end

      def comments
        check_comments_config
        super()
      end

      def comments=(value)
        check_comments_config
        super(value)
      end

      # The blogger who wrote this {Post Post's} display name
      #
      # Returns the blogger's display name as a String if it's set.
      # Returns an empty String if blogger is not present.
      # Raises a ConfigurationError if the method called is not defined on {#blogger}
      def blogger_display_name
        return "" if blogger.blank?
        if blogger.respond_to?(SpreeBlogit.configuration.blogger_display_name_method)
          blogger.send(SpreeBlogit.configuration.blogger_display_name_method)
        else
          method_name = SpreeBlogit.configuration.blogger_display_name_method
          raise SpreeBlogit::ConfigurationError, "#{blogger.class}##{method_name} is not defined"
        end
      end

      # If there's a blogger and that blogger responds to :twitter_username, returns that.
      # Otherwise, returns nil
      def blogger_twitter_username
        if blogger and blogger.respond_to?(:twitter_username)
          blogger.twitter_username
        end
      end

      def self.for_admin_index(page_no)
        page(page_no).order('created_at DESC').per(10)
      end

      private

      def check_comments_config
        unless SpreeBlogit.configuration.include_comments == :active_record
          raise RuntimeError,
            "Posts only allow active record comments (check blogit configuration)"
        end
      end

    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#F0F0F0">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </android.support.v7.widget.RecyclerView>

    </android.support.v4.widget.SwipeRefreshLayout>

</layout>


text:
/// <reference path='fourslash.ts'/>

// References to a property of the apparent type using string indexer

////interface Object {
////    toMyString();
////}
////
////var y: Object;
////y./*1*/toMyString();
////
////var x = {};
////x[/*2*/"toMyString"]();

goTo.marker("1");
verify.referencesCountIs(3);

goTo.marker("2");
verify.referencesCountIs(3);


text:
/*
 * 	Vanuit dit bestand wordt de rest ingeladen.
 * 	Dit bestand zal de verder nodige bestanden inladen.
 *
 * 	Titanium.App.Properties.getInt("BoatWidth", 0) bevat de breedte van de boot
 * 	Wel checken of het niet 0 is (default)
 *
 * 	Titanium.App.Properties.getInt("BoatHeight", null) bevat de hoogte van de boot
 * 	Wel checken of het niet null is (default)
 */
Titanium.include('uiMapView.js'); // kaart pagina
// Alle andere pagina ui's includen
Titanium.include('uiListView.js'); // lijst pagina
//Titanium.include('uiDetailView.js'); // detail pagina

Titanium.include('uiSettingsView.js'); // settings pagina

// Maken van het menu
var tabMenu = Titanium.UI.createTabGroup(); // de container van het menu

// Eerst de verschillende tabs maken:
// De tab voor de kaart
var MapTab = Titanium.UI.createTab({
	icon: Titanium.Platform.osname === 'android' ? 'img/Map.png' : 'img/IMap.png', 	// Het icoontje van de tab
	title: config.kaartTab,			// Naam die op de tab staat
	window: MapWindow 		// bind deze tab aan deze window (Kaart)
});

// De tab voor het lijstje van alle POI's
var ListTab = Titanium.UI.createTab({
	title: config.lijstTab,			// Naam die op de tab staat
	icon: Titanium.Platform.osname === 'android' ? 'img/Lijst.png' : 'img/IList.png',	// Het icoontje van de tab
	window: ListWindow 		// bind deze tab aan deze window (Lijst)
});

// En de tab voor de instellingen
var SettingsTab = Titanium.UI.createTab({
	title: config.optiesTab,		// Naam die op de tab staat
	icon: Titanium.Platform.osname === 'android' ? 'img/Opties.png' : 'img/IOpties.png',// Het icoontje van de tab
	window: SettingsWindow	// bind deze tab aan deze window (Opties)
});

// Toevoegen van elke tab aan het menu
tabMenu.addTab(MapTab); // de tab met de kaart
tabMenu.addTab(ListTab); // de tab met het lijstje
tabMenu.addTab(SettingsTab); // de tab met de instellingen

tabMenu.open(); // Openen van het menu zodat deze onderaan komt te staan