text:
/*
 *
 *
 *  Created on:
 *      Author: Jose Luis Sanchez-Lopez
 */

#include "droneMissionPlannerROSModule.h"

using namespace std;

DroneMissionPlanner::DroneMissionPlanner() : DroneModule(droneModule::active,FREQ_MISSION_PLANNER)
{
    if(!init())
        cout<<"Error init"<<endl;

    return;
}

DroneMissionPlanner::~DroneMissionPlanner()
{
	close();
	return;
}

void DroneMissionPlanner::open(ros::NodeHandle & nIn, std::string moduleName)
{
	//Node
    DroneModule::open(nIn,moduleName);

    //Set mission
    MyMissionPlanner.setMission(stackPath+"configs/drone"+stringId+"/configMission.xml");

    //Init mission
    submissionCounter=MyMissionPlanner.submissionTree.at(0);
    taskCounter=MyMissionPlanner.taskTree.at(0).at(0);

    cout<<" .init submission="<<submissionCounter<<endl;
    cout<<" .init task="<<taskCounter<<endl;

    //// Topics ///
    ///subs
    // rostopic pub -1 /drone1/ArucoSlam_EstimatedPose droneMsgsROS/dronePose -- 123 0.0 0.0 1.5 0.0 0.0 0.0 "a" "a" "a"
    dronePoseSub = n.subscribe(DRONE_MISSION_PLANNER_POSE_SUBSCRIPTION, 1, &DroneMissionPlanner::dronePoseCallback, this);
    // rostopic pub -1 /drone1/droneMissionHLCommandAck droneMsgsROS/droneHLCommandAck -- 123 true
    droneHLCommAckSub = n.subscribe(DRONE_MISSION_PLANNER_HL_COMMAND_ACK, 1, &DroneMissionPlanner::droneHLCommandAckCallback, this);

    droneGoTaskSub = n.subscribe(DRONE_MISSION_GO_TASK_SUBS, 1, &DroneMissionPlanner::droneGoTaskCallback, this);

    droneYawRefCommandSub = n.subscribe(DRONE_MISSION_YAW_REF_CMD_SUBS, 1, &DroneMissionPlanner::droneYawRefCommandCallback, this);

    ///pub
    droneHLCommPub=n.advertise<droneMsgsROS::droneHLCommand>(DRONE_MISSION_PLANNER_HL_COMMAND, 1, true);
    dronePositionRefCommandPub=n.advertise<droneMsgsROS::dronePositionRefCommand>(DRONE_MISSION_PLANNER_MISSION_POINT_REF, 1, true);
    droneYawToLookPub=n.advertise<droneMsgsROS::droneYawRefCommand>(DRONE_MISSION_PLANNER_YAW_TO_LOOK_PUB, 1, true);
    dronePointToLookPub=n.advertise<droneMsgsROS::dronePositionRefCommand>(DRONE_MISSION_PLANNER_POINT_TO_LOOK_PUB, 1, true);
    droneMissionInfoPub=n.advertise<droneMsgsROS::droneMissionInfo>(DRONE_MISSION_INFO_PUB, 1, true);

    //services
    suspendServerSrv=n.advertiseService(moduleName+"/suspend",&DroneMissionPlanner::suspendServCall,this);
    resumeServerSrv=n.advertiseService(moduleName+"/resume",&DroneMissionPlanner::resumeServCall,this);

    //Flag of module opened
    droneModuleOpened=true;

    //Start TODO JL_to remove!!
    //startVal();

	//End
	return;
}

void DroneMissionPlanner::dronePoseCallback(const droneMsgsROS::dronePose::ConstPtr& msg)
{
    dronePoseMsg.time=msg->time;
    dronePoseMsg.x=msg->x;
    dronePoseMsg.y=msg->y;
    dronePoseMsg.z=msg->z;
    dronePoseMsg.yaw=msg->yaw;
    dronePoseMsg.pitch=msg->pitch;
    dronePoseMsg.roll=msg->roll;

    return;
}

void DroneMissionPlanner::droneYawRefCommandCallback(const droneMsgsROS::droneYawRefCommand::ConstPtr& msg)
{
    droneYawRefCommandMsg.header=msg->header;
    droneYawRefCommandMsg.yaw=msg->yaw;

    return;
}

void DroneMissionPlanner::droneHLCommandAckCallback(const droneMsgsROS::droneHLCommandAck::ConstPtr& msg)
{
    droneHLCommAckMsg.time=msg->time;
    droneHLCommAckMsg.ack=msg->ack;

    flagAckReceived=droneHLCommAckMsg.ack;

    //Trye to resend again
    if(!flagAckReceived)
        flagSendNewTask=true;

    return;
}

void DroneMissionPlanner::droneGoTaskCallback(const droneMsgsROS::droneGoTask::ConstPtr& msg)
{
    //read the msgs
    droneGoTaskMsg.time=msg->time;
    droneGoTaskMsg.submissionId=msg->submissionId;
    droneGoTaskMsg.taskId=msg->taskId;

    //do things
    resetValues();
    submissionCounter=droneGoTaskMsg.submissionId;
    taskCounter=droneGoTaskMsg.taskId;

    //end
    return;
}

int DroneMissionPlanner::publishHLCommand(droneMsgsROS::droneHLCommand droneHLCommMsgIn)
{
    if(droneModuleOpened==false)
        return 0;

    droneHLCommPub.publish(droneHLCommMsgIn);

    return 1;
}

int DroneMissionPlanner::publishPositionRefCommand(droneMsgsROS::dronePositionRefCommand dronePositionRefCommandIn)
{
    if(droneModuleOpened==false)
        return 0;

    dronePositionRefCommandPub.publish(dronePositionRefCommandIn);

    return 1;
}

int DroneMissionPlanner::publishYawToLook(droneMsgsROS::droneYawRefCommand droneYawToLookIn)
{
    if(droneModuleOpened==false)
        return 0;

    droneYawToLookPub.publish(droneYawToLookIn);

    return 1;
}

int DroneMissionPlanner::publishPointToLook(droneMsgsROS::dronePositionRefCommand dronePointToLookIn)
{
    if(droneModuleOpened==false)
        return 0;

    dronePointToLookPub.publish(dronePointToLookIn);

    return 1;
}

int DroneMissionPlanner::publishMissionInfo(droneMsgsROS::droneMissionInfo droneMissionInfoIn)
{
    if(droneModuleOpened==false)
        return 0;

    droneMissionInfoPub.publish(droneMissionInfoIn);

    return 1;
}

bool DroneMissionPlanner::suspendServCall(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response)
{
    if(flagModuleSuspended)
        return false;

    cout<<"Suspending!!"<<endl;

    flagModuleSuspended=true;

    suspendedInitTime=ros::Time::now();

    return true;
}

bool DroneMissionPlanner::resumeServCall(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response)
{
    if(!flagModuleSuspended)
        return false;

    cout<<"Resuming!!"<<endl;

    flagModuleSuspended=false;

    supendedTime+=ros::Time::now()-suspendedInitTime;

    return true;
}

bool DroneMissionPlanner::init()
{
    //counters
    submissionCounter=0;
    taskCounter=0;

    flagMissionEnded=false;
    flagTaskEnded=false;

    flagNewTask=true;
    flagSendNewTask=false;
    flagNewSubmission=true;
    flagUpdateSubmissionTime=true;

    flagAckReceived=false;

    flagTaskReady=false;
    flagTaskRunning=false;

    flagFinishSubmissionLoop=false;
    flagFinishTaskLoop=false;

    flagModuleSuspended=false;

    //end
    return true;
}

void DroneMissionPlanner::close()
{

    DroneModule::close();
	return;
}

bool DroneMissionPlanner::resetValues()
{
    //Init mission
    missionInitTime=ros::Time::now();
    submissionInitTime=ros::Time::now();
    taskInitTime==ros::Time::now();

    submissionCounter=MyMissionPlanner.submissionTree.at(0);
    taskCounter=MyMissionPlanner.taskTree.at(0).at(0);

    flagMissionEnded=false;
    flagTaskEnded=false;

    flagNewTask=true;
    flagSendNewTask=false;
    flagNewSubmission=true;
    flagUpdateSubmissionTime=true;

    flagAckReceived=false;

    flagTaskReady=false;
    flagTaskRunning=false;

    flagFinishSubmissionLoop=false;
    flagFinishTaskLoop=false;

    flagModuleSuspended=false;

    return true;

}

bool DroneMissionPlanner::startVal()
{
    //Reset time

    //timeflagModuleSuspended;
    missionInitTime=ros::Time::now();

    //Read task
    if(!MyMissionPlanner.readTask(submissionCounter,taskCounter))
    {
        cout<<" .Submission or task not found!"<<endl;
        return false;
    }
    submissionInitTime=ros::Time::now();
    taskInitTime==ros::Time::now();

    //End
    return DroneModule::startVal();
}

bool DroneMissionPlanner::stopVal()
{
    return DroneModule::stopVal();
}

bool DroneMissionPlanner::run()
{
    if(!DroneModule::run())
        return false;

    if(droneModuleOpened==false)
        return false;

    if(flagModuleSuspended)
        return false;

    cout<<"New loop"<<endl;

    //Analize ack
    if(flagAckReceived)
    {
        cout<<"-Ack received!"<<endl;
        //Bajar bandera
        flagAckReceived=false;

        //Check actual task
        if(MyMissionPlanner.TheTask.type==missionPlanner::takeOff || MyMissionPlanner.TheTask.type==missionPlanner::land)
        {
            cout<<"  .task unable to be monitored"<<endl;
            flagTaskEnded=true;
        }
        else
        {
            cout<<"  .task to be monitored"<<endl;
            flagTaskReady=true;
        }

    }

    //check if task ended
    if(flagTaskEnded)
    {
        cout<<"-TaskEnded"<<endl;

        //bajamos bandera
        flagTaskEnded=false;

        //Check if the task is periodic
        if(MyMissionPlanner.TheTask.loop==true && !flagFinishTaskLoop)
        {
            //reset some parameters
            // TODO JL
            //taskInitTime=ros::Time::now();

            flagNewTask=true;
        }
        else
        {
            //bajamos flag si procede
            if(flagFinishTaskLoop)
                flagFinishTaskLoop=false;

            //search
            unsigned int iSubm;
            for(iSubm=0;iSubm<MyMissionPlanner.submissionTree.size();iSubm++)
            {
                if(MyMissionPlanner.submissionTree.at(iSubm)==submissionCounter)
                    break;
            }
            //cout<<"iSubm="<<iSubm<<endl;
            unsigned int iTask;
            for(iTask=0;iTask<MyMissionPlanner.taskTree.at(iSubm).size();iTask++)
            {
                if(MyMissionPlanner.taskTree.at(iSubm).at(iTask)==taskCounter)
                    break;
            }
            //cout<<"iTask="<<iTask<<endl;
            //read new task
            //cout<<"MyMissionPlanner.taskTree.at(iSubm).size()="<<MyMissionPlanner.taskTree.at(iSubm).size()<<endl;
            if(iTask<MyMissionPlanner.taskTree.at(iSubm).size()-1)
            {
                //There are more tasks in the submission
                //cout<<"There are more tasks in the submission"<<endl;
                taskCounter=MyMissionPlanner.taskTree.at(iSubm).at(iTask+1);

                //taskInitTime=ros::Time::now();

                flagNewTask=true;
                //cout<<"taskCounter="<<taskCounter<<endl;
            }
            else
            {
                //Check if the submission is periodic
                if(MyMissionPlanner.TheSubmission.loop && !flagFinishSubmissionLoop)
                {
                    //reset some parameters
                    //submissionInitTime=ros::Time::now();

                    taskCounter=MyMissionPlanner.taskTree.at(iSubm).at(0);

                    //taskInitTime=ros::Time::now();
                    flagNewSubmission=true;
                    flagUpdateSubmissionTime=false;
                    flagNewTask=true;
                }
                else
                {
                    //bajamos flag si procede
                    if(flagFinishSubmissionLoop)
                    {
                        cout<<"  .!!!Finish Submission Loop!!!!"<<endl;
                        flagFinishSubmissionLoop=false;
                    }

                    //New submission
                    if(iSubm<MyMissionPlanner.submissionTree.size()-1)
                    {
                        //cout<<"  .New submission"<<endl;
                        submissionCounter=MyMissionPlanner.submissionTree.at(iSubm+1);
                        //cout<<"submissionCounter="<<submissionCounter<<endl;
                        taskCounter=MyMissionPlanner.taskTree.at(iSubm+1).at(0);
                        //cout<<"taskCounter="<<taskCounter<<endl;

                        //submissionInitTime=ros::Time::now();
                        //taskInitTime=ros::Time::now();

                        flagNewTask=true;
                        flagNewSubmission=true;
                        flagUpdateSubmissionTime=true;
                    }
                    else
                    {
                        //we finished the mission
                        flagMissionEnded=true;
                    }
                }
            }
        }

    }

    //Check if mission ended
    if(flagMissionEnded)
    {
        cout<<"-Mission ended!"<<endl;
        return false;
    }

    //New task. communicate to the brain!
    if(flagNewTask)
    {
        //bajar bandera
        flagNewTask=false;

        cout<<"-!New task!. submission="<<submissionCounter<<"; task="<<taskCounter<<endl;

        //command task!
        if(!MyMissionPlanner.readTask(submissionCounter,taskCounter))
        {
            cout<<"  .Submission or task not found!"<<endl;
            return false;
        }

        flagSendNewTask=true;
    }

    if(flagSendNewTask)
    {
        //bajamos badera
        flagSendNewTask=false;

        cout<<"-send new task!!"<<endl;

        //send
        droneHLCommMsg.time=ros::Time::now();

        if(MyMissionPlanner.TheTask.type==missionPlanner::taskTypes::takeOff)
        {
            droneHLCommMsg.hlCommand=droneMsgsROS::droneHLCommand::TAKE_OFF;
        }
        else if(MyMissionPlanner.TheTask.type==missionPlanner::taskTypes::hover)
        {
            droneHLCommMsg.hlCommand=droneMsgsROS::droneHLCommand::HOVER;
        }
        else if(MyMissionPlanner.TheTask.type==missionPlanner::taskTypes::land)
        {
            droneHLCommMsg.hlCommand=droneMsgsROS::droneHLCommand::LAND;
        }
        else if(MyMissionPlanner.TheTask.type==missionPlanner::taskTypes::trajectoryMovement)
        {
            droneHLCommMsg.hlCommand=droneMsgsROS::droneHLCommand::MOVE_TRAJECTORY;
        }
        else if(MyMissionPlanner.TheTask.type==missionPlanner::taskTypes::sleep)
        {
            droneHLCommMsg.hlCommand=droneMsgsROS::droneHLCommand::SLEEP;
        }
        else
        {
            droneHLCommMsg.hlCommand=droneMsgsROS::droneHLCommand::UNKNOWN;
        }

        //publicamos
        publishHLCommand(droneHLCommMsg);

    }

    //launch task, because it is ready (the brain says ok)
    bool flagMonitorMissionNow=true;
    if(flagTaskReady)
    {

        cout<<"-The task is ready!"<<endl;

        //bajamos bandera
        flagTaskReady=false;

        //subimos la otra
        flagTaskRunning=true;

        //Init task
        taskInitTime=ros::Time::now();
        //cout<<"    setting task time to "<<taskInitTime<<endl;

        if(flagNewSubmission)
        {
            cout<<"  .!!New submission!!"<<endl;

            //bajamos bandera
            flagNewSubmission=false;

            if(flagUpdateSubmissionTime)
            {
                flagUpdateSubmissionTime=false;

                cout<<"  .!!updating time!"<<endl;
                submissionInitTime=ros::Time::now();
            }
        }

        //launch task!
        if(MyMissionPlanner.TheTask.type==missionPlanner::taskTypes::trajectoryMovement)
        {
            //Point!!!
            bool pointLoaded=false;
            //x
            if(MyMissionPlanner.TheTask.pointLoaded.at(0))
            {
                pointLoaded=true;
                dronePositionRefCommandMsg.x=MyMissionPlanner.TheTask.point.at(0);
            }
            else
            {
                dronePositionRefCommandMsg.x=dronePoseMsg.x;
                MyMissionPlanner.TheTask.point.at(0)=dronePoseMsg.x;
            }

            //y
            if(MyMissionPlanner.TheTask.pointLoaded.at(1))
            {
                pointLoaded=true;
                dronePositionRefCommandMsg.y=MyMissionPlanner.TheTask.point.at(1);
            }
            else
            {
                dronePositionRefCommandMsg.y=dronePoseMsg.y;
                MyMissionPlanner.TheTask.point.at(1)=dronePoseMsg.y;
            }

            //z
            if(MyMissionPlanner.TheTask.pointLoaded.at(2))
            {
                pointLoaded=true;
                dronePositionRefCommandMsg.z=MyMissionPlanner.TheTask.point.at(2);
            }
            else
            {
                dronePositionRefCommandMsg.z=dronePoseMsg.z;
                MyMissionPlanner.TheTask.point.at(2)=dronePoseMsg.z;
            }

            //enviamos el punto
            if(pointLoaded)
                publishPositionRefCommand(dronePositionRefCommandMsg);

            /////Yaw. Always send a command
            //Yaw
            if(MyMissionPlanner.TheTask.yawLoaded)
            {
                //command from xml
                droneYawToLookMsg.yaw=MyMissionPlanner.TheTask.yaw;
                publishYawToLook(droneYawToLookMsg);
            }
            /*
            else
            {
                //same yaw than before
                droneYawToLookMsg.yaw=dronePoseMsg.yaw;
                publishYawToLook(droneYawToLookMsg);
            }
            */

            //Point to look
            if(MyMissionPlanner.TheTask.pointToLookLoaded.at(0) && MyMissionPlanner.TheTask.pointToLookLoaded.at(1))
            {
                //comand from xml
                dronePointToLookMsg.x=MyMissionPlanner.TheTask.pointToLook.at(0);
                dronePointToLookMsg.y=MyMissionPlanner.TheTask.pointToLook.at(1);
                publishPointToLook(dronePointToLookMsg);
            }
            /*
            else
            {
                //same yaw than before
                droneYawToLookMsg.yaw=dronePoseMsg.yaw;
                publishYawToLook(droneYawToLookMsg);
            }
            */

        }

        flagMonitorMissionNow=false;

    }

    //////Monitor mission!!
    if(flagTaskRunning && flagMonitorMissionNow)
    {
        //Monitor the submission
        cout<<"-Monitoring mission"<<endl;

        //Time
        if(MyMissionPlanner.TheSubmission.duration!=-1)
        {
            cout<<"  .periodic submision"<<endl;

            //There is a limit in time
            ros::Duration submissionDuration;
            submissionDuration=ros::Time::now()-submissionInitTime-supendedTime;

            cout<<"    ->time="<<submissionDuration.toSec()<<" of "<<MyMissionPlanner.TheSubmission.duration<<endl;

            if(submissionDuration.toSec()>=MyMissionPlanner.TheSubmission.duration)
            {
                if(MyMissionPlanner.TheSubmission.loop)
                    flagFinishSubmissionLoop=true;
            }
        }

        //battery
        /*
        if(MyMissionPlanner.TheSubmission.battery!=-1)
        {
            //There is a limit in battery

        }
        */

        //monitor de task
        cout<<"  .Monitoring the task"<<endl;

        //move
        if(MyMissionPlanner.TheTask.type==missionPlanner::taskTypes::trajectoryMovement)
        {
            cout<<"  .Moving!"<<endl;

            //time. No sense
            /*
            if(MyMissionPlanner.TheTask.duration!=-1)
            {
                //There is a limit in time
                ros::Duration taskDuration;
                taskDuration=taskInitTime-ros::Time::now();

                if(taskDuration.toSec()>=MyMissionPlanner.TheTask.duration)
                {
                    if(MyMissionPlanner.TheTask.loop)
                        flagFinishTaskLoop=true;
                }
            }
            */

            //battery. No sense

            //mission achieved
            /*
            double distanceToMissionPoint=0.0;
            distanceToMissionPoint+=pow(dronePoseMsg.x-MyMissionPlanner.TheTask.point.at(0),2);
            distanceToMissionPoint+=pow(dronePoseMsg.y-MyMissionPlanner.TheTask.point.at(1),2);
            distanceToMissionPoint+=pow(dronePoseMsg.z-MyMissionPlanner.TheTask.point.at(2),2);
            distanceToMissionPoint=sqrt(distanceToMissionPoint);
            cout<<"  ->distances="<<distanceToMissionPoint<<endl;
            */

            //cout<<"pose=["<<dronePoseMsg.x<<"; "<<dronePoseMsg.y<<"; "<<dronePoseMsg.z<<"]"<<endl;
            //cout<<"mission point=["<<MyMissionPlanner.TheTask.point.at(0)<<"; "<<MyMissionPlanner.TheTask.point.at(1)<<"; "<<MyMissionPlanner.TheTask.point.at(2)<<"]"<<endl;

            //Position distances!!! Always important!!
            //TODO_JL fix this!! now is a square in x-y. it should be a circle!!
            std::vector<double> distanceToMissionPoint;
            //x
            distanceToMissionPoint.push_back(fabs(dronePoseMsg.x-MyMissionPlanner.TheTask.point.at(0)));
            //y
            distanceToMissionPoint.push_back(fabs(dronePoseMsg.y-MyMissionPlanner.TheTask.point.at(1)));
            //z
            distanceToMissionPoint.push_back(fabs(dronePoseMsg.z-MyMissionPlanner.TheTask.point.at(2)));

            cout<<"  ->distances="<<distanceToMissionPoint.at(0)<<"; "<<distanceToMissionPoint.at(1)<<"; "<<distanceToMissionPoint.at(2)<<endl;

            ///Yaw!!
            //yaw distance
            double distanceToYaw=0.0;

            distanceToYaw=fabs(dronePoseMsg.yaw-droneYawRefCommandMsg.yaw);

            cout<<"  ->distance yaw="<<distanceToYaw*180.0/M_PI<<endl;

            /*
            if(MyMissionPlanner.TheTask.pointToLookLoaded.at(0) && MyMissionPlanner.TheTask.pointToLookLoaded.at(1))
            {
                //Point to look distance
                //TODO_JL
            }
            else
            {
                //A command is always sent
                //Yaw command
                //if(MyMissionPlanner.TheTask.yawLoaded)
                    distanceToYaw=fabs(dronePoseMsg.yaw-MyMissionPlanner.TheTask.yaw);
            }
            */

            //Check distances
            bool flagPositionAchieved=false;
            if(distanceToMissionPoint.at(0)<=MyMissionPlanner.defaultPrecission.at(0) && distanceToMissionPoint.at(1)<=MyMissionPlanner.defaultPrecission.at(1) && distanceToMissionPoint.at(2)<=MyMissionPlanner.defaultPrecission.at(2))
            {
                flagPositionAchieved=true;
            }

            //Check yaw distances
            bool flagYawAchieved=false;
            if(distanceToYaw<=MyMissionPlanner.yawPrecission)
            {
                flagYawAchieved=true;
            }

            //Finish mission
            if(flagPositionAchieved && flagYawAchieved)
            {
                flagTaskEnded=true;
                flagTaskRunning=false;
            }

        }

        //hover
        if(MyMissionPlanner.TheTask.type==missionPlanner::hover)
        {
            cout<<"  .Hovering!"<<endl;

            //time
            if(MyMissionPlanner.TheTask.duration!=-1)
            {
                //There is a limit in time
                ros::Duration taskDuration;
                taskDuration=ros::Time::now()-taskInitTime-supendedTime;

                //cout<<"     -init time task="<<taskInitTime<<endl;
                //cout<<"     -ros now="<<ros::Time::now()<<endl;

                cout<<"   ->time="<<taskDuration.toSec()<<endl;

                if(taskDuration.toSec()>=MyMissionPlanner.TheTask.duration)
                {
                    flagTaskEnded=true;
                    flagTaskRunning=false;
                }
            }

            //battery. No sense

        }

        //sleep
        if(MyMissionPlanner.TheTask.type==missionPlanner::sleep)
        {
            cout<<"  .Sleeping!"<<endl;

            //time
            if(MyMissionPlanner.TheTask.duration!=-1)
            {
                //There is a limit in time
                ros::Duration taskDuration;
                taskDuration=ros::Time::now()-taskInitTime-supendedTime;

                cout<<"   ->time="<<taskDuration.toSec()<<endl;

                if(taskDuration.toSec()>=MyMissionPlanner.TheTask.duration)
                {
                    flagTaskEnded=true;
                    flagTaskRunning=false;
                }
            }

            //battery. No sense

        }
    }

    //Mission info

    ////set the variable
    droneMissionInfoMsg.timeMsgs=ros::Time::now();
    //missiom
    droneMissionInfoMsg.durationMission=ros::Time::now()-missionInitTime-supendedTime;
    //subtask
    droneMissionInfoMsg.durationSubmission=ros::Time::now()-submissionInitTime-supendedTime;
    droneMissionInfoMsg.idSubmission=submissionCounter;
    droneMissionInfoMsg.loopSubmission=MyMissionPlanner.TheSubmission.loop;
    //task
    droneMissionInfoMsg.durationTask=ros::Time::now()-taskInitTime-supendedTime;
    droneMissionInfoMsg.idTask=taskCounter;
    if(MyMissionPlanner.TheTask.type==missionPlanner::hover)
        droneMissionInfoMsg.taskType=droneMsgsROS::droneHLCommand::HOVER;
    else if(MyMissionPlanner.TheTask.type==missionPlanner::land)
        droneMissionInfoMsg.taskType=droneMsgsROS::droneHLCommand::LAND;
    else if(MyMissionPlanner.TheTask.type==missionPlanner::takeOff)
        droneMissionInfoMsg.taskType=droneMsgsROS::droneHLCommand::TAKE_OFF;
    else if(MyMissionPlanner.TheTask.type==missionPlanner::sleep)
        droneMissionInfoMsg.taskType=droneMsgsROS::droneHLCommand::SLEEP;
    else if(MyMissionPlanner.TheTask.type==missionPlanner::trajectoryMovement)
        droneMissionInfoMsg.taskType=droneMsgsROS::droneHLCommand::MOVE_TRAJECTORY;
    else
        droneMissionInfoMsg.taskType=droneMsgsROS::droneHLCommand::UNKNOWN;
    if(flagTaskRunning)
        droneMissionInfoMsg.taskState=droneMsgsROS::droneMissionInfo::TASK_RUNNING;
    else
        droneMissionInfoMsg.taskState=droneMsgsROS::droneMissionInfo::WAITING_BRAIN;

    ////publish
    publishMissionInfo(droneMissionInfoMsg);

    return false;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>The fuegocore.message.tests package</title>
  </head>

  <body>
    <p>
      Unit tests for the messaging system.  The classes in this
      package are JUnit unit tests designed to test various parts of
      the messaging system's functionality in isolation.
    </p>

  </body>
</html>

redpajama_set_name: RedPajamaGithub


text:
/*
    Document   : default
    Created on : 1 Jan, 2014, 4:50:01 PM
    Author     : admin
    Description:
        Purpose of the stylesheet follows.
*/

root {
    display: block;
}

#menu-wrapper {
/*    overflow: hidden;
    height: 56px;*/
    background: #1692CC; /* for non-css3 browsers */
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#f5f5f5', endColorstr='#1692CC'); /* for IE */
    background: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#1692CC)); /* for webkit browsers */
    background: -moz-linear-gradient(top,  #f5f5f5,  #1692CC); /* for firefox 3.6+ */
/*    width: 98%;
    margin:0 auto;*/
}
#bottom_menu_bar {
/*    width:  98%;
    margin: 0 auto;*/
     /*border-radius: 8px;*/
     height: 23px;
     /*background-color: rgb(226, 225, 225);*/
     background-color: #ffffff;
 }
 .breadcrumb_left-small {
    margin: 0px; padding: 0px; line-height:0px !important; padding-left: 4px;
}
#table_bottom_bg { background-color: #6BA9C7;}
/*    tabs style start       */
.ui-tabs .ui-tabs-nav li.ui-tabs-active a { background-color:#3FA5D4 !important}
.ui-tabs .ui-tabs-nav li.ui-tabs-active :after {
     content: '' !important;
    display: block !important;
    position: absolute !important;
    top: 0px !important;
    left: 100% !important;
    width: 0 !important;
    height: 0 !important;
    border-color: transparent transparent transparent #3FA5D4 !important;
    border-style: solid !important;
    z-index: 100 !important;
    border-width: 17px !important;
}
.ui-tabs .ui-tabs-nav li { padding: 0px !important}
.ui-tabs .ui-tabs-nav li:hover {border: none !important}
.ui-tabs .ui-tabs-nav li a:hover {border: none !important}
.ui-tabs .ui-tabs-nav li a { color: white !important; background-color:#A2D0E6 !important; border: none !important;}
.ui-tabs-nav li :after {
                content: '' !important;
                display: block !important;
                position: absolute !important;
                top: 0px !important;
                left: 100% !important;
                width: 0 !important;
                height: 0 !important;
                border-color: transparent transparent transparent #A2D0E6 !important;
                border-style: solid !important;
                z-index: 100 !important;
                border-width: 17px !important;
                border-left: 1px solid rgb(55, 128, 156) !important;
}

.ui-tabs-nav  .last_li :after {
    border-width: 0px !important;
}
.ui-tabs .ui-tabs-nav  .ui-state-default { border-radius:none !important; background-color:#A2D0E6 !important;}
.ui-tabs-active a {background-color:#A2D0E6 !important; border-radius:none !important}
.ui-tabs .ui-tabs-nav .ui-state-active {
    background-color:#3FA5D4 !important;
    border:none!important;
}
.ui-tabs .tabsbox .ui-tabs-nav li.ui-tabs-active :after {
        left: -32% !important;
        border-color: transparent #3FA5D4 transparent transparent !important;
    }
/*    tabs style end       */

thead th {
    background: -moz-linear-gradient(#E0E0E0, #B4B6B8) !important;
    background: -webkit-gradient(linear, left top, left bottom, from(#E0E0E0), to(#B4B6B8)) !important;
    background: -webkit-linear-gradient(#E0E0E0, #B4B6B8) !important;
    background: -o-linear-gradient(#E0E0E0, #B4B6B8) !important;
    background: -ms-linear-gradient(#E0E0E0, #B4B6B8) !important;
    background: linear-gradient(#E0E0E0, #B4B6B8) !important;
    -webkit-box-shadow: 0 -1px 0 rgba(255,255,255,.8) inset;
    -moz-box-shadow: 0 -1px 0 rgba(255,255,255,.8) inset;
    color: #000000; font-weight: bold;
    height:27px;
    font-size: 13px;

}
div.Help_Box_Style1 {
position:absolute;
top:47px;
/*left:-10%;*/
width: 250px;
height: 450px;
/*padding: 10px 30px 0px 30px;*/
padding: 6px;
border: 1px solid rgba(0,0,0,.05);
box-shadow: 0px 0px 0px 10px rgba(180, 180, 180, 0.55);
background: #FFFFFF;
z-index: 10;
display: none;
z-index: 100000;
right: 275px;
}
div.Help_Box_Style2 {
position:absolute;
top:47px;
/*left:-10%;*/
width: 250px;
height: 450px;
/*padding: 10px 30px 0px 30px;*/
padding: 6px;
border: 1px solid rgba(0,0,0,.05);
box-shadow: 0px 0px 0px 10px rgba(180, 180, 180, 0.55);
background: #FFFFFF;
z-index: 10;
display: none;
z-index: 100000;
right: 0px;
}
body::-webkit-scrollbar {
    width: 10px !important;
}

body::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3) !important;
}

body::-webkit-scrollbar-thumb {
  background-color: #5BB0D8 !important;
  outline: 1px solid slategrey !important;
}
.step {
text-align: left;
background: -moz-linear-gradient(#E0E0E0, #B4B6B8) !important;
    background: -webkit-gradient(linear, left top, left bottom, from(#E0E0E0), to(#B4B6B8)) !important;
    background: -webkit-linear-gradient(#E0E0E0, #B4B6B8) !important;
    background: -o-linear-gradient(#E0E0E0, #B4B6B8) !important;
    background: -ms-linear-gradient(#E0E0E0, #B4B6B8) !important;
    background: linear-gradient(#E0E0E0, #B4B6B8) !important;
color: black;
font-size: 22px;
text-shadow: 1px 1px 1px #fff;
font-weight: bold;

width: auto;
padding: 5px 0px 5px 10px;
padding: 0px 0px 0px 17px;
margin: 0px 0px;
border-bottom: 1px solid #fff;
border-top: 1px solid #d9d9d9;
background: -webkit-gradient(linear, left top, left bottom, from(#D4F5E5), to(#27B46B));
background: -webkit-linear-gradient(#D4F5E5, #27B46B);
border-radius: 5px;
border-bottom-left-radius: 0px;
border-bottom-right-radius: 0px;

}


text:
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
/**
 * @internalapi
 * @module vanilla
 */
/** */
import { BaseLocationServices } from './baseLocationService';
/** A `LocationServices` that gets/sets the current location from an in-memory object */
var MemoryLocationService = /** @class */ (function (_super) {
    __extends(MemoryLocationService, _super);
    function MemoryLocationService(router) {
        return _super.call(this, router, true) || this;
    }
    MemoryLocationService.prototype._get = function () {
        return this._url;
    };
    MemoryLocationService.prototype._set = function (state, title, url, replace) {
        this._url = url;
    };
    return MemoryLocationService;
}(BaseLocationServices));
export { MemoryLocationService };
//# sourceMappingURL=memoryLocationService.js.map


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef TIMEWORK_H
#define TIMEWORK_H

/* Includes ------------------------------------------------------------------*/
#include <stm32f10x.h>

/* Exported types ------------------------------------------------------------*/
typedef struct
{
	uint16_t year;
	uint8_t month;
	uint8_t date;

	uint8_t hour;
	uint8_t minute;
	uint8_t second;
}RTC_TimeDateTypeDef;

/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported define -----------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */
uint32_t RTC_TimeDateToCnt(RTC_TimeDateTypeDef*);
void RTC_CntToTimeDate(uint32_t, RTC_TimeDateTypeDef*);
void TimeToString(char[], RTC_TimeDateTypeDef*);
void DateToString(char[], RTC_TimeDateTypeDef*);

#endif //TIMEWORK_H


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.PropertyEditors.ValueConverters;
using Umbraco.Core.Services;

namespace Umbraco.Web.PropertyEditors
{
    /// <summary>
    /// Represents a media picker property editor.
    /// </summary>
    [DataEditor(
        Constants.PropertyEditors.Aliases.MediaPicker3,
        EditorType.PropertyValue,
        "Media Picker",
        "mediapicker3",
        ValueType = ValueTypes.Json,
        Group = Constants.PropertyEditors.Groups.Media,
        Icon = Constants.Icons.MediaImage)]
    public class MediaPicker3PropertyEditor : DataEditor
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MediaPicker3PropertyEditor" /> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        public MediaPicker3PropertyEditor(ILogger logger)
            : base(logger)
        { }

        /// <inheritdoc />
        protected override IConfigurationEditor CreateConfigurationEditor() => new MediaPicker3ConfigurationEditor();

        /// <inheritdoc />
        protected override IDataValueEditor CreateValueEditor() => new MediaPicker3PropertyValueEditor(Attribute);

        internal class MediaPicker3PropertyValueEditor : DataValueEditor, IDataValueReference
        {
            public MediaPicker3PropertyValueEditor(DataEditorAttribute attribute)
                : base(attribute)
            { }

            public override object ToEditor(Property property, IDataTypeService dataTypeService, string culture = null, string segment = null)
            {
                var value = property.GetValue(culture, segment);

                var dtos = Deserialize(value).ToList();

                var dataType = dataTypeService.GetDataType(property.PropertyType.DataTypeId);
                if (dataType?.Configuration != null)
                {
                    var configuration = dataType.ConfigurationAs<MediaPicker3Configuration>();

                    foreach (var dto in dtos)
                    {
                        dto.ApplyConfiguration(configuration);
                    }
                }

                return dtos;
            }

            public override object FromEditor(ContentPropertyData editorValue, object currentValue)
            {
                if (editorValue.Value is JArray dtos)
                {
                    // Clean up redundant/default data
                    foreach (var dto in dtos.Values<JObject>())
                    {
                        MediaWithCropsDto.Prune(dto);
                    }

                    return dtos.ToString(Formatting.None);
                }

                return base.FromEditor(editorValue, currentValue);
            }

            public IEnumerable<UmbracoEntityReference> GetReferences(object value)
            {
                foreach (var dto in Deserialize(value))
                {
                    yield return new UmbracoEntityReference(Udi.Create(Constants.UdiEntityType.Media, dto.MediaKey));
                }
            }

            internal static IEnumerable<MediaWithCropsDto> Deserialize(object value)
            {
                var rawJson = value is string str ? str : value?.ToString();
                if (string.IsNullOrWhiteSpace(rawJson))
                {
                    yield break;
                }

                if (!rawJson.DetectIsJson())
                {
                    // Old comma seperated UDI format
                    foreach (var udiStr in rawJson.Split(Constants.CharArrays.Comma))
                    {
                        if (GuidUdi.TryParse(udiStr, out var udi))
                        {
                            yield return new MediaWithCropsDto
                            {
                                Key = Guid.NewGuid(),
                                MediaKey = udi.Guid,
                                Crops = Enumerable.Empty<ImageCropperValue.ImageCropperCrop>(),
                                FocalPoint = new ImageCropperValue.ImageCropperFocalPoint
                                {
                                    Left = 0.5m,
                                    Top = 0.5m
                                }
                            };
                        }
                    }
                }
                else
                {
                    // New JSON format
                    foreach (var dto in JsonConvert.DeserializeObject<IEnumerable<MediaWithCropsDto>>(rawJson))
                    {
                        yield return dto;
                    }
                }
            }

            /// <summary>
            /// Model/DTO that represents the JSON that the MediaPicker3 stores.
            /// </summary>
            [DataContract]
            internal class MediaWithCropsDto
            {
                [DataMember(Name = "key")]
                public Guid Key { get; set; }

                [DataMember(Name = "mediaKey")]
                public Guid MediaKey { get; set; }

                [DataMember(Name = "crops")]
                public IEnumerable<ImageCropperValue.ImageCropperCrop> Crops { get; set; }

                [DataMember(Name = "focalPoint")]
                public ImageCropperValue.ImageCropperFocalPoint FocalPoint { get; set; }

                /// <summary>
                /// Applies the configuration to ensure only valid crops are kept and have the correct width/height.
                /// </summary>
                /// <param name="configuration">The configuration.</param>
                public void ApplyConfiguration(MediaPicker3Configuration configuration)
                {
                    var crops = new List<ImageCropperValue.ImageCropperCrop>();

                    var configuredCrops = configuration?.Crops;
                    if (configuredCrops != null)
                    {
                        foreach (var configuredCrop in configuredCrops)
                        {
                            var crop = Crops?.FirstOrDefault(x => x.Alias == configuredCrop.Alias);

                            crops.Add(new ImageCropperValue.ImageCropperCrop
                            {
                                Alias = configuredCrop.Alias,
                                Width = configuredCrop.Width,
                                Height = configuredCrop.Height,
                                Coordinates = crop?.Coordinates
                            });
                        }
                    }

                    Crops = crops;

                    if (configuration?.EnableLocalFocalPoint == false)
                    {
                        FocalPoint = null;
                    }
                }

                /// <summary>
                /// Removes redundant crop data/default focal point.
                /// </summary>
                /// <param name="value">The media with crops DTO.</param>
                /// <returns>
                /// The cleaned up value.
                /// </returns>
                /// <remarks>
                /// Because the DTO uses the same JSON keys as the image cropper value for crops and focal point, we can re-use the prune method.
                /// </remarks>
                public static void Prune(JObject value) => ImageCropperValue.Prune(value);
            }
        }
    }
}


text:
/*	$OpenBSD: eisa_machdep.h,v 1.3 1996/10/30 22:38:47 niklas Exp $	*/
/*	$NetBSD: eisa_machdep.h,v 1.1 1996/04/12 05:39:51 cgd Exp $	*/

/*
 * Copyright (c) 1996 Carnegie-Mellon University.
 * All rights reserved.
 *
 * Author: Chris G. Demetriou
 *
 * Permission to use, copy, modify and distribute this software and
 * its documentation is hereby granted, provided that both the copyright
 * notice and this permission notice appear in all copies of the
 * software, derivative works or modified versions, and any portions
 * thereof, and that both notices appear in supporting documentation.
 *
 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
 * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
 *
 * Carnegie Mellon requests users of this software to return to
 *
 *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
 *  School of Computer Science
 *  Carnegie Mellon University
 *  Pittsburgh PA 15213-3890
 *
 * any improvements or extensions that they make and grant Carnegie the
 * rights to redistribute these changes.
 */

/*
 * Types provided to machine-independent EISA code.
 */
typedef struct alpha_eisa_chipset *eisa_chipset_tag_t;
typedef int eisa_intr_handle_t;

struct alpha_eisa_chipset {
	void	*ec_v;

	void	(*ec_attach_hook) __P((struct device *, struct device *,
		    struct eisabus_attach_args *));
	int	(*ec_maxslots) __P((void *));
	int	(*ec_intr_map) __P((void *, u_int,
		    eisa_intr_handle_t *));
	const char *(*ec_intr_string) __P((void *, eisa_intr_handle_t));
	void	*(*ec_intr_establish) __P((void *, eisa_intr_handle_t,
		    int, int, int (*)(void *), void *, char *));
	void	(*ec_intr_disestablish) __P((void *, void *));
};

/*
 * Functions provided to machine-independent EISA code.
 */
#define	eisa_attach_hook(p, s, a)					\
    (*(a)->eba_ec->ec_attach_hook)((p), (s), (a))
#define	eisa_maxslots(c)						\
    (*(c)->ec_maxslots)((c)->ec_v)
#define	eisa_intr_map(c, i, hp)						\
    (*(c)->ec_intr_map)((c)->ec_v, (i), (hp))
#define	eisa_intr_string(c, h)						\
    (*(c)->ec_intr_string)((c)->ec_v, (h))
#define	eisa_intr_establish(c, h, t, l, f, a, nm)			\
    (*(c)->ec_intr_establish)((c)->ec_v, (h), (t), (l), (f), (a), (nm))
#define	eisa_intr_disestablish(c, h)					\
    (*(c)->ec_intr_disestablish)((c)->ec_v, (h))


text:
if test "$1" = "-xlen"
then
    XLEN="xlen"
else
    XLEN="len"
fi

TMP='tmp'
HASH=`../bin/tlsh_version | head -1 | cut -f1`
CHKSUM=`../bin/tlsh_version | tail -1 | cut -f1`

sh -cx "../bin/tlsh_unittest -r ../Testing/example_data > $TMP/example_data.out"
if test $XLEN = "xlen"
then
    sh -cx "../bin/tlsh_unittest -xlen -r ../Testing/example_data -c ../Testing/example_data/website_course_descriptors06-07.txt > $TMP/example_data.scores"
else
    sh -cx "../bin/tlsh_unittest -r ../Testing/example_data -c ../Testing/example_data/website_course_descriptors06-07.txt > $TMP/example_data.scores"
fi
if test $XLEN = "xlen"
then
    sh -cx "../bin/tlsh_unittest -xlen -l $TMP/example_data.out -c ../Testing/example_data/website_course_descriptors06-07.txt > $TMP/example_data.scores.2 2>&1"
else
    sh -cx "../bin/tlsh_unittest -l $TMP/example_data.out -c ../Testing/example_data/website_course_descriptors06-07.txt > $TMP/example_data.scores.2 2>&1"
fi
if test $XLEN = "xlen"
then
    sh -cx "../bin/tlsh_unittest -xref -xlen -r ../Testing/example_data > $TMP/example_data.xref.scores 2>&1"
else
    sh -cx "../bin/tlsh_unittest -xref -r ../Testing/example_data > $TMP/example_data.xref.scores 2>&1"
fi
if test $XLEN = "xlen"
then
    sh -cx "../bin/tlsh_unittest -T 201 -xlen -l $TMP/example_data.out -c ../Testing/example_data/website_course_descriptors06-07.txt > $TMP/example_data.scores.2.T-201 2>&1"
else
    sh -cx "../bin/tlsh_unittest -T 201 -l $TMP/example_data.out -c ../Testing/example_data/website_course_descriptors06-07.txt > $TMP/example_data.scores.2.T-201 2>&1"
fi

mv -v $TMP/example_data.out exp/example_data.$HASH.$CHKSUM.$XLEN.out_EXP
mv -v $TMP/example_data.scores exp/example_data.$HASH.$CHKSUM.$XLEN.scores_EXP
mv -v $TMP/example_data.scores.2 exp/example_data.$HASH.$CHKSUM.$XLEN.scores.2_EXP
mv -v $TMP/example_data.xref.scores exp/example_data.$HASH.$CHKSUM.$XLEN.xref.scores_EXP
mv -v $TMP/example_data.scores.2.T-201 exp/example_data.$HASH.$CHKSUM.$XLEN.scores.2.T-201_EXP


text:
package com.elusive_code.newsboy;

/**
 *
This interface represents event source, e.g. object that produces events to which others may subscribe

 *

 *     To receive events object must have public method with zero or one argument
 *     marked with {@link com.elusive_code.newsboy.Subscribe} annotation.

 *     This object should be passed to {@link com.elusive_code.newsboy.EventService#subscribe(Object)}.

 *

 *

 *
If event handling method has one argument,
 *     listener will be notified of the events that fit the type of that argument.

 *
If event handling method has no arguments,
 *     listener will notified of the events that fit {@link Subscribe#eventType()}

 *

 *
 * @see com.elusive_code.newsboy.Subscribe com.elusive_code.newsboy.EventService
 * @see AsyncEventService
 * @author Vladislav Dolgikh
 */
public interface EventSource {

    /**
     *
Subscribe for events from this EventService.

     *
     *
Subscriber should have method or methods marked with
     * {@link com.elusive_code.newsboy.Subscribe}
     * annotation.

     * If annotated method has no arguments, it still will be subscribed and notified
     * of the events of type specified in annotation parameter.
     *

     *
     * @param listener listener to receive events
     * @see com.elusive_code.newsboy.Subscribe
     */
    void subscribe(Object listener);

    /**
     *
Unsubscribe listener from events from this EventService

     * @param listener listener to
     */
    void unsubscribe(Object listener);
}


text:
'use strict';

var config = require('./config');
var API = require('../');
var muk = require('muk');
var urllib = require('urllib');
var expect = require('expect.js');

describe('api_custom_service', function () {
  var api = new API(config.appid, config.appsecret);

  describe('getRecords', function () {
    describe('getRecords mock', function () {
      before(function () {
        muk(urllib, 'request', function (url, args, callback) {
          var data = {'recordlist': []};
          var res =  {
            headers: {
              'content-type': 'application/json'
            }
          };
          process.nextTick(function () {
            callback(null, data, res);
          });
        });
      });

      after(function () {
        muk.restore();
      });

      it('getRecords should ok', function (done) {
        var condition = {
          'starttime' : 123456789,
          'endtime' : 987654321,
          'number' : 10000,
          'msgid'  : 1
        };

        api.getRecords(condition, function (err, data, res) {
          expect(err).not.to.be.ok();
          expect(data).to.have.property('recordlist');
          done();
        });
      });
    });
  });

  describe('getCustomServiceList', function () {
    it('should unauthorized', function (done) {
      api.getCustomServiceList(function (err, data, res) {
        expect(err).not.to.be.ok();
        expect(data).to.have.property('kf_list');
        done();
      });
    });
  });

  describe('getOnlineCustomServiceList', function () {
    it('should unauthorized', function (done) {
      api.getOnlineCustomServiceList(function (err, data, res) {
        expect(err).not.to.be.ok();
        expect(data).to.have.property('kf_online_list');
        done();
      });
    });
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
  <mime-type type="application/x-qtiplot-project">
    <sub-class-of type="text/plain"/>
    <comment>QtiPlot project file</comment>
    <glob pattern="*.qti" />
  </mime-type>
  <mime-type type="application/x-qtiplot-project-compressed">
    <comment>Compressed QtiPlot project file</comment>
    <glob pattern="*.qti.gz" />
  </mime-type>
  <mime-type type="application/x-qtiplot-project-backup">
    <sub-class-of type="text/plain"/>
    <comment>QtiPlot project file backup</comment>
    <glob pattern="*.qti~" />
  </mime-type>
</mime-info>


text:
class AddAddressIdToRecipients < ActiveRecord::Migration
  def change
    add_reference :recipients, :address, index: true, foreign_key: true
  end
end


text:
        Top padding

----

        Bottom padding

----


text:
package com.michaelflisar.storagemanager.interfaces;

/**
 * Created by flisar on 09.03.2016.
 */
public interface IFolderData
{
    boolean knowsCount();
    int getCount();
    IFile getMainFile();
}


text:
import {NgbConfig} from '../ngb-config';
import {NgbAccordionConfig} from './accordion-config';

describe('ngb-accordion-config', () => {
  it('should have sensible default values', () => {
    const config = new NgbAccordionConfig(new NgbConfig());

    expect(config.closeOthers).toBe(false);
    expect(config.type).toBeUndefined();
  });
});


text:
package monty;

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

import java.io.StringReader;
import java.util.Arrays;
import java.util.TreeSet;

import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonReader;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class ApplicationTests {

	@Autowired
	private TestRestTemplate restTemplate;

	private static final HttpHeaders ACCEPT_JSON = new HttpHeaders();
	static {
		ACCEPT_JSON.setContentType(MediaType.APPLICATION_JSON);
	}

	@Test
	public void basicTest() {
		String version = "UNSTABLE";

		JsonObject body = get("/");
		assertThat(parseJsonObject("{\"version\":\"" + version + "\",\"apis\":[\"/games\",\"/stats\"]}"))
				.isEqualTo(body);
	}

	@Test
	public void noSwitchTest() {
		// CREATE NEW GAME
		JsonObject body = post("/games", "{\"numberOfDoors\": 3}");
		// System.out.println(body);
		assertThat(body.keySet()).isEqualTo(new TreeSet<>(Arrays.asList(new String[] { "doors", "state", "id" })));
		assertThat("SELECT_A_DOOR").isEqualTo(body.getString("state"));
		assertThat(parseJsonArray(
				"[{\"number\":1,\"state\":\"UNSELECTED\"},{\"number\":2,\"state\":\"UNSELECTED\"},{\"number\":3,\"state\":\"UNSELECTED\"}]"))
						.isEqualTo(body.getJsonArray("doors"));
		assertThat(body.getString("id").matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"))
				.isEqualTo(true);

		// SELECT DOOR
		String id = body.getString("id");
		put("/games/" + id + "/doors/1", "{\"state\": \"SELECTED\"}");

		// GET GAME STATE (might be finished, might need to choose a door)
		JsonObject body2 = get("/games/" + id);
		// System.out.println(body2);
		assertThat(body.keySet()).isEqualTo(new TreeSet<>(Arrays.asList(new String[] { "doors", "state", "id" })));
		JsonArray option2a = parseJsonArray(
				"[{\"number\":1,\"state\":\"SELECTED\"},{\"number\":2,\"state\":\"UNSELECTED\"},{\"number\":3,\"state\":\"OPENED\",\"prize\":\"LOSE\"}]");
		JsonArray option2b = parseJsonArray(
				"[{\"number\":1,\"state\":\"SELECTED\"},{\"number\":2,\"state\":\"OPENED\",\"prize\":\"LOSE\"},{\"number\":3,\"state\":\"UNSELECTED\"}]");
		assertThat(Arrays.asList(new JsonArray[] { option2a, option2b })).contains(body2.getJsonArray("doors"));
		assertThat(id).isEqualTo(body2.getString("id"));
		String state2 = body2.getString("state");
		assertThat("SECOND_CHANCE").isEqualTo(state2);

		// OPEN DOOR
		put("/games/" + id + "/doors/1", "{\"state\": \"OPENED\"}");

		// GET GAME STATE (expect finished)
		JsonObject body3 = get("/games/" + id);
		// System.out.println(body3);
		assertThat(body3.keySet())
				.isEqualTo(new TreeSet<>(Arrays.asList(new String[] { "doors", "state", "id", "prize", "switched" })));
		JsonArray option3a = parseJsonArray(
				"[{\"number\":1,\"state\":\"OPENED\",\"prize\":\"LOSE\"},{\"number\":2,\"state\":\"UNSELECTED\"},{\"number\":3,\"state\":\"OPENED\",\"prize\":\"LOSE\"}]");
		JsonArray option3b = parseJsonArray(
				"[{\"number\":1,\"state\":\"OPENED\",\"prize\":\"WIN\"},{\"number\":2,\"state\":\"UNSELECTED\"},{\"number\":3,\"state\":\"OPENED\",\"prize\":\"LOSE\"}]");
		JsonArray option3c = parseJsonArray(
				"[{\"number\":1,\"state\":\"OPENED\",\"prize\":\"LOSE\"},{\"number\":2,\"state\":\"OPENED\",\"prize\":\"LOSE\"},{\"number\":3,\"state\":\"UNSELECTED\"}]");
		JsonArray option3d = parseJsonArray(
				"[{\"number\":1,\"state\":\"OPENED\",\"prize\":\"WIN\"},{\"number\":2,\"state\":\"OPENED\",\"prize\":\"LOSE\"},{\"number\":3,\"state\":\"UNSELECTED\"}]");
		assertThat(Arrays.asList(new JsonArray[] { option3a, option3b, option3c, option3d }))
				.contains(body3.getJsonArray("doors"));
		assertThat("FINISHED").isEqualTo(body3.getString("state"));
		assertThat(Arrays.asList(new String[] { "WIN", "LOSE" })).contains(body3.getString("prize"));
		assertThat(body3.getString("prize")).isEqualTo(body3.getJsonArray("doors").getJsonObject(0).getString("prize"));
		assertThat(false).isEqualTo(body3.getBoolean("switched"));
		assertThat(id).isEqualTo(body3.getString("id"));

		// DELETE GAME
		delete("/games/" + id);
	}

	@Test
	public void switchTest() {
		// CREATE NEW GAME
		JsonObject body = post("/games", "{\"numberOfDoors\": 3}");
		//System.out.println(body);
		assertThat(body.keySet()).isEqualTo(new TreeSet<>(Arrays.asList(new String[] { "doors", "state", "id" })));
		assertThat("SELECT_A_DOOR").isEqualTo(body.getString("state"));
		assertThat(parseJsonArray(
				"[{\"number\":1,\"state\":\"UNSELECTED\"},{\"number\":2,\"state\":\"UNSELECTED\"},{\"number\":3,\"state\":\"UNSELECTED\"}]"))
						.isEqualTo(body.getJsonArray("doors"));
		assertThat(body.getString("id").matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"))
				.isEqualTo(true);

		// SELECT DOOR
		String id = body.getString("id");
		put("/games/" + id + "/doors/1", "{\"state\": \"SELECTED\"}");

		// GET GAME STATE (might be finished, might need to choose a door)
		JsonObject body2 = get("/games/" + id);
		//System.out.println(body2);
		assertThat(body.keySet()).isEqualTo(new TreeSet<>(Arrays.asList(new String[] { "doors", "state", "id" })));
		JsonArray option2a = parseJsonArray(
				"[{\"number\":1,\"state\":\"SELECTED\"},{\"number\":2,\"state\":\"UNSELECTED\"},{\"number\":3,\"state\":\"OPENED\",\"prize\":\"LOSE\"}]");
		JsonArray option2b = parseJsonArray(
				"[{\"number\":1,\"state\":\"SELECTED\"},{\"number\":2,\"state\":\"OPENED\",\"prize\":\"LOSE\"},{\"number\":3,\"state\":\"UNSELECTED\"}]");
		assertThat(Arrays.asList(new JsonArray[] { option2a, option2b })).contains(body2.getJsonArray("doors"));
		assertThat(id).isEqualTo(body2.getString("id"));
		String state2 = body2.getString("state");
		assertThat("SECOND_CHANCE").isEqualTo(state2);

		// OPEN DOOR
		int door = body2.getJsonArray("doors").getJsonObject(1).getString("state").equals("UNSELECTED") ? 2 : 3;
		put("/games/" + id + "/doors/" + door, "{\"state\": \"OPENED\"}");

		// GET GAME STATE (expect finished)
		JsonObject body3 = get("/games/" + id);
		System.out.println(body3);
		assertThat(body3.keySet()).isEqualTo(new TreeSet<>(Arrays.asList(new String[] { "doors", "state", "id", "prize", "switched" })));
		JsonArray option3a = parseJsonArray(
				"[{\"number\":1,\"state\":\"SELECTED\"},{\"number\":2,\"state\":\"OPENED\",\"prize\":\"LOSE\"},{\"number\":3,\"state\":\"OPENED\",\"prize\":\"LOSE\"}]");
		JsonArray option3b = parseJsonArray(
				"[{\"number\":1,\"state\":\"SELECTED\"},{\"number\":2,\"state\":\"OPENED\",\"prize\":\"" + (door == 2 ? "WIN" : "LOSE") + "\"},{\"number\":3,\"state\":\"OPENED\",\"prize\":\"" + (door == 3 ? "WIN" : "LOSE") + "\"}]");
		assertThat(Arrays.asList(new JsonArray[] { option3a, option3b })).contains(body3.getJsonArray("doors"));
		assertThat("FINISHED").isEqualTo(body3.getString("state"));
		assertThat(Arrays.asList(new String[] {"WIN", "LOSE"})).contains(body3.getString("prize"));
		assertThat(body3.getString("prize")).isEqualTo(body3.getJsonArray("doors").getJsonObject(door - 1).getString("prize"));
		assertThat(true).isEqualTo(body3.getBoolean("switched"));
		assertThat(id).isEqualTo(body3.getString("id"));

		// DELETE GAME
		delete("/games/" + id);
	}

	private JsonObject get(String path) {
		return parseJsonObject(this.restTemplate.getForObject(path, String.class));
	}

	private JsonObject post(String path, String body) {
		HttpEntity<String> httpEntity = new HttpEntity<String>(body, ACCEPT_JSON);
		return parseJsonObject(this.restTemplate.postForObject(path, httpEntity, String.class));
	}

	private void put(String path, String body) {
		HttpEntity<String> httpEntity = new HttpEntity<String>(body, ACCEPT_JSON);
		this.restTemplate.put(path, httpEntity);
	}

	private void delete(String path) {
		this.restTemplate.delete(path);
	}

	private JsonObject parseJsonObject(String jsonString) {
		try (JsonReader jsonReader = Json.createReader(new StringReader(jsonString))) {
			return jsonReader.readObject();
		}
	}

	private JsonArray parseJsonArray(String jsonString) {
		try (JsonReader jsonReader = Json.createReader(new StringReader(jsonString))) {
			return jsonReader.readArray();
		}
	}
}


text:
'use strict';

const models = require('./index');

/**
 * Chaos Remove Replica Fault Scheduled event.
 *
 * @extends models['ReplicaEvent']
 */
class ChaosReplicaRemovalScheduledEvent extends models['ReplicaEvent'] {
  /**
   * Create a ChaosReplicaRemovalScheduledEvent.
   * @property {uuid} faultGroupId Id of fault group.
   * @property {uuid} faultId Id of fault.
   * @property {string} serviceUri Service name.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of ChaosReplicaRemovalScheduledEvent
   *
   * @returns {object} metadata of ChaosReplicaRemovalScheduledEvent
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ChaosReplicaRemovalScheduled',
      type: {
        name: 'Composite',
        polymorphicDiscriminator: {
          serializedName: 'Kind',
          clientName: 'kind'
        },
        uberParent: 'FabricEvent',
        className: 'ChaosReplicaRemovalScheduledEvent',
        modelProperties: {
          eventInstanceId: {
            required: true,
            serializedName: 'EventInstanceId',
            type: {
              name: 'String'
            }
          },
          category: {
            required: false,
            serializedName: 'Category',
            type: {
              name: 'String'
            }
          },
          timeStamp: {
            required: true,
            serializedName: 'TimeStamp',
            type: {
              name: 'DateTime'
            }
          },
          hasCorrelatedEvents: {
            required: false,
            serializedName: 'HasCorrelatedEvents',
            type: {
              name: 'Boolean'
            }
          },
          kind: {
            required: true,
            serializedName: 'Kind',
            isPolymorphicDiscriminator: true,
            type: {
              name: 'String'
            }
          },
          partitionId: {
            required: true,
            serializedName: 'PartitionId',
            type: {
              name: 'String'
            }
          },
          replicaId: {
            required: true,
            serializedName: 'ReplicaId',
            type: {
              name: 'Number'
            }
          },
          faultGroupId: {
            required: true,
            serializedName: 'FaultGroupId',
            type: {
              name: 'String'
            }
          },
          faultId: {
            required: true,
            serializedName: 'FaultId',
            type: {
              name: 'String'
            }
          },
          serviceUri: {
            required: true,
            serializedName: 'ServiceUri',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ChaosReplicaRemovalScheduledEvent;


text:
package com.github.blahord.integral.component.odf;

import com.github.blahord.bettercollections.util.Maps;
import com.github.blahord.integral.ComponentException;
import com.github.blahord.integral.data.DataRow;
import com.github.blahord.integral.schema.SchemaColumn;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Calendar;
import java.util.Date;

import static com.github.blahord.bettercollections.compatibility.MapWrappers.asJavaUtilMap;
import static com.github.blahord.bettercollections.util.Maps.entry;
import static com.github.blahord.integral.type.DefaultTypes.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class ReadODSTest {

    private ReadODS readODS;

    @BeforeEach
    public void setUp() throws Exception {
        readODS = new ReadODS(
            "read",
            new FileInputStream("src/test/resources/testData.ods"),
            asJavaUtilMap(Maps.<Integer, SchemaColumn>asMap(
                entry(0, new SchemaColumn("integer", SIMPLE_INTEGER_TYPE)),
                entry(1, new SchemaColumn("float", SIMPLE_FLOAT_TYPE)),
                entry(2, new SchemaColumn("string", SIMPLE_STRING_TYPE)),
                entry(3, new SchemaColumn("boolean", SIMPLE_BOOLEAN_TYPE)),
                entry(4, new SchemaColumn("time", SIMPLE_TIME_TYPE))
            )),
            "data"
        );
    }

    @Test
    public void run() {
        readODS.setTableIndex(1);
        readODS.setSkipRows(6);

        readODS.onJobStarted();

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        DataRow dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(1L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(1.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("aaa");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-01T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(2L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(2.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("bbb");
        assertThat(dataRow.getBooleanValue("boolean")).isFalse();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-02T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(3L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(3.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("ccc");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-03T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(4L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(4.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("ddd");
        assertThat(dataRow.getBooleanValue("boolean")).isFalse();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-04T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(5L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(5.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("eee");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-05T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(6L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(6.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("fff");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-06T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(7L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(7.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("ggg");
        assertThat(dataRow.getBooleanValue("boolean")).isFalse();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-07T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(8L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(8.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("hhh");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-08T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(9L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(9.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("iii");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-09T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(10L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(10.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("jjj");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-10T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(11L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(11.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("kkk");
        assertThat(dataRow.getBooleanValue("boolean")).isFalse();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-11T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(12L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(12.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("lll");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-12T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(13L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(13.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("mmm");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-13T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        dataRow = readODS.pollOutputData("data");
        assertThat(dataRow.getIntegerValue("integer")).isEqualTo(14L);
        assertThat(dataRow.getFloatValue("float")).isEqualTo(14.5);
        assertThat(dataRow.getStringValue("string")).isEqualTo("nnn");
        assertThat(dataRow.getBooleanValue("boolean")).isTrue();
        assertThat(dataRow.getTimeValue("time")).isEqualTo(toInstant("2000-01-14T12:12:12"));

        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        assertThat(readODS.pollOutputData("data")).isSameAs(DataRow.EOI);

        readODS.onJobFinished();
    }

    @Test
    public void run_emptyTable() {
        readODS.setSkipRows(1);

        readODS.onJobStarted();
        readODS.run();
        assertThat(readODS.hasOutputData("data")).isTrue();
        assertThat(readODS.pollOutputData("data")).isSameAs(DataRow.EOI);
        readODS.onJobFinished();
    }

    @Test
    public void onJobStarted_nullInputStream() {
        final ReadODS reader = new ReadODS(
            "readd",
            null,
            java.util.Collections.emptyMap(),
            "data"
        );

        assertThatThrownBy(reader::onJobStarted).isInstanceOf(ComponentException.class);
    }

    private static Instant toInstant(String dateString) {
        try {
            final Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateString);
            final Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            return calendar.toInstant();
        } catch (ParseException ignored) {
            return null;
        }
    }

}


text:
package opennlp.tools.doccat;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import opennlp.tools.formats.ResourceAsStreamFactory;
import opennlp.tools.util.InputStreamFactory;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.TrainingParameters;

/**
 * Tests for the {@link DoccatFactory} class.
 */
public class DoccatFactoryTest {

  private static ObjectStream<DocumentSample> createSampleStream()
      throws IOException {

    InputStreamFactory isf = new ResourceAsStreamFactory(
        DoccatFactoryTest.class, "/opennlp/tools/doccat/DoccatSample.txt");

    return new DocumentSampleStream(new PlainTextByLineStream(isf, StandardCharsets.UTF_8));
  }

  private static DoccatModel train() throws IOException {
    return DocumentCategorizerME.train("x-unspecified", createSampleStream(),
        TrainingParameters.defaultParams(), new DoccatFactory());
  }

  private static DoccatModel train(DoccatFactory factory) throws IOException {
    return DocumentCategorizerME.train("x-unspecified", createSampleStream(),
        TrainingParameters.defaultParams(), factory);
  }

  @Test
  void testDefault() throws IOException {
    DoccatModel model = train();

    Assertions.assertNotNull(model);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    model.serialize(out);
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

    DoccatModel fromSerialized = new DoccatModel(in);

    DoccatFactory factory = fromSerialized.getFactory();

    Assertions.assertNotNull(factory);

    Assertions.assertEquals(1, factory.getFeatureGenerators().length);
    Assertions.assertEquals(BagOfWordsFeatureGenerator.class,
        factory.getFeatureGenerators()[0].getClass());

  }

  @Test
  void testCustom() throws IOException {
    FeatureGenerator[] featureGenerators = {new BagOfWordsFeatureGenerator(),
        new NGramFeatureGenerator(), new NGramFeatureGenerator(2, 3)};

    DoccatFactory factory = new DoccatFactory(featureGenerators);

    DoccatModel model = train(factory);

    Assertions.assertNotNull(model);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    model.serialize(out);
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());

    DoccatModel fromSerialized = new DoccatModel(in);

    factory = fromSerialized.getFactory();

    Assertions.assertNotNull(factory);

    Assertions.assertEquals(3, factory.getFeatureGenerators().length);
    Assertions.assertEquals(BagOfWordsFeatureGenerator.class,
        factory.getFeatureGenerators()[0].getClass());
    Assertions.assertEquals(NGramFeatureGenerator.class,
        factory.getFeatureGenerators()[1].getClass());
    Assertions.assertEquals(NGramFeatureGenerator.class, factory.getFeatureGenerators()[2].getClass());
  }

}


text:
Ti.Geolocation.purpose = "Semantich Search would like to use your current location to find the repositories around you";
require("db").createTables();
require("db").deleteAllAnnotations();

$.searchWin.tab = $.searchTab;
$.docWin.tab = $.docTab;
$.dataWin.tab = $.dataTab;

Ti.API.info('yeahh');

if (OS_ANDROID) {
	$.index.addEventListener('open', function(e) {
		var activity = $.index.activity;

		if (activity.actionBar) {
			activity.actionBar.title = "Semantic Search";
		}

	});

	$.docTab.addEventListener('focus', addMapMenu);
	$.dataTab.addEventListener('focus', addMapMenu);
	//$.searchTab.addEventListener('focus', removeMapMenu);

	/*function annotationsReady(e) {
		if (e.source.itemId == 0) {
			if (Alloy.Globals.documentsAnnotationsLoaded) {
				addMapMenu(e);
			}
		} else {
			if (Alloy.Globals.dataAnnotationsLoaded) {
				addMapMenu(e);
			}
		}
	}

	Ti.App.addEventListener("showMapMenu", function(tab) {
		//$.docTab.fireEvent('focus')
	});*/

	function addMapMenu(e) {
		var menuItemTitle = "List";
		if($.index.activeTab == $.docTab){
			if($.docWin.mapShown){
				menuItemTitle = "List";
			}else{
				menuItemTitle = "Map";
			};
		}else{
			if($.dataWin.mapShown){
				menuItemTitle = "List";
			}else{
				menuItemTitle = "Map";
			};
		};

		Ti.API.info("sto creando un bel menu");
		var activity = $.index.activity;
		activity.onCreateOptionsMenu = function(e) {
			var menuInfo = e.menu.add({
				title : "Info & Credits",
				showAsAction : Ti.Android.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW,
				itemId : 2
				//icon : "KS_nav_ui.png"
			});
			/*var menuSettings = e.menu.add({
				title : "Settings",
				showAsAction : Ti.Android.SHOW_AS_ACTION_NEVER,
				itemId : 3
				//icon : "KS_nav_ui.png"
			});*/
			menuInfo.addEventListener("click", showInfoWindow);
			//menuSettings.addEventListener("click", showSettingsWindow);

			var menuItem = e.menu.add({
				title : menuItemTitle,
				showAsAction : Ti.Android.SHOW_AS_ACTION_ALWAYS,
				itemId : ($.index.activeTab == $.docTab) ? 0 : 1
				//icon : "KS_nav_ui.png"
			});
			var indexSwitch; // Per passare da mappa a lista
			menuItem.addEventListener("click", function(e) {
				//alert(e.source.itemId);
				if(menuItem.title === "List"){
					menuItem.title = "Map";
					indexSwitch = 1;
				}else{
					menuItem.title = "List";
					indexSwitch = 0;
				};

				if (e.source.itemId == 0) {
					/*var mappaDoc = Alloy.createController("MapWindow", {
							title: "DR Map View",
							ann: $.docWin.annotations,
							index : 0
						}).getView();
					//addSpy("mappa", mappaDoc);
					mappaDoc.open();
					Ti.API.info("map should be open!");*/
					$.docWin.switchView({
						index : indexSwitch
					});
				} else {
					/*var mappaDoc = Alloy.createController("MapWindow", {
							title: "OADR Map View",
							ann: $.dataWin.annotations,
							index : 1
						}).getView();

					mappaDoc.open();*/
					//Ti.API.info("map should be open!");
					$.dataWin.switchView({
						index : indexSwitch
					});
				}
			});
		};

		activity.invalidateOptionsMenu();
	}

	function removeMapMenu() {
		var activity = $.index.activity;
		activity.invalidateOptionsMenu();
		activity.onCreateOptionsMenu = function(e) {
			var menuItem = e.menu.removeItem(0);

		};
	}

	//$.docTab.addEventListener('load', addMenu);
	//$.dataTab.addEventListener('load', addMenu);
	$.searchTab.addEventListener('focus', addMenu);

	function addMenu() {
		var activity = $.index.activity;
		activity.onCreateOptionsMenu = function(e) {
			//var menuItem = e.menu.removeItem(0);
			var menuInfo = e.menu.add({
				title : "Info & Credits",
				showAsAction : Ti.Android.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW ,
				itemId : 2
				//icon : "KS_nav_ui.png"
			});
			/*var menuSettings = e.menu.add({
				title : "Settings",
				showAsAction : Ti.Android.SHOW_AS_ACTION_NEVER,
				itemId : 3
				//icon : "KS_nav_ui.png"
			});*/
			menuInfo.addEventListener("click", showInfoWindow);
			//menuSettings.addEventListener("click", showSettingsWindow);
		};

		activity.invalidateOptionsMenu();
	}

	/*Ti.App.addEventListener('app:foo', function(data) {
		var name = data.name;
		Ti.API.info("***********YEEEEEESSSSSSSS: " + name);
		addMapMenu("");
	});*/
}

$.index.open();

function showSettingsWindow(e){
	var settingsWindow = Alloy.createController("SettingsWindow").getView();
	settingsWindow.open();
}

function showInfoWindow(e){
	var infoWindow = Alloy.createController("InfoWindow", {
		url: "/html/info.html"
	}).getView();
	infoWindow.open();
}

if(OS_ANDROID){
	var closeAppAlert = Ti.UI.createAlertDialog({
		title : "Semantic Search",
		message : "Do you want to quit\nSemantic Search?",
		buttonNames : ["YES", "NO"],
		cancel: 1
	});
	closeAppAlert.addEventListener("click", function(e){
		if(e.index === 0){
			$.index.close();
			Ti.API.info("CLOSE APP");
			if($.index.getActivity()){
				var activity = $.index.getActivity();
				activity.finish();
			};
		};
		$.index.animate({
			backgroundColor : "#fff",
			duration : 250
		});
	});

	function androidBack(){
		$.index.animate({
			backgroundColor : "#ccc",
			duration : 250
		});
		closeAppAlert.show();
	};
};

// CHECK CONNECTION
var winNoConnection = Ti.UI.createWindow({
	backgroundColor : "#fff"
});
var noConnectionLbl = Ti.UI.createLabel({
	text : "Semantic Search requires an internet connection.\nPlease check your connection.",
	font : {
		fontSize : "18sp",
		fontWeight : 'bold'
	},
	color : Alloy.Globals.css.tintColor,
	height : Ti.UI.SIZE,
	width : Ti.UI.SIZE	,
	textAlign : "center"
});
winNoConnection.add(noConnectionLbl);
var alertDialog = 	Ti.UI.createAlertDialog({
	title : "Semantic Search",
	message : "Semantic Search requires an internet connection.\nPlease check your connection."
});

if(!Titanium.Network.getOnline()){
	alertDialog.show();
	winNoConnection.open();
};
Titanium.Network.addEventListener("change", function(e){
	Ti.API.info("Connection change. Is online? ----> " + e.online);
	if(e.online){
		winNoConnection.close();
	}else{
		alertDialog.show();
		winNoConnection.open();
	};
});


text:
<?php
$context = Timber::get_context();

$post = new TimberPost();

$context['post'] = $post;

Timber::render(array('page-' . $post->post_name . '.twig', 'page.twig'), $context);


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayoutMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#FFFFFF">
    <HorizontalScrollView
        android:id="@+id/ScrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <Button
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/buttonStartLatencyTest"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/buttonTest_enabled"
                android:drawableLeft="@drawable/ic_play_arrow"
                android:drawableStart="@drawable/ic_play_arrow"
                style="@style/TextAppearance.AppCompat.Button"
                android:onClick="onButtonLatencyTest"/>

            <Button
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/buttonStartBufferTest"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/buttonBufferTest"
                android:drawableLeft="@drawable/ic_play_arrow"
                android:drawableStart="@drawable/ic_play_arrow"
                style="@style/TextAppearance.AppCompat.Button"
                android:onClick="onButtonBufferTest"/>

        </LinearLayout>
    </HorizontalScrollView>

    <Button
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/buttonCalibrateSoundLevel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/buttonCalibrateSoundLevel"
        android:drawableLeft="@drawable/ic_play_arrow"
        android:drawableStart="@drawable/ic_play_arrow"
        style="@style/TextAppearance.AppCompat.Button"
        android:onClick="onButtonCalibrateSoundLevel" />

    <TextView
        android:id="@+id/textInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:text="@string/labelInfo"/>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Current Level"
            android:id="@+id/textViewCurrentLevel"/>

        <SeekBar
            android:id="@+id/BarMasterLevel"
            android:indeterminate="false"
            android:max="100"
            android:progress="0"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            style="?android:attr/progressBarStyleHorizontal" />
    </LinearLayout>

    <HorizontalScrollView
        android:id="@+id/glitchReportPanel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible">
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <Button
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    android:id="@+id/buttonRecorderBufferPeriod"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:drawableLeft="@drawable/ic_assessment"
                    style="@style/TextAppearance.AppCompat.Button"
                    android:text="@string/buttonRecorderBufferPeriod"
                    android:onClick="onButtonRecorderBufferPeriod"/>

                <Button
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    android:id="@+id/buttonPlayerBufferPeriod"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:drawableLeft="@drawable/ic_assessment"
                    style="@style/TextAppearance.AppCompat.Button"
                    android:text="@string/buttonPlayerBufferPeriod"
                    android:onClick="onButtonPlayerBufferPeriod"/>
            </LinearLayout>
            <LinearLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <Button
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    android:id="@+id/buttonGlitches"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:drawableLeft="@drawable/ic_description"
                    style="@style/TextAppearance.AppCompat.Button"
                    android:text="@string/buttonGlitches"
                    android:onClick="onButtonGlitches"/>
                <Button
                    android:id="@+id/buttonHeatMap"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:drawableLeft="@drawable/ic_assessment"
                    style="@style/TextAppearance.AppCompat.Button"
                    android:text="@string/compareAll"
                    android:onClick="onButtonHeatMap"/>
            </LinearLayout>
        </LinearLayout>
    </HorizontalScrollView>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:text=""
            android:id="@+id/resultSummary"
            android:textStyle="bold"/>
    </LinearLayout>

    <LinearLayout
        android:layout_marginTop="0mm"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="center_horizontal"
        android:orientation="horizontal"
        android:layout_weight="1">

        <org.drrickorang.loopback.WavePlotView
            android:id="@+id/viewWavePlot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/zoomAndSaveControlPanel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:padding="10dp"
        android:visibility="invisible"
        android:orientation="horizontal">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true">

            <ImageButton
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/buttonZoomOutFull"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:paddingEnd="5dp"
                android:paddingRight="5dp"
                android:paddingLeft="5dp"
                android:text="@string/buttonZoomOutFull"
                android:src="@drawable/ic_zoom_out_full"
                android:background="@null"
                android:onClick="onButtonZoomOutFull"/>

            <ImageButton
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/buttonZoomOut"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:paddingEnd="5dp"
                android:paddingRight="5dp"
                android:paddingLeft="5dp"
                android:text="@string/buttonZoomOut"
                android:src="@drawable/ic_zoom_out"
                android:background="@null"
                android:onClick="onButtonZoomOut"/>

            <ImageButton
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/buttonZoomIn"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:paddingEnd="5dp"
                android:paddingRight="5dp"
                android:paddingLeft="5dp"
                android:text="@string/buttonZoomIn"
                android:src="@drawable/ic_zoom_in"
                android:background="@null"
                android:onClick="onButtonZoomIn"/>

        </LinearLayout>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true">

            <ImageButton
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/buttonReport"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:paddingEnd="5dp"
                android:paddingRight="5dp"
                android:paddingLeft="5dp"
                android:src="@drawable/ic_report"
                android:text="@string/buttonSave"
                android:background="@null"
                android:onClick="onButtonReport"/>

            <ImageButton
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/buttonSave"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:paddingEnd="5dp"
                android:paddingRight="5dp"
                android:paddingLeft="5dp"
                android:src="@drawable/ic_save"
                android:text="@string/buttonSave"
                android:background="@null"
                android:onClick="onButtonSave"/>

        </LinearLayout>

    </RelativeLayout>

</LinearLayout>


text:
package st.gravel.support.compiler;

import static org.junit.Assert.assertEquals;

import java.lang.reflect.InvocationTargetException;

import org.junit.Before;
import org.junit.Test;

import st.gravel.support.compiler.testtools.TestBootstrap;
import st.gravel.support.jvm.runtime.ImageBootstrapper;
import st.gravel.support.jvm.runtime.MethodTools;

public class TraitTest {
	@Before
	public void setUp() {
		TestBootstrap.getSingleton();
	}

	@Test
	public void test_notEmpty() throws NoSuchMethodException,
			SecurityException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException,
			InstantiationException {

		Object setClass = ImageBootstrapper.systemMapping.singletonAtReferenceString_("st.gravel.lang.collections.Set");
		Object set = MethodTools.safePerform(setClass, "with:", 1);
		//#notEmpty is a method from a trait
		Object bool = MethodTools.safePerform(set, "notEmpty");
		assertEquals(Boolean.TRUE, bool);
	}

}


text:
package container

import (
	"testing"

	"github.com/docker/docker/pkg/signal"
	"github.com/docker/docker/runconfig"
)

func TestContainerStopSignal(t *testing.T) {
	c := &Container{
		CommonContainer: CommonContainer{
			Config: &runconfig.Config{},
		},
	}

	def, err := signal.ParseSignal(signal.DefaultStopSignal)
	if err != nil {
		t.Fatal(err)
	}

	s := c.StopSignal()
	if s != int(def) {
		t.Fatalf("Expected %v, got %v", def, s)
	}

	c = &Container{
		CommonContainer: CommonContainer{
			Config: &runconfig.Config{StopSignal: "SIGKILL"},
		},
	}
	s = c.StopSignal()
	if s != 9 {
		t.Fatalf("Expected 9, got %v", s)
	}
}