text:
#include <string.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

#ifdef WIN32
#define strncpy strncpy_s
#define strcasecmp _strcmpi

double round(double nr) {
   double f = floor(nr);
   double c = ceil(nr);
   return (((c-nr) >= (nr-f)) ? f :c);
}

#endif

#ifdef LINUX
#include <time.h>
#include <unistd.h>
#include <sys/time.h>
#endif

#ifdef _MSC_VER
#define inline __inline
#endif

#include "com/sbapi.h"
#include "com/sbmessage.h"
#include "com/sbstate.h"

#define D2R(X) ((X)*M_PI/180.0)
#define R2D(X) ((X)*180.0/M_PI)
#define MAX(X,Y) (((X)<(Y))?(Y):(X))
#define MIN(X,Y) (((X)<(Y))?(X):(Y))
#define DEFAULT_TIMEOUT_MS 500

#ifdef WIN32
// Open a serial communication channel to the helicopter.
// Under linux, device may be (for instance) "/dev/tty0" or "/dev/rfcomm0" for
// bluetooth, and baudrate is a define symbol as defined in bit/termios.h (e.g.
// B115200).
// TODO: implement and test under windows/osx
int sbOpenBluetoothCommunication(struct SBControlContext *control,
		const char *port, unsigned int speed)
{
	int res;
	memset(&control->channel, 0, sizeof(SBChannel));
	res = sbChannelCreateBTWin(&control->channel,port,speed);
	if (res) {
		return res;
	}
	res = sbChannelOpen(&control->channel);

	// by default, request acknowledgement
	control->ackMode = SB_MSGID_REQACK;

	return res;
}

// Open a network communication channel to the helicopter.
// This may be used in simulation or possibly to communicate via an on-board
// network-enabled processor.
int sbOpenWinsockCommunication(struct SBControlContext *control,
		const char *hostname, unsigned int port)
{
	int res;
	memset(&control->channel, 0, sizeof(SBChannel));
	res = sbChannelCreateWinsockUDP(&control->channel,hostname,port);
	if (res) {
		return res;
	}
	res = sbChannelOpen(&control->channel);

	// by default, request acknowledgement
	control->ackMode = SB_MSGID_REQACK;

	return res;
}

#else

// Open a serial communication channel to the helicopter.
// Under linux, device may be (for instance) "/dev/tty0" or "/dev/rfcomm0" for
// bluetooth, and baudrate is a define symbol as defined in bit/termios.h (e.g.
// B115200).
// TODO: implement and test under windows/osx
int sbOpenSerialCommunication(struct SBControlContext *control,
		const char *device, unsigned int baudrate, int rtscts)
{
	int res;
	bzero(&control->channel, sizeof(SBChannel));
	res = sbChannelCreateSerial(&control->channel,device,baudrate,rtscts);
	if (res) {
		return res;
	}
	res = sbChannelOpen(&control->channel);

	// by default, request acknowledgement
	control->ackMode = SB_MSGID_REQACK;

	return res;
}

// Open a network communication channel to the helicopter.
// This may be used in simulation or possibly to communicate via an on-board
// network-enabled processor.
int sbOpenSocketCommunication(struct SBControlContext *control,
		const char *hostname, unsigned int port)
{
	int res;
	bzero(&control->channel, sizeof(SBChannel));
	res = sbChannelCreateSocketUDP(&control->channel,hostname,port);
	if (res) {
		return res;
	}
	res = sbChannelOpen(&control->channel);

	// by default, request acknowledgement
	control->ackMode = SB_MSGID_REQACK;

	return res;
}

#endif

// Close the communication channel and release any resource if needed
int sbCloseCommunication(struct SBControlContext *control)
{
	return sbChannelDestroy(&control->channel);
}

// Flush the communication channel
int sbFlushCommunication(struct SBControlContext *control)
{
	return sbChannelFlush(&control->channel);
}

// Lock the communication channel to prevent concurrent access from different
// threads. Currently, this will only work on POSIX systems.
int sbLockCommunication(struct SBControlContext *control)
{
	return sbChannelLock(&control->channel);
}

// Unlock the communication channel
int sbUnlockCommunication(struct SBControlContext *control)
{
	return sbChannelUnlock(&control->channel);
}

static
void scaleHeliState(SBHeliState *hs, const SBHeliStateRaw *hr)
{
	int i;
	hs->errorFlags = hr->errorFlags;
	hs->content = ((unsigned long)hr->content[1]) |
		(((unsigned long)hr->content[0]) << 16);
	hs->timeStamp = hr->timeStamp;
	hs->controlTimeout = hr->controlTimeout;
	hs->watchdogTimeout = hr->watchdogTimeout;
	hs->mode.navigation = hr->mode.navigation;
	hs->mode.communication = hr->mode.communication;
	hs->mode.oavoid = hr->mode.oavoid;
	hs->mode.rollAxis = hr->mode.rollAxis;
	hs->mode.pitchAxis = hr->mode.pitchAxis;
	hs->mode.yawAxis = hr->mode.yawAxis;
	hs->mode.altAxis = hr->mode.altAxis;
	hs->roll = (float)( ((signed short)hr->roll) * M_PI/1800.0 );
	hs->pitch = (float)( ((signed short)hr->pitch) * M_PI/1800.0 );
	hs->yaw = (float)( ((signed short)hr->yaw) * M_PI/1800.0 );
	for (i=0;i<3;i++) {
		hs->gyro[i] = (float)( ((signed short)hr->gyro[i])*M_PI/1800.0 );
		hs->accel[i] = (float)( ((signed short)hr->accel[i])/1000.0 );
		hs->magneto[i] = (float)( ((signed short)hr->magneto[i])/1000.0 );
		hs->o_attitude[i] = (float)( ((signed short)hr->o_attitude[i])/1000.0 );
	}
	for (i=0;i<4;i++) {
		hs->hranges[i] = (float)( ((unsigned short)hr->hranges[i])/1000.0 );
	}
	hs->imutemp = (float)( ((unsigned short)hr->imutemp)/1000.0 );
	hs->battery = (float)( ((unsigned short)hr->battery)/1000.0 );
	hs->zrange = (float)( ((signed short)hr->zrange)/1000.0 );
	hs->zfiltered = (float)( ((signed short)hr->zfiltered)/1000.0 );
	hs->pressure = (float)( ((signed short)hr->pressure));
	hs->xrel = (float)( ((signed short)hr->xrel)/1000.0 );
	hs->yrel = (float)( ((signed short)hr->yrel)/1000.0 );
	hs->o_altitude = (float)( ((signed short)hr->o_altitude)/1000.0 );
	hs->o_tol = hr->o_tol;
	for (i=0;i<2;i++) {
		hs->o_xy[i] = hr->o_xy[i];
		hs->o_oavoid[i] = hr->o_oavoid[i];
	}
	for (i=0;i<8;i++) {
		hs->rcChannel[i] = (float)(hr->rcChannel[i]/1000.);
	}
    hs->coaxspeed.state = hr->coaxspeed.state;
    hs->coaxspeed.light = hr->coaxspeed.light;
    hs->coaxspeed.vel_x = (float)(hr->coaxspeed.vel_x/1000.0);
    hs->coaxspeed.vel_y = (float)(hr->coaxspeed.vel_y/1000.0);
}

// #define DEBUG_SEND_AND_WAIT
static
int sendAndWaitMsg(struct SBControlContext *control,
		SBSerialisedMessage *tosend,
		SBSerialisedMessage *reply)
{
	unsigned int numtries = 10;
#ifdef DEBUG_SEND_AND_WAIT
	printf("sendAndWaitMsg %02X\n",tosend->msgid);
#endif // DEBUG_SEND_AND_WAIT
	while (numtries > 0) {
		numtries --;
#ifdef DEBUG_SEND_AND_WAIT
		printf("Sending message %02X\n",tosend->msgid);
#endif // DEBUG_SEND_AND_WAIT
		if(sbSendMessage(&control->channel,tosend,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
#ifdef DEBUG_SEND_AND_WAIT
		printf("Waiting message %02X\n",tosend->msgid);
#endif // DEBUG_SEND_AND_WAIT
		if (sbWaitRawMessage(&control->channel,-1,reply,DEFAULT_TIMEOUT_MS)) {
			printf("Timeout %d\n",numtries);
			continue;
		}
#ifdef DEBUG_SEND_AND_WAIT
		printf("Got message %02X\n",reply->msgid);
#endif // DEBUG_SEND_AND_WAIT
		if (reply->msgid == (SB_MSGID_REPLY|SB_MSGID_STATE)) {
#ifdef DEBUG_SEND_AND_WAIT
			printf("That's a state message\n");
#endif
			numtries ++; // that does not count :)
			if (control->stateCallback) {
				SBHeliStateRaw hr;
				SBHeliState hs;
				sbStateDecode(reply,&hr);
				scaleHeliState(&hs,&hr);
				control->stateCallback(&hs,control->stateUserData);
			}
        } else if (reply->msgid == SB_MSGID_REPEAT) {
#ifdef DEBUG_SEND_AND_WAIT
			printf("That's a repeat message\n");
#endif
			numtries ++; // that does not count :)
			if (control->repeatCallback) {
				control->repeatCallback(reply->data+SB_MESSAGE_HEADER_LEN,
                        reply->len,control->repeatUserData);
			}
		} else if (reply->msgid == (SB_MSGID_REPLY|(tosend->msgid&SB_MSGID_MASK))) {
#ifdef DEBUG_SEND_AND_WAIT
			printf("Got the ack\n");
#endif // DEBUG_SEND_AND_WAIT
			break;
		}
	}
	return numtries?0:-2;
}

// TODO: Implementation TBD
int sbConnect(struct SBControlContext *control)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBBasicReplyMessage br;
	sm.len = 0;
	sm.handle = 0;
	sm.msgid = SB_MSGID_CONNECT;
	if (control->ackMode) {
		sm.msgid |= SB_MSGID_REQACK;
	}
	sbFinalizeMessage(&sm);

	if (sendAndWaitMsg(control,&sm,&reply)) {
		return -1;
	}
	r = sbBasicReplyDecode(&reply,&br);
	if (r == 0) {
		control->handle = reply.handle;
		return br.status;
	}
	return -1;
}

// TODO: Implementation TBD
int sbDisconnect(struct SBControlContext *control)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBBasicReplyMessage br;
	sm.len = 0;
	sm.handle = control->handle;
	sm.msgid = SB_MSGID_DISCONNECT;
	if (control->ackMode) {
		sm.msgid |= SB_MSGID_REQACK;
	}
	sbFinalizeMessage(&sm);

	control->handle = 0;
	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

// This function illustrates the spirit of this API.
// At any one time, only one process/thread should use the control
// channel.
// In synchronous mode, the dialogue is only question/response
// When the communication is continuous, the helicopter may send state
// information at any time. When a question/response mode is started, some
// state information may arrive in-between. This callback can be setup to
// handle this piece of data in this case, instead of discarding it.
// Example:
//
// // Global variable to store the state, for illustration
// SBHeliState state;
//
// void * receive_thread(void *) {
//	 ...
//	 while (1) {
//		sbLockCommunication(&control);
//		sbReceiveState(control,&state);
//		sbUnlockCommunication(&control);
//	 }
//	}
//
//	void recCB(SBHeliState *rstate, void *user_data) {
//		memcpy(&state,&rstate,sizeof(SBHeliState);
//	}
//
//	int main() {
//		struct SBControlContext control;
//		unsigned long sensors = SBS_ALL;
//		unsigned long content = SBS_ALL;
//		sbOpenSerialCommunication(&control,"/dev/rfcomm0",B115200)
//		sbConnect(&control);
//		sbRegisterStateCallback(&control,recCB,NULL);
//		sbGetSensorList(&control, &sensors);
//		sbConfigureOAMode(&control,SB_OA_NONE);
//		sbConfigureControl(&control,SB_CTRL_NONE,SB_CTRL_NONE,
//				SB_CTRL_POS, SB_CTRL_POS, SB_CTRL_VEL);
//		// In order to request only the data available on this platform
//		sbConfigureComm(SB_COM_CONTINUOUS,30,content & sensors);
//		start receive_thread()
//		while (1) {
//			wait something
//			sbLockCommunication(&control);
//			// Any state received here will be handle by the callback
//			sbSetNavMode(&control,SB_NAV_HOVER);
//			sbUnlockCommunication(&control);
//		}
//	}
int sbRegisterStateCallback(struct SBControlContext *control,
	void (*stateCallback)(SBHeliState *state, void *userData),
	void *userData)
{
	control->stateCallback = stateCallback;
	control->stateUserData = userData;
	return 0;
}

int sbRegisterRepeatCallback(struct SBControlContext *control,
	void (*repeatCallback)(const unsigned char*data, unsigned int len, void *userData),
	void *userData)
{
	control->repeatCallback = repeatCallback;
	control->repeatUserData = userData;
	return 0;
}

// Configure the communication so that control requests (sbSetNavMode,
// sbKeepAlive, sbSetControl) requires an acknowledgement
// from the helicopter. If requestAck is zero, all control functions
// will not confirm reception of their commands. With bluetooth communication,
// this can improve the communication rate. If requestAck is non zero, the
// control request will be followed by an acknowledgement.
int sbConfigureAckMode(struct SBControlContext *control,
		unsigned int requestAck)
{
	control->ackMode = requestAck;
	return 0;
}

int sbGetVersionInformation(struct SBControlContext *control, SBVersionStatus * status)
{
	int r;
	SBSerialisedMessage sm,reply;
	sm.len = 0;
	sm.handle = control->handle;
	sm.msgid = SB_MSGID_GET_VERSION;
	sbFinalizeMessage(&sm);

	if (sendAndWaitMsg(control,&sm,&reply)) {
		printf("sbGetVersionInformation: Send and wait failed\n");
		return -1;
	}
	r = sbVersionMsgDecode(&reply,status);
	if (r ==0) {
		return 0;
	} else {
		printf("sbGetVersionInformation: Decode failed\n");
	}
	return r;
}

int sbGetSensorList(struct SBControlContext *control, unsigned long *list)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBSensorListMessage sl;
	sm.len = 0;
	sm.handle = control->handle;
	sm.msgid = SB_MSGID_SENSORLIST;
	sbFinalizeMessage(&sm);

	if (sendAndWaitMsg(control,&sm,&reply)) {
		printf("sbGetSensorList: Send and wait failed\n");
		return -1;
	}
	r = sbSensorListDecode(&reply,&sl);
	if (r ==0) {
		*list = (sl.content[1] | (((unsigned long)sl.content[0]) << 16));
	} else {
		printf("sbGetSensorList: Decode failed\n");
	}
	return r;
}

int sbConfigureCommLoop(struct SBControlContext *control, unsigned int verbose,
		int debug_channel)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBConfigureCommLoop cl;
	SBBasicReplyMessage br;
	cl.verbosity = verbose;
	cl.debug_channel = debug_channel;
	sbCfgCommLoopEncode(&sm,control->handle,&cl,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

// oavoidMode defined from sbconst.h SB_OA_xxxx
int sbConfigureOAMode(struct SBControlContext *control, unsigned int oavoidMode)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBConfigureObstAvoid oa;
	SBBasicReplyMessage br;
	oa.oavoidMode = oavoidMode;
	sbCfgOAEncode(&sm,control->handle,&oa,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

// debugMode defined from sbconst.h SB_DEBUG_xxxx
int sbSetDebugMode(struct SBControlContext *control, unsigned char debugMode)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBSetDebugMode sd;
	SBBasicReplyMessage br;
	sd.debugMode = debugMode;
	sbSetDebugEncode(&sm,control->handle,&sd,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

// commMode defined from sbconst.h SB_COM_xxxx
int sbConfigureComm(struct SBControlContext *control,
		unsigned int commMode,
		unsigned int frequency,
		unsigned int numMessages,
		unsigned long contents)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBConfigureCommunication comm;
	SBBasicReplyMessage br;
	comm.commMode = commMode;
	comm.frequency = frequency;
	comm.numMessages = numMessages;
	comm.content[1] = contents & 0xFFFF;
	comm.content[0] = (contents >> 16) & 0xFFFF;
	sbCfgCommEncode(&sm,control->handle,&comm,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

// controlMode defined from sbconst.h SB_CTRL_xxxx
int sbConfigureControl(struct SBControlContext *control,
		unsigned int roll,
		unsigned int pitch,
		unsigned int yaw,
		unsigned int altitude)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBConfigureControl ctrl;
	SBBasicReplyMessage br;
	ctrl.roll = roll;
	ctrl.pitch = pitch;
	ctrl.yaw = yaw;
	ctrl.altitude = altitude;
	sbCfgControlEncode(&sm,control->handle,&ctrl,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

int sbConfigureTimeout(struct SBControlContext *control,
		unsigned short control_timeout_ms,
		unsigned short watchdog_timeout_ms)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBConfigureTimeout timeout;
	SBBasicReplyMessage br;
	timeout.controlTimeout = control_timeout_ms;
	timeout.watchdogTimeout = watchdog_timeout_ms;
	sbCfgTimeoutEncode(&sm,control->handle,&timeout,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

int sbKeepAlive(struct SBControlContext *control)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBBasicReplyMessage br;
	sm.len = 0;
	sm.handle = control->handle;
	sm.msgid = SB_MSGID_KEEP_ALIVE;
	if (control->ackMode) {
		sm.msgid |= SB_MSGID_REQACK;
	}
	sbFinalizeMessage(&sm);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

/**   Control the light of the coax speed, if used as a sensor without control
 *   */
int sbSetCoaxSpeedLight(struct SBControlContext *control, unsigned char percent)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBCoaxSpeedSetLight setlight;
	SBBasicReplyMessage br;
	setlight.percent = percent;
	sbCoaxSpeedSetLightEncode(&sm,control->handle,&setlight,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

/*   Send a reset command to the DSPIC. After this command, the connections may
 *   not be reusable.
 *   */
int sbResetDSPIC(struct SBControlContext *control)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBBasicReplyMessage br;
	sm.len = 0;
	sm.handle = control->handle;
	sm.msgid = SB_MSGID_RESET;
	if (control->ackMode) {
		sm.msgid |= SB_MSGID_REQACK;
	}
	sbFinalizeMessage(&sm);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	}else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

/*   Send a string to the DSPIC. If the debug interface are active, then this
 *   string is displayed on the DEBUG console. Otherwise it is ignored.
 *   The string length cannot be longer than SB_STRING_MESSAGE_LENGTH
 *   */
int sbSendString(struct SBControlContext *control,const char *text)
{
	SBSerialisedMessage sm;
	SBStringMessage msg;
#ifdef WIN32
	strncpy_s((char*)msg.text,SB_STRING_MESSAGE_LENGTH-1,text,SB_STRING_MESSAGE_LENGTH-1);
#else
	strncpy((char*)msg.text,text,SB_STRING_MESSAGE_LENGTH-1);
#endif
	msg.text[SB_STRING_MESSAGE_LENGTH-1]=0;
	sbStringMsgEncode(&sm,control->handle,&msg);

	if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
		return -1;
	}
	return 0;
}

/** Store a custom message on the dsPIC, to be read by the next
 *  sbGetCustomMessage call.
 *  The data length cannot be longer than SB_STRING_MESSAGE_LENGTH
 *   */
int sbSetCustomMessage(struct SBControlContext *control,const char message[SB_STRING_MESSAGE_LENGTH])
{
    int r=0;
	SBSerialisedMessage sm,reply;
	SBCustomMessage msg;
	SBBasicReplyMessage br;
#ifdef WIN32
	strncpy_s((char*)msg.text,SB_STRING_MESSAGE_LENGTH-1,message,SB_STRING_MESSAGE_LENGTH-1);
#else
	strncpy((char*)msg.text,message,SB_STRING_MESSAGE_LENGTH-1);
#endif
	msg.text[SB_STRING_MESSAGE_LENGTH-1]=0;
	sbCustomMsgEncode(&sm,control->handle,&msg,0);

	if (sendAndWaitMsg(control,&sm,&reply)) {
		printf("sSGetCustomMessage: Send and wait failed\n");
		return -1;
	}
    r = sbBasicReplyDecode(&reply,&br);
    if (r == 0) {
        return br.status;
    }
	return -2;
}

/** Read the last custom message from the dsPIC.*/
int sbGetCustomMessage(struct SBControlContext *control,char message[SB_STRING_MESSAGE_LENGTH])
{
	int r;
	SBSerialisedMessage sm,reply;
	SBCustomMessage msg;
	sm.len = 0;
	sm.handle = control->handle;
	sm.msgid = SB_MSGID_CUSTOM;
	sbFinalizeMessage(&sm);

	if (sendAndWaitMsg(control,&sm,&reply)) {
		printf("sbGetCustomMessage: Send and wait failed\n");
		return -1;
	}
	r = sbCustomMsgDecode(&reply,&msg);
	if (r ==0) {
#ifdef WIN32
        strncpy_s((char*)message,SB_STRING_MESSAGE_LENGTH-1,(char*)msg.text,SB_STRING_MESSAGE_LENGTH-1);
#else
        strncpy((char*)message,(char*)msg.text,SB_STRING_MESSAGE_LENGTH-1);
#endif
        message[SB_STRING_MESSAGE_LENGTH-1]=0;
	} else {
		printf("sbGetCustomMessage: Decode failed\n");
	}
	return r;
}

// Use a OR of SBS_... flags to create content
int sbRequestState(struct SBControlContext *control,
		unsigned long contents, SBHeliState *state)
{
	unsigned int numtry = 0;
	SBSerialisedMessage sm;
	SBRequestState rs;
	rs.content[1] = contents & 0xFFFF;
	rs.content[0] = (contents >> 16) & 0xFFFF;
	sbReqStateEncode(&sm,control->handle,&rs);
	// dumpMessage("sbReqStateEncode",&sm);

	do {
		numtry += 1;
		if (numtry > 5) {
			printf("sbRequestState: timeout\n");
			return -3;
		}
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			printf("sbRequestState: sbSendMessage failed\n");
			state->content = 0;
		}
		if(sbReceiveState(control,state,DEFAULT_TIMEOUT_MS)) {
			printf("sbRequestState: sbReceiveState failed\n");
			state->content = 0;
		}
#ifdef LINUX
		usleep(10000);
#endif
#ifdef WIN32
		Sleep(10);
#endif
		// If the state content is not what we asked for, request it again!
	} while (state->content != contents);
	return 0;
}

int sbWaitState(struct SBControlContext *control, unsigned int timeout_ms)
{
	return sbChannelWaitData(&control->channel, timeout_ms);
}

// Content controlled via sbConfigureComm
int sbReceiveState(struct SBControlContext *control,SBHeliState *state,
		unsigned int timeout_ms)
{
	SBSerialisedMessage reply;
	SBHeliStateRaw hr;
	if (sbWaitRawMessage(&control->channel,-1,&reply,timeout_ms)) {
		return -1;
	}
	// sbDumpMessage("sbReceiveState",&reply);
	if (reply.msgid == (SB_MSGID_REPLY|SB_MSGID_STATE)) {
		sbStateDecode(&reply,&hr);
		scaleHeliState(state,&hr);
		return 0;
	}
	return -2;
}

int sbReceiveDataWithCallbacks(struct SBControlContext *control,
        unsigned int timeout_wait_ms, unsigned int timeout_receive_ms)
{
	SBHeliState state;
    SBSerialisedMessage reply;
    int res = -1;
    sbLockCommunication(control);
    // Receive state
    res = sbChannelWaitData(&control->channel, timeout_wait_ms);
    if (res==0) {
        // printf("There is data\n");
        // There should be something coming, so we wait for long
        // if it is too long, it means something wrong happened with the
        // communication, and we want to trigger the watchdog
        if (sbWaitRawMessage(&control->channel,-1,&reply,timeout_receive_ms)) {
            printf("Error while receiving raw message\n");
        } else {
            // printf("Got the raw data\n");
            res = 0;
        }
    }
    sbUnlockCommunication(control);
    if (res==0) {
        if (reply.msgid == (SB_MSGID_REPLY|SB_MSGID_STATE)) {
            // printf("This is a state\n");
            if (control->stateCallback) {
                // printf("And we have a callback\n");
                SBHeliStateRaw hr;
                sbStateDecode(&reply,&hr);
                scaleHeliState(&state,&hr);
                control->stateCallback(&state,control->stateUserData);
            }
        } else if ((reply.msgid & SB_MSGID_MASK)  == SB_MSGID_REPEAT) {
            // printf("\nThis is a repeat\n");
            if (control->repeatCallback) {
                // printf("And we have a callback\n");
                control->repeatCallback(reply.data+SB_MESSAGE_HEADER_LEN,
                        reply.len,control->repeatUserData);
            }
        } else {
            // printf("This is nothing: %02X\n",reply.msgid);
        }
    } else {
        return res;
    }
    return 0;
}

int sbSendRepeatMessage(struct SBControlContext *control,
        const unsigned char *data, unsigned int len) {
	int i,r;
	SBSerialisedMessage sm,reply;
	SBBasicReplyMessage br;
    if (len > SB_STRING_MESSAGE_LENGTH) {
        printf("sbSendRepeatMessage: message too long\n");
        return -1;
    }
	sm.len = len;
	sm.handle = control->handle;
	sm.msgid = SB_MSGID_REPEAT;
	if (control->ackMode) {
		sm.msgid |= SB_MSGID_REQACK;
	}
    for (i=0;i<len;i++) {
        sm.data[SB_MESSAGE_HEADER_LEN+i] = data[i];
    }
	sbFinalizeMessage(&sm);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	} else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

// navMode defined from sbconst.h SB_NAV_xxxx
int sbSetNavMode(struct SBControlContext *control,
		unsigned int navMode)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBSetNavigationMode nav;
	SBBasicReplyMessage br;
	nav.mode = navMode;
	sbSetNavEncode(&sm,control->handle,&nav,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	} else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

#ifdef LINUX
static
inline double now() {
	struct timeval tv;
	gettimeofday(&tv,NULL);
	return tv.tv_sec + 1e-6*tv.tv_usec;
}
#endif

#ifdef WIN32
#ifndef EPOCHFILETIME
#ifndef __GNUC__
#define EPOCHFILETIME (116444736000000000i64)
#else
#define EPOCHFILETIME (116444736000000000LL)
#endif
#endif

static inline double now() {
	FILETIME        ft;
	LARGE_INTEGER   li;
	__int64         t;

	GetSystemTimeAsFileTime(&ft);
	li.LowPart  = ft.dwLowDateTime;
	li.HighPart = ft.dwHighDateTime;
	t  = li.QuadPart;       /* In 100-nanosecond intervals */
	t -= EPOCHFILETIME;     /* Offset to the Epoch time */
	return t * 1e-7;
}
#endif

double sbGetCurrentTime() {
	return now();
}

//#define DEBUG(c) {int __res__;printf("Executing "#c"\n");__res__ = (c);printf("Result %d\n",__res__);}
#define DEBUG(c) {int __res__ = (c);if (__res__) printf("Result of "#c": %d\n",__res__);}
int sbSetNavAndWait(struct SBControlContext *control,
		int setmode, int waitmode,double timout_sec)
{
	SBHeliState state;
	int res;
	double t,t0 = now();
	sbLockCommunication(control);
	DEBUG(res = sbSetNavMode(control,setmode));
	sbUnlockCommunication(control);
	if (res) return res;
	while (1) {
		sbLockCommunication(control);
		DEBUG(res = sbRequestState(control, SBS_MODES, &state));
		sbUnlockCommunication(control);
		if (res) return res;

		if (state.mode.navigation == waitmode){
			break;
		}
		t = now();
		if (t < t0) t += 86400; // time of day wrap around
		if ((t - t0) > timout_sec) {
			break;
		}
#ifdef LINUX
		usleep(5000);
#endif
#ifdef WIN32
		Sleep(5);
#endif
	}
	return (state.mode.navigation == waitmode)?0:+1;
}

// Only SI unit used here: percent, percent, rad/s, m, m/s
int sbSetControl(struct SBControlContext *control,
		double roll, double pitch, double yaw, double altitude)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBSetControl ctrl;
	SBBasicReplyMessage br;
	ctrl.roll = (signed short)round(roll*1000);
	ctrl.pitch = (signed short)round(pitch*1000);
	ctrl.yaw = (signed short)round(yaw*1800.0/M_PI);
	ctrl.altitude = (signed short)round(altitude*1000.0);
	sbSetControlEncode(&sm,control->handle,&ctrl,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	} else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

// Only SI unit used here: percent, percent, rad/s, m, m/s
int sbSetControlWithTimestamp(struct SBControlContext *control,
		double roll, double pitch, double yaw, double altitude, unsigned long timestamp)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBSetControlWithTimestamp ctrl;
	SBBasicReplyMessage br;
	ctrl.roll = (signed short)round(roll*1000);
	ctrl.pitch = (signed short)round(pitch*1000);
	ctrl.yaw = (signed short)round(yaw*1800.0/M_PI);
	ctrl.altitude = (signed short)round(altitude*1000.0);
	ctrl.timestamp = timestamp;
	sbSetControlWithTimestampEncode(&sm,control->handle,&ctrl,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	} else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

int sbConfigureRawControl(struct SBControlContext *control,
		unsigned char speedprofile1, unsigned char speedprofile2)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBConfigureRawControl cfg;
	SBBasicReplyMessage br;
	cfg.speedprofile1 = speedprofile1;
	cfg.speedprofile2 = speedprofile2;
	sbCfgRawControlEncode(&sm,control->handle,&cfg,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	} else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

int sbSetRawControl(struct SBControlContext *control,
		double motor1, double motor2, double servo1, double servo2)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBRawControl ctrl;
	SBBasicReplyMessage br;
	ctrl.motor1 = (signed short)(motor1*1000);
	ctrl.motor2 = (signed short)(motor2*1000);
	ctrl.servo1 = (signed short)(servo1*1000);
	ctrl.servo2 = (signed short)(servo2*1000);
	sbRawControlEncode(&sm,control->handle,&ctrl,control->ackMode);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	} else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

int sbGetTrimMode(struct SBControlContext *control, struct SBTrimMode *mode)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBTrimModeMessage tm;
	sm.len = 0;
	sm.handle = control->handle;
	sm.msgid = SB_MSGID_TRIMMODE | (control->ackMode?SB_MSGID_REQACK:0);
	sbFinalizeMessage(&sm);

	if (sendAndWaitMsg(control,&sm,&reply)) {
		return -1;
	}
	r = sbTrimModeDecode(&reply,&tm);
	if (r ==0) {
		mode->trimMode = tm.trimMode;
		mode->rollTrim = (float)(tm.rollTrim/10000.);
		mode->pitchTrim = (float)(tm.pitchTrim/10000.);
	}
	return r;
}

int sbSetTrimMode(struct SBControlContext *control, const struct SBTrimMode *mode)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBTrimModeMessage tm;
	SBBasicReplyMessage br;
	tm.trimMode = mode->trimMode;
	tm.rollTrim = (signed short)(10000 * mode->rollTrim);
	tm.pitchTrim = (signed short)(10000 * mode->pitchTrim);
	sbTrimModeEncode(&sm,control->handle,&tm,1);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	} else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

int sbGetControlParameters(struct SBControlContext *control,
		struct SBControlParameters *params)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBControlParametersMessage cm;
	sm.len = 0;
	sm.handle = control->handle;
	sm.msgid = SB_MSGID_CTRLPARM | (control->ackMode?SB_MSGID_REQACK:0);
	sbFinalizeMessage(&sm);

	if (sendAndWaitMsg(control,&sm,&reply)) {
		return -1;
	}
	r = sbCtrlParametersDecode(&reply,&cm);
	if (r ==0) {
		params->baseThrust = (float)(cm.baseThrust/1000.);
		params->yawOffset = (float)(cm.yawOffset/1000.);
		params->altitudeKp = (float)(cm.altitudeKp/1000.);
		params->altitudeKi = (float)(cm.altitudeKi/1000.);
		params->altitudeKd = (float)(cm.altitudeKd/1000.);
		params->yawKp = (float)(cm.yawKp/1000.);
		params->yawKi = (float)(cm.yawKi/1000.);
		params->yawKd = (float)(cm.yawKd/1000.);
	}
	return r;
}

int sbSetControlParameters(struct SBControlContext *control,
		const struct SBControlParameters *params)
{
	int r;
	SBSerialisedMessage sm,reply;
	SBControlParametersMessage cm;
	SBBasicReplyMessage br;
	cm.baseThrust = (unsigned short)(1000 * params->baseThrust);
	cm.yawOffset = (unsigned short)(1000 * params->yawOffset);
	cm.altitudeKp = (signed short)(1000 * params->altitudeKp);
	cm.altitudeKi = (signed short)(1000 * params->altitudeKi);
	cm.altitudeKd = (signed short)(1000 * params->altitudeKd);
	cm.yawKp = (signed short)(1000 * params->yawKp);
	cm.yawKi = (signed short)(1000 * params->yawKi);
	cm.yawKd = (signed short)(1000 * params->yawKd);
	sbCtrlParametersEncode(&sm,control->handle,&cm,1);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	} else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

int sbConfigureBluetooth(struct SBControlContext *control,
		const char code[4], const char name[16])
{
	int r;
	SBSerialisedMessage sm,reply;
	SBConfigureBluetoothMessage cm;
	SBBasicReplyMessage br;
	memcpy(cm.code,code,4);
	memcpy(cm.name,name,16);
	sbConfigureBluetoothEncode(&sm,control->handle,&cm,1);

	if (control->ackMode) {
		if (sendAndWaitMsg(control,&sm,&reply)) {
			return -1;
		}
		r = sbBasicReplyDecode(&reply,&br);
		if (r == 0) {
			return br.status;
		}
	} else {
		if(sbSendMessage(&control->channel,&sm,DEFAULT_TIMEOUT_MS)) {
			return -1;
		}
		return 0;
	}
	return -1;
}

#ifdef SBC_HAS_IO

#define TESTCONTENT(content,what) ((content) & (what))

const char* sbContentString(unsigned long c)
{
	switch (c) {
		case SBS_MODES:
			return "MODES";
		case SBS_TIMESTAMP:
			return "TIMESTAMP";
		case SBS_RPY:
			return "RPY";
		case SBS_GYRO:
			return "GYRO";
		case SBS_ACCEL:
			return "ACCEL";
		case SBS_MAGNETO:
			return "MAGNETO";
		case SBS_IMUTEMP:
			return "IMUTEMP";
		case SBS_ALTITUDE:
			return "ALTITUDE";
		case SBS_PRESSURE:
			return "PRESSURE";
		case SBS_HRANGES:
			return "HRANGES";
		case SBS_XY_REL:
			return "XY_REL";
		case SBS_BATTERY:
			return "BATTERY";
		case SBS_CHANNELS:
			return "CHANNELS";
		case SBS_O_ATTITUDE:
			return "O_ATTITUDE";
		case SBS_O_ALTITUDE:
			return "O_ALTITUDE";
		case SBS_O_TOL:
			return "O_TOL";
		case SBS_O_XY:
			return "O_XY";
		case SBS_O_OAVOID:
			return "O_OAVOID";
		case SBS_TIMEOUT:
			return "TIMEOUT";
		case SBS_COAXSPEED:
			return "COAXSPEED";
		default:
			break;
	}
	return NULL;
}

const char * sbFlagString(unsigned char err) {
    switch (err) {
        case SB_FLAG_IMUCRASH: return "IMUCRASH";
        case SB_FLAG_LOWPOWER: return "LOWPOWER";
        case SB_FLAG_RCLOST: return "RCLOST";
        case SB_FLAG_KILLED: return "KILLED";
        case SB_FLAG_MANUAL: return "MANUAL";
        default : return "UNKNOWN";
    }
    return NULL;
}

void sbErrorPrint(FILE * fp, unsigned char err) {
	fprintf(fp,"Error  : %02X [ ",err);
    if (err & SB_FLAG_IMUCRASH) fprintf(fp,"%s ",sbFlagString(SB_FLAG_IMUCRASH));
    if (err & SB_FLAG_LOWPOWER) fprintf(fp,"%s ",sbFlagString(SB_FLAG_LOWPOWER));
    if (err & SB_FLAG_RCLOST) fprintf(fp,"%s ",sbFlagString(SB_FLAG_RCLOST));
    if (err & SB_FLAG_MANUAL) fprintf(fp,"%s ",sbFlagString(SB_FLAG_MANUAL));
    if (err & SB_FLAG_KILLED) fprintf(fp,"%s ",sbFlagString(SB_FLAG_KILLED));
    fprintf(fp,"]\n");
}

void sbStatePrint(FILE * fp, const SBHeliState *hs)
{
	fprintf(fp,"Content: "); sbContentPrint(fp,hs->content);
	fprintf(fp,"\n");
    sbErrorPrint(fp,hs->errorFlags);
	if (TESTCONTENT(hs->content,SBS_MODES)) {
		fprintf(fp,"Modes:\n");
		fprintf(fp,"\tNavigation %s",sbNavModeString(hs->mode.navigation));
		fprintf(fp,"\tCommunication %s",sbCommModeString(hs->mode.communication));
		fprintf(fp,"\tObst. Avoid: %s\n",sbOAModeString(hs->mode.oavoid));
		fprintf(fp,"\tAxis: Roll %s",sbCtrlModeString(hs->mode.rollAxis));
		fprintf(fp,"\tPitch %s",sbCtrlModeString(hs->mode.pitchAxis));
		fprintf(fp,"\tYaw %s",sbCtrlModeString(hs->mode.yawAxis));
		fprintf(fp,"\tAlti. %s",sbCtrlModeString(hs->mode.altAxis));
		fprintf(fp,"\n");
	}
	if (TESTCONTENT(hs->content,SBS_TIMESTAMP)) {
		fprintf(fp,"Timestamp: %8ld\n",hs->timeStamp);
	}
	if (TESTCONTENT(hs->content,SBS_RPY)) {
		fprintf(fp,"RPY (deg): %+6.2f, %+6.2f, %+6.2f\n",R2D(hs->roll), R2D(hs->pitch), R2D(hs->yaw));
	}
	if (TESTCONTENT(hs->content,SBS_GYRO)) {
		fprintf(fp,"Gyro (deg/s): %+6.2f, %+6.2f, %+6.2f\n",R2D(hs->gyro[0]), R2D(hs->gyro[1]), R2D(hs->gyro[2]));
	}
	if (TESTCONTENT(hs->content,SBS_ACCEL)) {
		fprintf(fp,"Accel (m/s2): %+5.2f, %+5.2f, %+5.2f\n",hs->accel[0], hs->accel[1], hs->accel[2]);
	}
	if (TESTCONTENT(hs->content,SBS_MAGNETO)) {
		fprintf(fp,"Magneto: %+5.2f, %+5.2f, %+5.2f\n",hs->magneto[0], hs->magneto[1], hs->magneto[2]);
	}
	if (TESTCONTENT(hs->content,SBS_IMUTEMP)) {
		fprintf(fp,"IMU Temp (degC): %.2f\n",hs->imutemp);
	}
	if (TESTCONTENT(hs->content,SBS_ALTITUDE)) {
		fprintf(fp,"Z Range (m): %+4.2f Filtered (m): %.2f\n",
				hs->zrange, hs->zfiltered);
	}
	if (TESTCONTENT(hs->content,SBS_PRESSURE)) {
		fprintf(fp,"Pressure (?): %+6.2f\n",hs->pressure);
	}
	if (TESTCONTENT(hs->content,SBS_HRANGES)) {
		int i;
		fprintf(fp,"H ranges (m): ");
		for (i=0;i<4;i++) {
			if (hs->hranges[i]>65.5) {
				fprintf(fp,"inf ");
			} else {
				fprintf(fp,"%4.2f ",hs->hranges[i]);
			}
		}
		printf("\n");
	}
	if (TESTCONTENT(hs->content,SBS_XY_REL)) {
		fprintf(fp,"XY Rel (m): %.2f, %.2f\n",hs->xrel, hs->yrel);
	}
	if (TESTCONTENT(hs->content,SBS_BATTERY)) {
		fprintf(fp,"Battery (V): %5.2f\n",hs->battery);
	}
	if (TESTCONTENT(hs->content,SBS_TIMEOUT)) {
		fprintf(fp,"Timeout (ms): WD %d CTRL %d \n",hs->watchdogTimeout,hs->controlTimeout);
	}
	if (TESTCONTENT(hs->content,SBS_CHANNELS)) {
		fprintf(fp,"Channels: %.3f %.3f %.3f %.3f\n\t%.3f %.3f %.3f %.3f \n",
				hs->rcChannel[0],hs->rcChannel[1],
				hs->rcChannel[2],hs->rcChannel[3],
				hs->rcChannel[4],hs->rcChannel[5],
				hs->rcChannel[6],hs->rcChannel[7]);
	}
	if (TESTCONTENT(hs->content,SBS_O_ATTITUDE)) {
		fprintf(fp,"Output Attitude: %f, %f, %f\n",hs->o_attitude[0], hs->o_attitude[1], hs->o_attitude[2]);
	}
	if (TESTCONTENT(hs->content,SBS_O_ALTITUDE)) {
		fprintf(fp,"Output Altitude: %f\n", hs->o_altitude);
	}
	if (TESTCONTENT(hs->content,SBS_O_TOL)) {
		fprintf(fp,"Output TOL: %04X\n",hs->o_tol);
	}
	if (TESTCONTENT(hs->content,SBS_O_XY)) {
		fprintf(fp,"Output XY: %f, %f\n",hs->o_xy[0], hs->o_xy[1]);
	}
	if (TESTCONTENT(hs->content,SBS_O_OAVOID)) {
		fprintf(fp,"Output OA XY: %f, %f\n", hs->o_oavoid[0], hs->o_oavoid[1]);
	}
	if (TESTCONTENT(hs->content,SBS_COAXSPEED)) {
        if (hs->coaxspeed.state & COAXSPEED_AVAILABLE) {
            if (hs->coaxspeed.state & COAXSPEED_VALID_MEASUREMENT) {
                fprintf(fp,"CoaxSpeed %02X: V %.3f %.3f L %3d%%\n",hs->coaxspeed.state,
                        hs->coaxspeed.vel_x, hs->coaxspeed.vel_y, hs->coaxspeed.light);
            } else {
                fprintf(fp,"CoaxSpeed %02X: V  invalid  L %3d%%\n",hs->coaxspeed.state, hs->coaxspeed.light);
            }
        } else {
            fprintf(fp,"CoaxSpeed %02X: not detected\n",hs->coaxspeed.state);
        }
	}
}

void sbContentPrint(FILE* fp, unsigned long content)
{
	fprintf(fp,"%08lX [",content);
	if (TESTCONTENT(content,SBS_MODES)) {
		fprintf(fp,"%s,",sbContentString(SBS_MODES));
	}
	if (TESTCONTENT(content,SBS_TIMESTAMP)) {
		fprintf(fp,"%s,",sbContentString(SBS_TIMESTAMP));
	}
	if (TESTCONTENT(content,SBS_RPY)) {
		fprintf(fp,"%s,",sbContentString(SBS_RPY));
	}
	if (TESTCONTENT(content,SBS_GYRO)) {
		fprintf(fp,"%s,",sbContentString(SBS_GYRO));
	}
	if (TESTCONTENT(content,SBS_ACCEL)) {
		fprintf(fp,"%s,",sbContentString(SBS_ACCEL));
	}
	if (TESTCONTENT(content,SBS_MAGNETO)) {
		fprintf(fp,"%s,",sbContentString(SBS_MAGNETO));
	}
	if (TESTCONTENT(content,SBS_IMUTEMP)) {
		fprintf(fp,"%s,",sbContentString(SBS_IMUTEMP));
	}
	if (TESTCONTENT(content,SBS_ALTITUDE)) {
		fprintf(fp,"%s,",sbContentString(SBS_ALTITUDE));
	}
	if (TESTCONTENT(content,SBS_PRESSURE)) {
		fprintf(fp,"%s,",sbContentString(SBS_PRESSURE));
	}
	if (TESTCONTENT(content,SBS_HRANGES)) {
		fprintf(fp,"%s,",sbContentString(SBS_HRANGES));
	}
	if (TESTCONTENT(content,SBS_XY_REL)) {
		fprintf(fp,"%s,",sbContentString(SBS_XY_REL));
	}
	if (TESTCONTENT(content,SBS_BATTERY)) {
		fprintf(fp,"%s,",sbContentString(SBS_BATTERY));
	}
	if (TESTCONTENT(content,SBS_TIMEOUT)) {
		fprintf(fp,"%s,",sbContentString(SBS_TIMEOUT));
	}
	if (TESTCONTENT(content,SBS_CHANNELS)) {
		fprintf(fp,"%s,",sbContentString(SBS_CHANNELS));
	}
	if (TESTCONTENT(content,SBS_O_ATTITUDE)) {
		fprintf(fp,"%s,",sbContentString(SBS_O_ATTITUDE));
	}
	if (TESTCONTENT(content,SBS_O_ALTITUDE)) {
		fprintf(fp,"%s,",sbContentString(SBS_O_ALTITUDE));
	}
	if (TESTCONTENT(content,SBS_O_TOL)) {
		fprintf(fp,"%s,",sbContentString(SBS_O_TOL));
	}
	if (TESTCONTENT(content,SBS_O_XY)) {
		fprintf(fp,"%s,",sbContentString(SBS_O_XY));
	}
	if (TESTCONTENT(content,SBS_O_OAVOID)) {
		fprintf(fp,"%s,",sbContentString(SBS_O_OAVOID));
	}
	if (TESTCONTENT(content,SBS_COAXSPEED)) {
		fprintf(fp,"%s,",sbContentString(SBS_COAXSPEED));
	}
	fprintf(fp,"]");
}

int sbPrintControlParameters(FILE * fp, const struct SBControlParameters * params)
{
	if (!fp) return -1;
	fprintf(fp,"baseThrust %e\n",params->baseThrust);
	fprintf(fp,"yawOffset %e\n",params->yawOffset);
	fprintf(fp,"altitudeKp %e\n",params->altitudeKp);
	fprintf(fp,"altitudeKi %e\n",params->altitudeKi);
	fprintf(fp,"altitudeKd %e\n",params->altitudeKd);
	fprintf(fp,"yawKp %e\n",params->yawKp);
	fprintf(fp,"yawKi %e\n",params->yawKi);
	fprintf(fp,"yawKd %e\n",params->yawKd);
	return 0;
}

int sbSaveControlParamters(const char * fname,
		const struct SBControlParameters * params)
{
	int res;
	FILE * fp = fopen(fname,"w");
	if (!fp) {perror("sbSaveControlParamters:");return -1;}
	res = sbPrintControlParameters(fp,params);
	fclose(fp);
	return res;
}

int sbLoadControlParameters(const char * fname,
		struct SBControlParameters * params)
{
	char line[80],pname[80];
	float value;
	int res = 0;
	FILE * fp = stdin;
	if (strcmp(fname,"-")!=0) {
		fp = fopen(fname,"r");
		if (!fp) {perror("sbLoadControlParameters:");return -1;}
	}
	while (!feof(fp)) {
		line[0] = 0;
		fgets(line,79,fp);
		if (line[0] == '#') {
			continue;
		}
		if (sscanf(line," %s %e ",pname,&value) != 2) {
			continue;
		}
		if (strcasecmp(pname,"baseThrust")==0) {
			params->baseThrust = value;
		}
		if (strcasecmp(pname,"yawOffset")==0) {
			params->yawOffset = value;
		}
		if (strcasecmp(pname,"altitudeKp")==0) {
			params->altitudeKp = value;
		}
		if (strcasecmp(pname,"altitudeKd")==0) {
			params->altitudeKd = value;
		}
		if (strcasecmp(pname,"altitudeKi")==0) {
			params->altitudeKi = value;
		}
		if (strcasecmp(pname,"yawKp")==0) {
			params->yawKp = value;
		}
		if (strcasecmp(pname,"yawKi")==0) {
			params->yawKi = value;
		}
		if (strcasecmp(pname,"yawKd")==0) {
			params->yawKd = value;
		}
	}
	if (fp != stdin) {
		fclose(fp);
	}
	printf("Loaded control parameters:\n");
	sbPrintControlParameters(stdout,params);
	return res;
}

#endif


text:
#ifndef COIN_SOVRMLTOUCHSENSOR_H
#define COIN_SOVRMLTOUCHSENSOR_H

#include <Inventor/nodes/SoSubNode.h>
#include <Inventor/fields/SoSFBool.h>
#include <Inventor/fields/SoSFVec3f.h>
#include <Inventor/fields/SoSFVec2f.h>
#include <Inventor/fields/SoSFTime.h>

class COIN_DLL_API SoVRMLTouchSensor : public SoNode
{
  typedef SoNode inherited;
  SO_NODE_HEADER(SoVRMLTouchSensor);

public:
  static void initClass(void);
  SoVRMLTouchSensor(void);

  SoSFBool enabled;
  SoSFVec3f hitNormal_changed;
  SoSFVec3f hitPoint_changed;
  SoSFVec2f hitTexCoord_changed;
  SoSFBool isActive;
  SoSFBool isOver;
  SoSFTime touchTime;

  virtual SbBool affectsState(void) const;
  virtual void handleEvent(SoHandleEventAction * action);

protected:
  virtual ~SoVRMLTouchSensor();

  virtual void notify(SoNotList * list);

private:
  SbBool isactive;
}; // class SoVRMLTouchSensor

#endif // ! COIN_SOVRMLTOUCHSENSOR_H

redpajama_set_name: RedPajamaGithub


text:
<component name="ProjectDictionaryState">
  <dictionary name="jamesromo" />
</component>


text:
id: 348
title: Gestion de communautés
date: 2010-11-10T22:29:52+00:00
author: Perrine
layout: post
guid: http://localhost:8888/?p=348
permalink: /gestion-de-communautes/
categories:
  - Portfolio
---
<!--more-->Gestion des communautés web du M sur Masson, du festival d’art émergent OUMF et du Quartier latin.

  * Élaboration de stratégies de développement des médias sociaux.
  * Création, gestion et diffusion via des comptes Facebook, Twitter et Instagram.
  * Maîtrise des outils de programmation et de suivi/analyse.


text:
require 'test_helper'

class ScenariosHelperTest < ActionView::TestCase
end


text:
from __future__ import unicode_literals

import os
import sys
from subprocess import PIPE, Popen

from django.utils import six
from django.utils.encoding import DEFAULT_LOCALE_ENCODING, force_text

from .base import CommandError

def popen_wrapper(args, os_err_exc_type=CommandError):
    """
    Friendly wrapper around Popen.

    Returns stdout output, stderr output and OS status code.
    """
    try:
        p = Popen(args, shell=False, stdout=PIPE, stderr=PIPE,
                close_fds=os.name != 'nt', universal_newlines=True)
    except OSError as e:
        strerror = force_text(e.strerror, DEFAULT_LOCALE_ENCODING,
                              strings_only=True)
        six.reraise(os_err_exc_type, os_err_exc_type('Error executing %s: %s' %
                    (args[0], strerror)), sys.exc_info()[2])
    output, errors = p.communicate()
    return (
        output,
        force_text(errors, DEFAULT_LOCALE_ENCODING, strings_only=True),
        p.returncode
    )

def handle_extensions(extensions):
    """
    Organizes multiple extensions that are separated with commas or passed by
    using --extension/-e multiple times.

    For example: running 'django-admin makemessages -e js,txt -e xhtml -a'
    would result in an extension list: ['.js', '.txt', '.xhtml']

    >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.py'])
    {'.html', '.js', '.py'}
    >>> handle_extensions(['.html, txt,.tpl'])
    {'.html', '.tpl', '.txt'}
    """
    ext_list = []
    for ext in extensions:
        ext_list.extend(ext.replace(' ', '').split(','))
    for i, ext in enumerate(ext_list):
        if not ext.startswith('.'):
            ext_list[i] = '.%s' % ext_list[i]
    return set(ext_list)

def find_command(cmd, path=None, pathext=None):
    if path is None:
        path = os.environ.get('PATH', '').split(os.pathsep)
    if isinstance(path, six.string_types):
        path = [path]
    # check if there are funny path extensions for executables, e.g. Windows
    if pathext is None:
        pathext = os.environ.get('PATHEXT', '.COM;.EXE;.BAT;.CMD').split(os.pathsep)
    # don't use extensions if the command ends with one of them
    for ext in pathext:
        if cmd.endswith(ext):
            pathext = ['']
            break
    # check if we find the command on PATH
    for p in path:
        f = os.path.join(p, cmd)
        if os.path.isfile(f):
            return f
        for ext in pathext:
            fext = f + ext
            if os.path.isfile(fext):
                return fext
    return None


text:
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.Logging;
using Moq;
using Raven.Client.Documents;
using Raven.TestDriver;
using Xunit;

namespace Raven.Migrations.Tests
{
    public class MigrationTests : RavenTestDriver
    {
        private readonly ILogger logger = new ConsoleLogger();
        private readonly List<Assembly> assemblies = new List<Assembly> { typeof(MigrationTests).Assembly };

        protected override void PreInitialize(IDocumentStore documentStore)
        {
            documentStore.Conventions.MaxNumberOfRequestsPerSession = 100;
        }

        [Fact]
        public void Can_migrate_up()
        {
            using var store = GetDocumentStore();
            var professorZoom = InitialiseWithPerson(store, "Professor", "Zoom");

            var migration = new AddFullName();
            migration.Setup(store, new MigrationOptions(), logger);

            migration.Up();

            using var session = store.OpenSession();
            var loaded = session.Load<Person>(professorZoom.Id);
            loaded.FullName.Should().Be("Professor Zoom");
        }

        [Fact]
        public void Can_migrate_down()
        {
            using var store = GetDocumentStore();
            var ladyDeathstrike = InitialiseWithPerson(store, "Lady", "Deathstrike");

            var migration = new AddFullName();
            migration.Setup(store, new MigrationOptions(), logger);

            migration.Up();
            WaitForIndexing(store);

            migration.Down();
            WaitForIndexing(store);

            using var session = store.OpenSession();
            var loaded = session.Load<Person>(ladyDeathstrike.Id);
            loaded.FullName.Should().Be(null);
        }

        [Fact(Skip = "no logging in place")]
        public void Logger_WriteInformation_is_called_when_altering_collection()
        {
            var loggerMock = new Mock<ILogger>();

            using (var store = GetDocumentStore())
            {
                var scarletSpider = InitialiseWithPerson(store, "Scarlet", "Spider");

                var migration = new AddFullName();
                migration.Setup(store, new MigrationOptions(), loggerMock.Object);

                migration.Up();
            }

            loggerMock.Verify(logger => logger.LogInformation("Updated {0} documents", 1), "Informational message should indicate how many documents were updated.");
        }

        [Fact]
        public async Task Calling_run_in_parallel_runs_migrations_only_once()
        {
            using var documentStore = GetDocumentStore();
            await new TestDocumentIndex().ExecuteAsync(documentStore);

            var instanceOne = new MigrationRunner(documentStore, new MigrationOptions() { Assemblies = assemblies }, new ConsoleLogger());
            var instanceTwo = new MigrationRunner(documentStore, new MigrationOptions() { Assemblies = assemblies }, new ConsoleLogger());

            var first = Task.Run(() => instanceOne.Run());
            var second = Task.Run(() => instanceTwo.Run());

            await Task.WhenAll(first, second);

            WaitForIndexing(documentStore);
            WaitForUserToContinueTheTest(documentStore);

            using var session = documentStore.OpenSession();
            var testDocCount = session.Query<TestDocument, TestDocumentIndex>().Count();
            testDocCount
                .Should()
                .Be(1);
        }

        private Person InitialiseWithPerson(IDocumentStore store, string firstName, string lastName)
        {
            using var session = store.OpenSession();
            var person = new Person { Id = "People/1", FirstName = firstName, LastName = lastName };
            session.Store(person);
            session.SaveChanges();
            return person;
        }

        private void InitialiseWithPeople(IDocumentStore store, List<Person> people)
        {
            using (var session = store.OpenSession())
            {
                people.ForEach(p => session.Store(p));
                session.SaveChanges();
            }
            WaitForIndexing(store);
        }
    }

    [Migration(1, "alter")]
    public class AddFullName : Migration
    {
        public override void Up()
        {
            PatchCollection("from People update { this.FullName = this.FirstName + ' ' + this.LastName; }");
        }

        public override void Down()
        {
            PatchCollection("from People update { delete this.FullName; }");
        }
    }

    public class FooBaz
    {
        public int Id { get; set; }
        public string Bar { get; set; }
    }

    public class Person
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string FullName { get; set; }
    }
}


text:
/**
 * @fileoverview gRPC-Web generated client stub for greet
 * @enhanceable
 * @public
 */

// GENERATED CODE -- DO NOT EDIT!

/* eslint-disable */
// @ts-nocheck

const grpc = {};
grpc.web = require('grpc-web');

const proto = {};
proto.greet = require('./greet_pb.js');

/**
 * @param {string} hostname
 * @param {?Object} credentials
 * @param {?grpc.web.ClientOptions} options
 * @constructor
 * @struct
 * @final
 */
proto.greet.GreeterClient =
    function(hostname, credentials, options) {
  if (!options) options = {};
  options.format = 'text';

  /**
   * @private @const {!grpc.web.GrpcWebClientBase} The client
   */
  this.client_ = new grpc.web.GrpcWebClientBase(options);

  /**
   * @private @const {string} The hostname
   */
  this.hostname_ = hostname;

};

/**
 * @param {string} hostname
 * @param {?Object} credentials
 * @param {?grpc.web.ClientOptions} options
 * @constructor
 * @struct
 * @final
 */
proto.greet.GreeterPromiseClient =
    function(hostname, credentials, options) {
  if (!options) options = {};
  options.format = 'text';

  /**
   * @private @const {!grpc.web.GrpcWebClientBase} The client
   */
  this.client_ = new grpc.web.GrpcWebClientBase(options);

  /**
   * @private @const {string} The hostname
   */
  this.hostname_ = hostname;

};

/**
 * @const
 * @type {!grpc.web.MethodDescriptor<
 *   !proto.greet.HelloRequest,
 *   !proto.greet.HelloReply>}
 */
const methodDescriptor_Greeter_SayHello = new grpc.web.MethodDescriptor(
  '/greet.Greeter/SayHello',
  grpc.web.MethodType.UNARY,
  proto.greet.HelloRequest,
  proto.greet.HelloReply,
  /**
   * @param {!proto.greet.HelloRequest} request
   * @return {!Uint8Array}
   */
  function(request) {
    return request.serializeBinary();
  },
  proto.greet.HelloReply.deserializeBinary
);

/**
 * @param {!proto.greet.HelloRequest} request The
 *     request proto
 * @param {?Object<string, string>} metadata User defined
 *     call metadata
 * @param {function(?grpc.web.RpcError, ?proto.greet.HelloReply)}
 *     callback The callback function(error, response)
 * @return {!grpc.web.ClientReadableStream<!proto.greet.HelloReply>|undefined}
 *     The XHR Node Readable Stream
 */
proto.greet.GreeterClient.prototype.sayHello =
    function(request, metadata, callback) {
  return this.client_.rpcCall(this.hostname_ +
      '/greet.Greeter/SayHello',
      request,
      metadata || {},
      methodDescriptor_Greeter_SayHello,
      callback);
};

/**
 * @param {!proto.greet.HelloRequest} request The
 *     request proto
 * @param {?Object<string, string>=} metadata User defined
 *     call metadata
 * @return {!Promise<!proto.greet.HelloReply>}
 *     Promise that resolves to the response
 */
proto.greet.GreeterPromiseClient.prototype.sayHello =
    function(request, metadata) {
  return this.client_.unaryCall(this.hostname_ +
      '/greet.Greeter/SayHello',
      request,
      metadata || {},
      methodDescriptor_Greeter_SayHello);
};

/**
 * @const
 * @type {!grpc.web.MethodDescriptor<
 *   !proto.greet.HelloRequest,
 *   !proto.greet.HelloReply>}
 */
const methodDescriptor_Greeter_SayHellos = new grpc.web.MethodDescriptor(
  '/greet.Greeter/SayHellos',
  grpc.web.MethodType.SERVER_STREAMING,
  proto.greet.HelloRequest,
  proto.greet.HelloReply,
  /**
   * @param {!proto.greet.HelloRequest} request
   * @return {!Uint8Array}
   */
  function(request) {
    return request.serializeBinary();
  },
  proto.greet.HelloReply.deserializeBinary
);

/**
 * @param {!proto.greet.HelloRequest} request The request proto
 * @param {?Object<string, string>=} metadata User defined
 *     call metadata
 * @return {!grpc.web.ClientReadableStream<!proto.greet.HelloReply>}
 *     The XHR Node Readable Stream
 */
proto.greet.GreeterClient.prototype.sayHellos =
    function(request, metadata) {
  return this.client_.serverStreaming(this.hostname_ +
      '/greet.Greeter/SayHellos',
      request,
      metadata || {},
      methodDescriptor_Greeter_SayHellos);
};

/**
 * @param {!proto.greet.HelloRequest} request The request proto
 * @param {?Object<string, string>=} metadata User defined
 *     call metadata
 * @return {!grpc.web.ClientReadableStream<!proto.greet.HelloReply>}
 *     The XHR Node Readable Stream
 */
proto.greet.GreeterPromiseClient.prototype.sayHellos =
    function(request, metadata) {
  return this.client_.serverStreaming(this.hostname_ +
      '/greet.Greeter/SayHellos',
      request,
      metadata || {},
      methodDescriptor_Greeter_SayHellos);
};

module.exports = proto.greet;


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using PodPath.FFUtils.Abstracts;
using PodPath.FFUtils.Exceptions;
using PodPath.FFUtils.Interfaces;
using PodPath.FFUtils.Results;

namespace PodPath.FFUtils
{
    public class FFConvert : FFBase, IConversion
    {
        public event ProgressChangedEventHandler ProgressChanged;

        public event ErrorOcurredEventHandler ErrorOcurred;

        private TimeSpan _streamDuration;

        public FFConvert(string pathToMpegExecutable)
            : base(pathToMpegExecutable)
        {
        }

        public ConversionResult ProcessStream(IProbe probe, string inputfileName, string outputFileName)
        {
            if (String.IsNullOrEmpty(inputfileName))
                throw new ArgumentNullException("inputfileName");

            if (String.IsNullOrEmpty(outputFileName))
                throw new ArgumentNullException("outputFileName");

            if (!File.Exists(inputfileName))
                throw new FileNotFoundException(String.Format("Input file '{0}' was not found", inputfileName));

            if (File.Exists(outputFileName))
                throw new FileNotFoundException(String.Format("Output file '{0}' already exists.", outputFileName));

            var outputDir = Path.GetDirectoryName(outputFileName);

            // if it's null or empty, assume working directory otherwise check path
            if (!String.IsNullOrEmpty(outputDir))
            {
                if (!Directory.Exists(outputDir)) throw new DirectoryNotFoundException("Output path does not exist");
            }

            // guard clause for probe instance
            if (probe == null) throw new ArgumentNullException("probe");

            // check if file is audio only
            if (!probe.IsAudioOnly(inputfileName))
                return new ConversionResult(ConversionResult.Outcome.Failed, "Input file contained video, conversion aborted.");

            try
            {

                // Start the child process.
                var conversionProcess = new Process
                {
                    StartInfo =
                    {
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        FileName = PathToExecutable,
                        Arguments = @" -i """ + inputfileName + @"""" +
                                    @" -map 0:0 -loglevel info -hide_banner -vn -ar 44100 -ac 2 -ab 192k -f mp3 """ + outputFileName + @""""
                    }
                };

                // everything seems to appear on errOut for some reason...
                conversionProcess.ErrorDataReceived += (sender, args) => HandleProgress(args.Data);

                conversionProcess.Start();
                conversionProcess.BeginOutputReadLine();
                conversionProcess.BeginErrorReadLine();

                conversionProcess.WaitForExit();

                return new ConversionResult(ConversionResult.Outcome.Success);
            }
            catch (Exception ex)
            {
                throw new ConversionException("Exception occurred while converting input file to MP3", ex);
            }

        }

        private void HandleProgress(string output)
        {
            if (output != null)
            {
                if (output.Contains("Duration"))
                {
                    // sample output - "  Duration: 00:35:56.57, start: 42513.181922, bitrate: 1463 kb/s"
                    var allInfo = output.Trim().Split(',');
                    var durationAndName = allInfo[0].Split(' ');
                    var durationInfo = durationAndName[1].Split(':');

                    var hours = Convert.ToInt32(durationInfo[0]);
                    var mins = Convert.ToInt32(durationInfo[1]);
                    var secs = Convert.ToInt32(durationInfo[2].Split('.')[0]);

                    _streamDuration = new TimeSpan(0, hours, mins, secs);
                }

                // sample output - "size=     470kB time=00:00:19.98 bitrate= 192.5kbits/s    "
                if (output.StartsWith("size"))
                {
                    var delimiter = new string[] { "time=" };
                    var allInfo = output.Split(delimiter, StringSplitOptions.None);
                    var timeString = allInfo[1].Split(' ')[0];
                    var time = timeString.Split(':');

                    var hours = Convert.ToInt32(time[0]);
                    var mins = Convert.ToInt32(time[1]);
                    var secs = Convert.ToInt32(time[2].Split('.')[0]);

                    var currentLocation = new TimeSpan(0, hours, mins, secs);

                    if (_streamDuration != null)
                    {
                        var timeSpanLocation = String.Format("{0:00}:{1:00}:{2:00}", currentLocation.Hours, currentLocation.Minutes,
                            currentLocation.Seconds);
                        var percentageComplete = Math.Truncate(Divide(currentLocation, _streamDuration) * 100);
                        if (ProgressChanged != null) ProgressChanged((int)percentageComplete, timeSpanLocation);
                    }
                    else
                    {
                        if (ProgressChanged != null) ProgressChanged(0, "Unknown");
                    }
                }
            }

        }

        public static double Divide(TimeSpan dividend, TimeSpan divisor)
        {
            return (double)dividend.Ticks / (double)divisor.Ticks;
        }
    }
}


text:
class Foo:
        def __init__(self):
            self.tmp = False

        def extract_method(self, condition1, condition2, condition3, condition4):
            list = (1, 2, 3)
            a = 6
            b = False
            if a in list or self.tmp:
                if condition1:
                    print(condition1)
                if b is not condition2:
                    print(b)
            else:
                <selection>self.tmp2 = True
                if condition3:
                    print(condition3)
                if condition4:
                    print(condition4)
                print("misterious extract method test")</selection>
f = Foo()
f.extract_method(True, True, True, True)


text:
<?php

namespace Chamilo\Core\Repository\ContentObject\Assignment\Display\Component;

use Chamilo\Core\Repository\ContentObject\Assignment\Display\Manager;
use Chamilo\Core\Repository\ContentObject\Assignment\Display\Service\EntryDownloader;
use Chamilo\Libraries\Architecture\Exceptions\UserException;

/**
 *
 * @package Chamilo\Core\Repository\ContentObject\Assignment\Display\Component
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 * @author Eduard Vossen <eduard.vossen@ehb.be>
 */
class DownloaderComponent extends Manager
{

    /**
     * @return string|void
     * @throws \Chamilo\Libraries\Architecture\Exceptions\UserException
     */
    public function run()
    {
        $entryCompressor = new EntryDownloader(
            $this->getAssignmentServiceBridge(), $this->getRightsService(), $this->getArchiveCreator(),
            $this->getUser(), $this->getAssignment()
        );

        try
        {
            $entryCompressor->downloadByRequest($this->getRequest());
        }
        catch(\Exception $exception)
        {
            $this->getExceptionLogger()->logException($exception);
            throw new UserException($this->getTranslator()->trans('EntriesNotDownloadable', [], Manager::context()));
        }
    }

    /**
     * @return \Chamilo\Libraries\File\Compression\ArchiveCreator\ArchiveCreator
     */
    protected function getArchiveCreator()
    {
        return $this->getService('chamilo.libraries.file.compression.archive_creator.archive_creator');
    }
}


text:
package io.dropwizard.request.logging;

import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.Resources;
import io.dropwizard.configuration.YamlConfigurationFactory;
import io.dropwizard.jackson.DiscoverableSubtypeResolver;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.logging.ConsoleAppenderFactory;
import io.dropwizard.logging.FileAppenderFactory;
import io.dropwizard.logging.SyslogAppenderFactory;
import io.dropwizard.validation.BaseValidator;
import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class RequestLogFactoryTest {
    private LogbackAccessRequestLogFactory logbackAccessRequestLogFactory;

    @Before
    public void setUp() throws Exception {
        final ObjectMapper objectMapper = Jackson.newObjectMapper();
        objectMapper.getSubtypeResolver().registerSubtypes(ConsoleAppenderFactory.class,
                                                           FileAppenderFactory.class,
                                                           SyslogAppenderFactory.class);
        this.logbackAccessRequestLogFactory = new YamlConfigurationFactory<>(LogbackAccessRequestLogFactory.class,
                                                     BaseValidator.newValidator(),
                                                     objectMapper, "dw")
                .build(new File(Resources.getResource("yaml/requestLog.yml").toURI()));
    }

    @Test
    public void fileAppenderFactoryIsSet() {
        assertThat(logbackAccessRequestLogFactory).isNotNull();
        assertThat(logbackAccessRequestLogFactory.getAppenders()).isNotNull();
        assertThat(logbackAccessRequestLogFactory.getAppenders().size()).isEqualTo(1);
        assertThat(logbackAccessRequestLogFactory.getAppenders().get(0))
            .isInstanceOf(FileAppenderFactory.class);
    }

    @Test
    public void isDiscoverable() throws Exception {
        assertThat(new DiscoverableSubtypeResolver().getDiscoveredSubtypes())
            .contains(LogbackAccessRequestLogFactory.class);
    }
}


text:
To deploy one or more functions all you need to do is run `apex deploy`. Apex deploys are idempotent; a build is created
for each function, and Apex performs a checksum to see if the deployed function matches the local build, if so
it's not deployed.

After deploy Apex will cleanup old function's versions stored on AWS Lambda leaving only few. Number of retained versions
can be specified in project or function configuration.

If you prefer to be explicit you can pass one or more function names to `apex deploy`. You may also perform shell-style globbing matches with any command accepting function names, such as `deploy`, `logs`, and `rollback`.

## Examples

Deploy all functions in the current directory:

```sh
$ apex deploy
```

Deploy all functions in the directory "~/dev/myapp":

```sh
$ apex deploy -C ~/dev/myapp
```

Deploy specific functions:

```sh
$ apex deploy auth
$ apex deploy auth api
```

Deploy all functions which name starts with "auth":

```sh
$ apex deploy auth*
```

Deploy all functions ending with "_reporter".

```sh
$ apex deploy *_reporter
```


text:
@extends('layouts.admin')
@section('admincontent')

Add Tutorial

{!! Form::model($tutorial, [
'method' => 'POST',
'action' => ['ResourcesController@createTutorial', $tutorial->id],
'class' => 'form-horizontal'
]) !!}

@include('panel.resources.add_edit_tutorial_form')

{!! Form::close() !!}

@endsection


text:
package jp.gr.java_conf.ke.util;

public class Timer {

	public static boolean sleep(long milis) {
		try {
			Thread.sleep(milis);
		} catch (InterruptedException e) {
			return false;
		}
		return true;
	}

}


text:
package com.github.kohanyirobert.sggc;

import com.google.common.base.Objects;

import java.net.URL;

final class DefaultRequest implements Request {

  private final Protocol protocol;
  private final Output output;
  private final String address;
  private final Location location;
  private final Bounds bounds;
  private final Language language;
  private final Region region;
  private final boolean sensor;
  private final String client;
  private final String signature;
  private final URL url;

  // @do-not-check-next-line ParameterNumber
  DefaultRequest(
      Protocol protocol,
      Output output,
      String address,
      Location location,
      Bounds bounds,
      Region region,
      Language language,
      String client,
      String signature,
      boolean sensor,
      URL url) {
    this.protocol = protocol;
    this.output = output;
    this.address = address;
    this.location = location;
    this.bounds = bounds;
    this.region = region;
    this.language = language;
    this.client = client;
    this.signature = signature;
    this.sensor = sensor;
    this.url = url;
  }

  @Override
  public Protocol protocol() {
    return protocol;
  }

  @Override
  public Output output() {
    return output;
  }

  @Override
  public String address() {
    return address;
  }

  @Override
  public Location location() {
    return location;
  }

  @Override
  public Bounds bounds() {
    return bounds;
  }

  @Override
  public Language language() {
    return language;
  }

  @Override
  public Region region() {
    return region;
  }

  @Override
  public boolean sensor() {
    return sensor;
  }

  @Override
  public String client() {
    return client;
  }

  @Override
  public String signature() {
    return signature;
  }

  @Override
  public URL url() {
    return url;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(
        protocol(),
        output(),
        address(),
        location(),
        bounds(),
        region(),
        language(),
        Boolean.valueOf(sensor()),
        client(),
        signature());
  }

  // @do-not-check-next-line CyclomaticComplexity
  @Override
  public boolean equals(Object object) {
    if (object instanceof DefaultRequest) {
      DefaultRequest other = (DefaultRequest) object;
      return protocol().equals(other.protocol())
          && output().equals(other.output())
          && Objects.equal(address(), other.address())
          && Objects.equal(location(), other.location())
          && Objects.equal(bounds(), other.bounds())
          && Objects.equal(region(), other.region())
          && Objects.equal(language(), other.language())
          && sensor() == other.sensor()
          && Objects.equal(client(), other.client())
          && Objects.equal(signature(), other.signature());
    }
    return false;
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(Request.class)
        .add("protocol", protocol())
        .add("output", output())
        .add("address", address())
        .add("latlng", location())
        .add("bounds", bounds())
        .add("region", region())
        .add("language", language())
        .add("sensor", String.valueOf(sensor))
        .add("client", client())
        .add("signature", signature())
        .toString();
  }
}


text:
(function () {

    jQuery.fn.combobox = function (selectOptions) {

        return this.each(function () {
            var newCombobox = new Combobox(this, selectOptions);
            jQuery.combobox.instances.push(newCombobox);
        });

    };

    jQuery.combobox = {
        instances : []
    };

    var Combobox = function (textInputElement, selectOptions) {
        this.textInputElement = jQuery(textInputElement);
        this.textInputElement.wrap(
            ''
        );
        this.selector = new ComboboxSelector(this);
        this.setSelectOptions(selectOptions);
        var inputHeight = this.textInputElement.outerHeight();
        var buttonLeftPosition = this.textInputElement.outerWidth() + 0;
        var showSelectorButton = jQuery(
            '

'
        );
        this.textInputElement.css('margin', '0 '+showSelectorButton.outerWidth()+'px 0 0');
        showSelectorButton.insertAfter(this.textInputElement);
        var thisSelector = this.selector;
        var thisCombobox = this;
        showSelectorButton.click(function (e) {
            jQuery('html').trigger('click');
            thisSelector.buildSelectOptionList();
            thisSelector.show();
            thisCombobox.focus();
            return false;
        });
        this.bindKeypress();
    };

    Combobox.prototype = {

        setSelectOptions : function (selectOptions) {
            this.selector.setSelectOptions(selectOptions);
            this.selector.buildSelectOptionList(this.getValue());
        },

        bindKeypress : function () {
            var thisCombobox = this;
            this.textInputElement.keyup(function (event) {
                if (event.keyCode == Combobox.keys.TAB
                    || event.keyCode == Combobox.keys.SHIFT)
                {
                    return;
                }
                if (event.keyCode != Combobox.keys.DOWNARROW
                    && event.keyCode != Combobox.keys.UPARROW
                    && event.keyCode != Combobox.keys.ESCAPE
                    && event.keyCode != Combobox.keys.ENTER)
                {
                    thisCombobox.selector.buildSelectOptionList(thisCombobox.getValue());
                }
                if (event.keyCode === Combobox.keys.ENTER)
                {
                    return;
                }
                thisCombobox.selector.show()
            });
        },

        setValue : function (value) {
            var oldValue = this.textInputElement.val();
            this.textInputElement.val(value);
            if (oldValue != value) {
                this.textInputElement.trigger('change');
            }
        },

        getValue : function () {
            return this.textInputElement.val();
        },

        focus : function () {
            this.textInputElement.trigger('focus');
        }

    };

    Combobox.keys = {
        UPARROW : 38,
        DOWNARROW : 40,
        ENTER : 13,
        ESCAPE : 27,
        TAB : 9,
        SHIFT : 16
    };

    var ComboboxSelector = function (combobox) {
        this.combobox = combobox;
        this.optionCount = 0;
        this.selectedIndex = -1;
        this.allSelectOptions = [];
        var selectorTop = combobox.textInputElement.outerHeight();
        var selectorWidth = combobox.textInputElement.outerWidth();
        this.selectorElement = jQuery(
            '

'
        ).insertAfter(this.combobox.textInputElement);
        var thisSelector = this;
        this.keypressHandler = function (e) {
            if (e.keyCode == Combobox.keys.DOWNARROW) {
                thisSelector.selectNext();
            } else if (e.keyCode == Combobox.keys.UPARROW) {
                thisSelector.selectPrevious();
            } else if (e.keyCode == Combobox.keys.ESCAPE) {
                thisSelector.hide();
                thisSelector.combobox.focus();
            } else if (e.keyCode == Combobox.keys.ENTER) {
                if(thisSelector.selectedIndex !== -1){
                    e.preventDefault();
                }
                thisSelector.combobox.setValue(thisSelector.getSelectedValue());
                thisSelector.combobox.focus();
                thisSelector.hide();
            } else if(e.keyCode == Combobox.keys.TAB){
                thisSelector.hide();
            }
        }

    };

    ComboboxSelector.prototype = {

        setSelectOptions : function (selectOptions) {
            this.allSelectOptions = selectOptions;
        },

        buildSelectOptionList : function (startingLetters) {
            if (! startingLetters) {
                startingLetters = "";
            }
            this.unselect();
            this.selectorElement.empty();
            var selectOptions = [];
            this.selectedIndex = -1;
            var i;
            for (i=0; i < this.allSelectOptions.length; i++) {
                if (! startingLetters.length
                    || this.allSelectOptions[i].toLowerCase().indexOf(startingLetters.toLowerCase()) === 0)
                {
                    selectOptions.push(this.allSelectOptions[i]);
                }
            }
            this.optionCount = selectOptions.length;
            var ulElement = jQuery('

').appendTo(this.selectorElement);
            for (i = 0; i < selectOptions.length; i++) {
                ulElement.append('
'+selectOptions[i]+'
');
            }
            var thisSelector = this;
            this.selectorElement.find('li').click(function (e) {
                thisSelector.hide();
                thisSelector.combobox.setValue(this.innerHTML);
                thisSelector.combobox.focus();
            });
            this.selectorElement.mouseover(function (e) {
                thisSelector.unselect();
            });
            this.htmlClickHandler = function () {
                thisSelector.hide();
            };

        },

        show : function () {
            if (this.selectorElement.find('li').length < 1
                || this.selectorElement.is(':visible'))
            {
                return false;
            }
            jQuery('html').keydown(this.keypressHandler);
            this.selectorElement.slideDown('fast');
            jQuery('html').click(this.htmlClickHandler);
            return true;
        },

        hide : function () {
            jQuery('html').unbind('keydown', this.keypressHandler);
            jQuery('html').unbind('click', this.htmlClickHandler);
            this.selectorElement.unbind('click');
            this.unselect();
            this.selectorElement.hide();
        },

        selectNext : function () {
            var newSelectedIndex = this.selectedIndex + 1;
            if (newSelectedIndex > this.optionCount - 1) {
                newSelectedIndex = this.optionCount - 1;
            }
            this.select(newSelectedIndex);
        },

        selectPrevious : function () {
            var newSelectedIndex = this.selectedIndex - 1;
            if (newSelectedIndex < 0) {
                newSelectedIndex = 0;
            }
            this.select(newSelectedIndex);
        },

        select : function (index) {
            this.unselect();
        	this.selectorElement.find('li:eq('+index+')').addClass('selected');
        	this.selectedIndex = index;
        },

        unselect : function () {
        	this.selectorElement.find('li').removeClass('selected');
        	this.selectedIndex = -1;
        },

        getSelectedValue : function () {
            if(this.selectedIndex !== -1){
                return this.selectorElement.find('li').get(this.selectedIndex).innerHTML;
            } else {
                return this.combobox.textInputElement.val();
            }
        }

    };

})();


text:
package org.apache.lucene.search;

import java.io.IOException;
import java.io.Serializable;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.LuceneTestCase;

/**
 * Unit test for sorting code.
 *
 */

public class TestCustomSearcherSort
extends LuceneTestCase
implements Serializable {

    private Directory index = null;
    private Query query = null;
    // reduced from 20000 to 2000 to speed up test...
    private final static int INDEX_SIZE = 2000;

  public TestCustomSearcherSort (String name) {
    super (name);
  }

  public static void main (String[] argv) {
      TestRunner.run (suite());
  }

  public static Test suite() {
    return new TestSuite (TestCustomSearcherSort.class);
  }

  // create an index for testing
  private Directory getIndex()
  throws IOException {
          RAMDirectory indexStore = new RAMDirectory ();
          IndexWriter writer = new IndexWriter (indexStore, new StandardAnalyzer(org.apache.lucene.util.Version.LUCENE_CURRENT), true, IndexWriter.MaxFieldLength.LIMITED);
          RandomGen random = new RandomGen(newRandom());
          for (int i=0; i<INDEX_SIZE; ++i) { // don't decrease; if to low the problem doesn't show up
          Document doc = new Document();
              if((i%5)!=0) { // some documents must not have an entry in the first sort field
                  doc.add (new Field("publicationDate_", random.getLuceneDate(), Field.Store.YES, Field.Index.NOT_ANALYZED));
              }
              if((i%7)==0) { // some documents to match the query (see below)
                  doc.add (new Field("content", "test", Field.Store.YES, Field.Index.ANALYZED));
              }
              // every document has a defined 'mandant' field
              doc.add(new Field("mandant", Integer.toString(i%3), Field.Store.YES, Field.Index.NOT_ANALYZED));
              writer.addDocument (doc);
          }
          writer.optimize ();
          writer.close ();
      return indexStore;
  }

  /**
   * Create index and query for test cases.
   */
  @Override
  public void setUp() throws Exception {
          super.setUp();
          index = getIndex();
          query = new TermQuery( new Term("content", "test"));
  }

  /**
   * Run the test using two CustomSearcher instances.
   */
  public void testFieldSortCustomSearcher() throws Exception {
    // log("Run testFieldSortCustomSearcher");
    // define the sort criteria
      Sort custSort = new Sort(
              new SortField("publicationDate_", SortField.STRING),
              SortField.FIELD_SCORE
      );
      Searcher searcher = new CustomSearcher (index, 2);
      // search and check hits
    matchHits(searcher, custSort);
  }
  /**
   * Run the test using one CustomSearcher wrapped by a MultiSearcher.
   */
  public void testFieldSortSingleSearcher() throws Exception {
    // log("Run testFieldSortSingleSearcher");
    // define the sort criteria
      Sort custSort = new Sort(
              new SortField("publicationDate_", SortField.STRING),
              SortField.FIELD_SCORE
      );
      Searcher searcher = new MultiSearcher(new Searcher[] { new CustomSearcher(
        index, 2) });
      // search and check hits
    matchHits(searcher, custSort);
  }
  /**
   * Run the test using two CustomSearcher instances.
   */
  public void testFieldSortMultiCustomSearcher() throws Exception {
    // log("Run testFieldSortMultiCustomSearcher");
    // define the sort criteria
      Sort custSort = new Sort(
              new SortField("publicationDate_", SortField.STRING),
              SortField.FIELD_SCORE
      );
      Searcher searcher =
          new MultiSearcher(new Searchable[] {
                  new CustomSearcher (index, 0),
                  new CustomSearcher (index, 2)});
      // search and check hits
    matchHits(searcher, custSort);
  }

  // make sure the documents returned by the search match the expected list
  private void matchHits (Searcher searcher, Sort sort)
  throws IOException {
      // make a query without sorting first
    ScoreDoc[] hitsByRank = searcher.search(query, null, 1000).scoreDocs;
    checkHits(hitsByRank, "Sort by rank: "); // check for duplicates
        Map resultMap = new TreeMap();
        // store hits in TreeMap - TreeMap does not allow duplicates; existing entries are silently overwritten
        for(int hitid=0;hitid<hitsByRank.length; ++hitid) {
            resultMap.put(
                    Integer.valueOf(hitsByRank[hitid].doc),  // Key:   Lucene Document ID
                    Integer.valueOf(hitid));				// Value: Hits-Objekt Index
        }

        // now make a query using the sort criteria
    ScoreDoc[] resultSort = searcher.search (query, null, 1000, sort).scoreDocs;
    checkHits(resultSort, "Sort by custom criteria: "); // check for duplicates

        // besides the sorting both sets of hits must be identical
        for(int hitid=0;hitid<resultSort.length; ++hitid) {
            Integer idHitDate = Integer.valueOf(resultSort[hitid].doc); // document ID from sorted search
            if(!resultMap.containsKey(idHitDate)) {
                log("ID "+idHitDate+" not found. Possibliy a duplicate.");
            }
            assertTrue(resultMap.containsKey(idHitDate)); // same ID must be in the Map from the rank-sorted search
            // every hit must appear once in both result sets --> remove it from the Map.
            // At the end the Map must be empty!
            resultMap.remove(idHitDate);
        }
        if(resultMap.size()==0) {
            // log("All hits matched");
        } else {
        log("Couldn't match "+resultMap.size()+" hits.");
        }
        assertEquals(resultMap.size(), 0);
  }

  /**
   * Check the hits for duplicates.
   * @param hits
   */
    private void checkHits(ScoreDoc[] hits, String prefix) {
        if(hits!=null) {
            Map idMap = new TreeMap();
            for(int docnum=0;docnum<hits.length;++docnum) {
                Integer luceneId = null;

                luceneId = Integer.valueOf(hits[docnum].doc);
                if(idMap.containsKey(luceneId)) {
                    StringBuilder message = new StringBuilder(prefix);
                    message.append("Duplicate key for hit index = ");
                    message.append(docnum);
                    message.append(", previous index = ");
                    message.append(((Integer)idMap.get(luceneId)).toString());
                    message.append(", Lucene ID = ");
                    message.append(luceneId);
                    log(message.toString());
                } else {
                    idMap.put(luceneId, Integer.valueOf(docnum));
                }
            }
        }
    }

    // Simply write to console - choosen to be independant of log4j etc
    private void log(String message) {
        System.out.println(message);
    }

    public class CustomSearcher extends IndexSearcher {
        private int switcher;
        /**
         * @param directory
         * @throws IOException
         */
        public CustomSearcher(Directory directory, int switcher) throws IOException {
            super(directory, true);
            this.switcher = switcher;
        }
        /**
         * @param r
         */
        public CustomSearcher(IndexReader r, int switcher) {
            super(r);
            this.switcher = switcher;
        }
        /* (non-Javadoc)
         * @see org.apache.lucene.search.Searchable#search(org.apache.lucene.search.Query, org.apache.lucene.search.Filter, int, org.apache.lucene.search.Sort)
         */
        @Override
        public TopFieldDocs search(Query query, Filter filter, int nDocs,
                Sort sort) throws IOException {
            BooleanQuery bq = new BooleanQuery();
            bq.add(query, BooleanClause.Occur.MUST);
            bq.add(new TermQuery(new Term("mandant", Integer.toString(switcher))), BooleanClause.Occur.MUST);
            return super.search(bq, filter, nDocs, sort);
        }
        /* (non-Javadoc)
         * @see org.apache.lucene.search.Searchable#search(org.apache.lucene.search.Query, org.apache.lucene.search.Filter, int)
         */
        @Override
        public TopDocs search(Query query, Filter filter, int nDocs)
        throws IOException {
            BooleanQuery bq = new BooleanQuery();
            bq.add(query, BooleanClause.Occur.MUST);
            bq.add(new TermQuery(new Term("mandant", Integer.toString(switcher))), BooleanClause.Occur.MUST);
            return super.search(bq, filter, nDocs);
        }
    }
    private class RandomGen {
      RandomGen(Random random) {
        this.random = random;
      }
      private Random random;
      private Calendar base = new GregorianCalendar(1980, 1, 1);

      // Just to generate some different Lucene Date strings
      private String getLuceneDate() {
        return DateTools.timeToString(base.getTimeInMillis() + random.nextInt() - Integer.MIN_VALUE, DateTools.Resolution.DAY);
      }
    }
}


text:
module Azure::CognitiveServices::Mgmt::V2017_04_18
  module Models
    #
    # SkuCapability indicates the capability of a certain feature.
    #
    class SkuCapability

      include MsRestAzure

      # @return [String] The name of the SkuCapability.
      attr_accessor :name

      # @return [String] The value of the SkuCapability.
      attr_accessor :value

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


text:
__pragma__ ('alias', 'S', '$')

def sendMessage():
    message = prompt("Scrivi qui il messaggio:", "Nessun messaggio")
    print("ricevuto", message)
    csrftoken = S("[name=csrfmiddlewaretoken]").val()
    sender = S("[name=envelope_username]").val()
    receiver = 'admin'
    data = {
        'message':message,
        'sender':sender,
        'receiver': receiver,
    }
    S.ajax({
        'method': 'POST',
        'headers': {
            'X_CSRF_TOKEN':csrftoken,
            'X-CSRFToken':csrftoken,
        },
        'data': data,
        'url': 'back/envelope',
        'complete': lambda d: alert("Messaggio inviato"),
    })

def clean(*args):
    for id in args:
        S("#{}".format(id)).empty()

def hide(*args):
    for id in args:
        S("#{}".format(id)).css('visibility', 'hidden')

def collapse_table(id):
    if S("#{} tbody tr:first-child".format(id)).css('visibility') == 'hidden':
        S("#{} tbody tr:first-child".format(id)).css('visibility', 'visible')
        S("#{} tbody tr:not(:first-child)".format(id)).show()
    else:
        S("#{} tbody tr:first-child".format(id)).css('visibility', 'hidden')
        S("#{} tbody tr:not(:first-child)".format(id)).hide()

def load(id, query):
    print('load', id, query)
    hide(id)
    S.ajax({
        'method': 'GET',
        'url': query,
        'success': lambda d: S("#{}".format(id)).html(d),
        'error': lambda t, e: S("#{}".format(id)).html(e),
        'complete': lambda d: typeset_and_show(id),})
    if id in ['board', 'admin_board']:
        window.scrollTo(0, 0)

def edit(data={}):
    print('active.edit' + str(data))
    if 'value' not in data:
        data['value'] = S("[name={}]".format(data['attr'])).val()
    if 'csrf' in data:
        csrftoken = data['csrf']
    else:
        csrftoken = S("[name=csrfmiddlewaretoken]").val()
    S.ajax({
        'method': 'POST',
        'headers': {
            'X_CSRF_TOKEN':csrftoken,
            'X-CSRFToken':csrftoken,
        },
        'data': data,
        'url': 'back/edit',
        'complete': lambda d: load(data['attr'], 'html/admin-table?serial={}&attr={}'.format(data['serial'], data['attr'])),
    })
    return False

def new_model(serial=None, attr=None, model=None, csrf=None):
    print(serial, attr, model, csrf)
    data = {}
    data['serial'] = serial
    data['attr'] = attr
    data['model'] = model
    S.ajax({
        'method': 'POST',
        'headers': {
            'X_CSRF_TOKEN':csrf,
            'X-CSRFToken':csrf,
        },
        'data': data,
        'url': 'back/new',
        'success': lambda d: load('admin_board', 'html/admin-model?serial={}'.format(d)),
    })

def show(*args):
    for id in args:
        S("#{}".format(id)).show()
        S("#{}".format(id)).css('visibility', 'visible')

def submit():
    def wrong_answer(d, e):
        if d['status']=='401':
            load('board', "html/login")
        else:
            load('board', 'html/solution?status=wrong&serial={}&answer={}'.format(data['serial'], data['answer']))
    hide('board')
    kind = S("[name=kind]").val()
    csrftoken = S("[name=csrfmiddlewaretoken]").val();
    if kind=='bool':
        answer = S("input:checked").val()
    elif kind=='multi':
        answer = S("input:checked").val()
    elif kind=='open':
        answer = S("#textInput").val()
    else:
        answer = 'done'
    required = S("[name=required]").val()
    data = {
        'serial': S("h1 small").html(),
        'answer': answer,
        'required': required,
    }
    S.ajax({
        'method': 'POST',
        'headers': {
            'X_CSRF_TOKEN':csrftoken,
            'X-CSRFToken':csrftoken,},
        'data': data,
        'url': 'back/submit',
        'success': lambda d: load('board', 'html/solution?status=correct&serial={}&answer={}'.format(data['serial'], data['answer'])),
        'error': wrong_answer,
    })
    return False

def common_truth(s):
    if s.lower() in ['true', 'vero']:
        return 'true'
    elif s.lower() in ['false', 'falso']:
        return 'false'
    else:
        raise ValueError("{} is not bool".format(s))

def typeset_and_show(id):
    MathJax.Hub.Queue(['Typeset', MathJax.Hub])
    show(id)


text:
<img src="https://uppy.io/images/logos/uppy-dog-head-arrow.svg" width="120" alt="Uppy logo: a superman puppy in a pink suit" align="right">

[![npm version](https://img.shields.io/npm/v/@uppy/screen-capture.svg?style=flat-square)](https://www.npmjs.com/package/@uppy/screen-capture)
![CI status for Uppy tests](https://github.com/transloadit/uppy/workflows/Tests/badge.svg)
![CI status for Companion tests](https://github.com/transloadit/uppy/workflows/Companion/badge.svg)
![CI status for browser tests](https://github.com/transloadit/uppy/workflows/End-to-end%20tests/badge.svg)

The screen capture plugin for Uppy lets you take photos and record videos with a built-in camera on desktop and mobile devices.

Uppy is being developed by the folks at [Transloadit](https://transloadit.com), a versatile file encoding service.

## Example

```js
import Uppy from '@uppy/core'
import ScreenCapture from '@uppy/screen-capture'

const uppy = new Uppy()
uppy.use(ScreenCapture)
```

## Installation

```bash
$ npm install @uppy/screen-capture
```

Alternatively, you can also use this plugin in a pre-built bundle from Transloadit's CDN: Edgly. In that case `Uppy` will attach itself to the global `window.Uppy` object. See the [main Uppy documentation](https://uppy.io/docs/#Installation) for instructions.

## Documentation

Documentation for this plugin can be found on the [Uppy website](https://uppy.io/docs/screen-capture).

## License

[The MIT License](./LICENSE).


text:
package org.apache.hadoop.eclipse.server;

/**
 * Interface for updating/adding jobs to the MapReduce Server view.
 */
public interface IJobListener {

  void jobChanged(HadoopJob job);

  void jobAdded(HadoopJob job);

  void jobRemoved(HadoopJob job);

  void publishStart(JarModule jar);

  void publishDone(JarModule jar);

}


text:
require 'zendesk_deployment'

module Zendesk::Deployment
  module CodeChanges
    def self.extended(config)
      config.extend(Utils)

      config.load do
        required_variable :revision, :provided_by => :mirror_strategy
        required_variable :current_revision, :provided_by => :mirror_strategy
      end
    end

    # helper method to speed up deploys by avoiding precompile
    # try to sync over old assets if they did not change or execute block
    #
    # on_outdated_assets do
    #  run "rake assets:precompile"
    # end
    def on_outdated_assets
      if changes_in?("Gemfile", "Gemfile.lock", "vendor/assets", "app/assets", "lib/assets") || !sync_from_last_release("public/assets")
        yield
      end
    end

    # changes to last release (in other folder: alpha -> omega)
    def changes_in?(*files)
      changed_files = `git diff --name-only #{current_revision} #{revision}`.split

      unless $?.success?
        $stderr.puts "git diff failed, assuming changed."
        return true
      end

      changed_files.any? { |c| files.any? { |f| c.start_with?(f) } }
    end

    private

    def sync_from_last_release(folder)
      return unless current_path

      source = "#{current_path}/#{folder}"
      target = "#{release_path}/#{folder}"

      run_success?("test -d #{source} && grep #{current_revision} #{current_path}/REVISION && rsync -a #{source}/. #{target}")
    end

    def run_success?(command)
      run command
    rescue Capistrano::CommandError
      false
    else
      true
    end

    Capistrano::Configuration.instance(:must_exist).extend(CodeChanges)
  end
end


text:
/*
 * user.js: Instance of a rackspace cloud databases user
 *
 * (C) 2013 Andrew Regner
 *
 * Inspired by node-cloudservers from Nodejitsu &
 *      clouddns from davidandrewcope
 *
 * MIT LICENSE
 *
 */

var rackspace = require('../rackspace-openstack');

var DatabaseUser = function(instance, details) {
    if (!details) {
        throw new Error('DatabaseUser must be constructed with at-least basic details.')
    }

    this.instance = instance;
    this._setProperties(details);
};

DatabaseUser.prototype = {

    /**
     * @name DatabaseUser._setProperties
     *
     * @description Loads the properties of an object into this instance
     *
     * @param {Object}      details     the details to load
     */
    _setProperties: function(details) {
        var self = this;
        this.name = details.name;
        this.password = details.password;

        if (details.databases) {
            var dbs = [];

            for (var i = 0; i < details.databases.length; i++) {
                dbs.push(new rackspace.Database(self.instance, details.databases[i]));
            }

            this.databases = dbs;
        }
    }
};

exports.DatabaseUser = DatabaseUser;