<commit_before>#include "ros/ros.h"
#include "NavigationControl.hpp"
#include "Robosub/HighLevelControl.h"

NavigationControl::NavigationControl()
 : m_nodeHandle(),
   m_highLevelMotorPublisher()
{
  //bool OMODE = OFF;
  POINTMODE = OFF;
  LINEMODE = OFF;
  //bool Centered = false;
  Begun = false;
  OnLine = false;
  Rotating = false;

  start_x = 0;
  start_y = 0;
  start_rot = 0;

  m_highLevelMotorPublisher = m_nodeHandle.advertise<Robosub::HighLevelControl>("High_Level_Motion", 10);
  ros::Subscriber targetPoint = m_nodeHandle.subscribe("Center_On_Point", 1, &NavigationControl::PointCallback, this);
  ros::Subscriber targetLine = m_nodeHandle.subscribe("Center_On_Line", 1, &NavigationControl::LineCallback, this);
  ros::Subscriber enabled = m_nodeHandle.subscribe("Module_Enable", 1, &NavigationControl::EnabledCallback, this);
}

NavigationControl::~NavigationControl()
{

}

/**
* @brief Translates a percentage to a thrust unit
*
* @param percent Percent of the distance
*/
float NavigationControl::makeVoltage(float percent)
{
    //The smallest output is 60
    //The largets output is 255

    //map from 100 to 255 and from 60 to 5 percent

    return (percent - 5) * (255-60) / (100-5) + 60;
    //return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

}
// Create a thrust for Diving
// and send it to the motor
void NavigationControl::setDive(float val)
{

    float thrust = makeVoltage(val);
    publishMotor("Depth", "Manual",thrust);

}

void NavigationControl::setStrafe(float val)
{
    float thrust = makeVoltage(val);
    publishMotor("Straf", "Manual",thrust);
}

void NavigationControl::setDrive(float val)
{
    float thrust = makeVoltage(val);
    publishMotor("Forward", "Manual",thrust);

}

void NavigationControl::setTurn(float val)
{
    float thrust = makeVoltage(val);
    publishMotor("Turn", "Manual",thrust);
}

void NavigationControl::run()
{
    //if want to do something between spins
    //change to a while loop with ros::spinOnce() and sleep
    ros::spin();
}

void NavigationControl::EnabledCallback(const Robosub::ModuleEnableMsg& msg) {
	if(msg.Module == "NavigationControl")
	{
		//POINTMODE = msg.State;

	}
}

void NavigationControl::PointCallback(const Robosub::Point& msg)
{
		// The speed is created based on the difference between
        // the target point and the center

    // If the it is the beginning of the process
    // save the target as the objective

    // Target points
    int target_x = msg.x;
    int target_y = msg.y;

    if (!target_x && !target_y ) {
//        Centered = true;
        Begun = false;
        start_x = 0;
        start_y = 0;

        setStrafe(0);
        setDive(0);

        return;
    }

    if (!Begun){ // First assignment: create starting points
        start_x = msg.x;
        start_y = msg.y;
        Begun = true;
//        Centered = false;
    }

    // Calculate the directions what direction do we have to move?

    int dir_x = target_x>0 ? 1 : -1; //Left -1, Right +1
    int dir_y = target_y>0 ? -1 : 1; //Up -1, Down +1

    // Calculate the percentage (OR SIMPLY USE ERROR??)

    float per_x = (target_x/start_x);
    float per_y = (target_y/start_y);

    //  Control Process (calculate the right thrust)
    //  Use less than 100% based on how big the number is.

    //  Convert the distance percentage to thrust percentage

    // These are set assuming there is no bias on the voltage
    // sent to the thrusters
    int minT = 50; // to avoid sending values under the minimum.
    //maxT = 90; //To avoid moving too fast and sucking too much power
    int range = 40;

    int thrust_x = 0;
    int thrust_y = 0;

    if((per_x) <MAX_THRESHOLD){
        if((per_x)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed
            thrust_x = -60*dir_x;
        } else {
            thrust_x = 0;
        }
    } else {
        thrust_x = (range*per_x+minT)*dir_x;
    }

    if((per_y) <MAX_THRESHOLD){
        if((per_y)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed
            thrust_y = -60*dir_y;
        } else {
            thrust_y = 0; // We zeroed out in this direction
        }
    } else {
        if(dir_y>0) // && FORWARDCAMERA
            range = 30; //So we don't go up too fast
            thrust_y = (range*per_y+minT)*dir_y;
    }

    //Send the calculated speed to the motor
    setStrafe(thrust_x);
    setDive(thrust_y);

}

bool NavigationControl::moveToLine(int x, int y){
    //Returns 1 if on top of the line, 0 otherwise

    int target_x = x;
    int target_y = y;

    if (!target_x && !target_y ) {
//        Centered = true;
        Begun = false;

        start_x = 0;
        start_y = 0;

        setStrafe(0);
        setDrive(0);

        return 1; //Centered
    }

    if (!Begun){ // First assignment: create starting points
        start_x = x;
        start_y = y;
        Begun = true;
//        Centered = false;
    }

    // Calculate the directions what direction do we have to move?

    int dir_x = target_x>0 ? 1 : -1; //Left -1, Right +1
    int dir_y = target_y>0 ? 1 : -1; //Reverse -1, Forward +1

    // Calculate the percentage (OR SIMPLY USE ERROR??)

    float per_x = (target_x/start_x);
    float per_y = (target_y/start_y);

    //  Control Process (calculate the right thrust)
    //  Use less than 100% based on how big the number is.

    //  Convert the distance percentage to thrust percentage

    // These are set assuming there is no bias on the voltage
    // sent to the thrusters
    int minT = 50; // to avoid sending values under the minimum.
    //maxT = 90; //To avoid moving too fast and sucking too much power
    int range = 40;

    int thrust_x = 0;
    int thrust_y = 0;

    if((per_x) <MAX_THRESHOLD ){
        if((per_x)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed
            thrust_x = -60*dir_x;
        } else {
            thrust_x = 0; // this line may be unnecessary
        }
    } else {
        thrust_x = (range*per_x+minT)*dir_x;
    }

    if((per_y) <MAX_THRESHOLD ){
        if((per_y)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed
            thrust_y = -60*dir_y;
        } else {
            thrust_y = 0; // We zeroed out in this direction
        }
    } else {
        if(dir_y>0) //
            range = 30; //So we don't go up too fast
            thrust_y = (range*per_y+minT)*dir_y;
    }

    if (!thrust_x && !thrust_y)
        return 1; //No speed means we're <1% away

    //Send the calculated speed to the motor
    setStrafe(thrust_x);
    setDrive(thrust_y);

    return 0;

}

float NavigationControl::sanitize(float rot){
    //converts the given rotation to a number between 0-180
    if (rot>=180)
	return rot-360;
    return rot;
}

void NavigationControl::LineCallback(const Robosub::Line msg) {
	if(LINEMODE == OFF)
		return;

    OnLine = moveToLine(msg.x, msg.y);
    //Once it's on top of the line, rotate
    if (!OnLine){
        return; //keep rotating
    }

    int target_rot = sanitize(msg.rotation);
    if(!target_rot){
	 start_rot = 0;
         Rotating = 0;
	 setTurn(0);
	 return; //Stoppped by Higher Level
    }
    if(!Rotating){
        start_rot = target_rot;
    }

    float per_rot = (target_rot/start_rot);

    //This needs to be implemented better (any ideas?)
    //int direction = 1; //always rotate right?
    int direction = target_rot>0 ? 1 : -1; //-1 Rotate left

    int rate = 0;
    int range=40;
    int minR = 50;

    if(abs(per_rot)<MAX_THRESHOLD ){
        if(abs(per_rot)>.01)
            rate = -60*direction;
        else
            rate = 0;
    } else {
        rate = (range*per_rot+minR)*direction;
    }

    setTurn(rate);

}

/**
 * @brief plubish to the high level motor controller topic
 *
 * @param direction The direction: Forward, Straf, Turn
 * @param motion The motion type: Manual, Offset
 * @param value The value
 */
void NavigationControl::publishMotor(std::string direction, std::string motion, float value)
{
  Robosub::HighLevelControl msg;
  msg.Direction = direction;
  msg.MotionType = motion;
  msg.Value = value;

  m_highLevelMotorPublisher.publish(msg);
}
<commit_msg>Fix brackets on NavigationControl<commit_after>#include "ros/ros.h"
#include "NavigationControl.hpp"
#include "Robosub/HighLevelControl.h"

NavigationControl::NavigationControl()
 : m_nodeHandle(),
   m_highLevelMotorPublisher()
{
  //bool OMODE = OFF;
  POINTMODE = OFF;
  LINEMODE = OFF;
  //bool Centered = false;
  Begun = false;
  OnLine = false;
  Rotating = false;

  start_x = 0;
  start_y = 0;
  start_rot = 0;

  m_highLevelMotorPublisher = m_nodeHandle.advertise<Robosub::HighLevelControl>("High_Level_Motion", 10);
  ros::Subscriber targetPoint = m_nodeHandle.subscribe("Center_On_Point", 1, &NavigationControl::PointCallback, this);
  ros::Subscriber targetLine = m_nodeHandle.subscribe("Center_On_Line", 1, &NavigationControl::LineCallback, this);
  ros::Subscriber enabled = m_nodeHandle.subscribe("Module_Enable", 1, &NavigationControl::EnabledCallback, this);
}

NavigationControl::~NavigationControl()
{

}

/**
* @brief Translates a percentage to a thrust unit
*
* @param percent Percent of the distance
*/
float NavigationControl::makeVoltage(float percent)
{
    //The smallest output is 60
    //The largets output is 255

    //map from 100 to 255 and from 60 to 5 percent

    return (percent - 5) * (255-60) / (100-5) + 60;
    //return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;

}
// Create a thrust for Diving
// and send it to the motor
void NavigationControl::setDive(float val)
{

    float thrust = makeVoltage(val);
    publishMotor("Depth", "Manual",thrust);

}

void NavigationControl::setStrafe(float val)
{
    float thrust = makeVoltage(val);
    publishMotor("Straf", "Manual",thrust);
}

void NavigationControl::setDrive(float val)
{
    float thrust = makeVoltage(val);
    publishMotor("Forward", "Manual",thrust);

}

void NavigationControl::setTurn(float val)
{
    float thrust = makeVoltage(val);
    publishMotor("Turn", "Manual",thrust);
}

void NavigationControl::run()
{
    //if want to do something between spins
    //change to a while loop with ros::spinOnce() and sleep
    ros::spin();
}

void NavigationControl::EnabledCallback(const Robosub::ModuleEnableMsg& msg) {
	if(msg.Module == "NavigationControl")
	{
		//POINTMODE = msg.State;

	}
}

void NavigationControl::PointCallback(const Robosub::Point& msg)
{
		// The speed is created based on the difference between
        // the target point and the center

    // If the it is the beginning of the process
    // save the target as the objective

    // Target points
    int target_x = msg.x;
    int target_y = msg.y;

    if (!target_x && !target_y ) {
//        Centered = true;
        Begun = false;
        start_x = 0;
        start_y = 0;

        setStrafe(0);
        setDive(0);

        return;
    }

    if (!Begun){ // First assignment: create starting points
        start_x = msg.x;
        start_y = msg.y;
        Begun = true;
//        Centered = false;
    }

    // Calculate the directions what direction do we have to move?

    int dir_x = target_x>0 ? 1 : -1; //Left -1, Right +1
    int dir_y = target_y>0 ? -1 : 1; //Up -1, Down +1

    // Calculate the percentage (OR SIMPLY USE ERROR??)

    float per_x = (target_x/start_x);
    float per_y = (target_y/start_y);

    //  Control Process (calculate the right thrust)
    //  Use less than 100% based on how big the number is.

    //  Convert the distance percentage to thrust percentage

    // These are set assuming there is no bias on the voltage
    // sent to the thrusters
    int minT = 50; // to avoid sending values under the minimum.
    //maxT = 90; //To avoid moving too fast and sucking too much power
    int range = 40;

    int thrust_x = 0;
    int thrust_y = 0;

    if((per_x) <MAX_THRESHOLD){
        if((per_x)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed
            thrust_x = -60*dir_x;
        } else {
            thrust_x = 0;
        }
    } else {
        thrust_x = (range*per_x+minT)*dir_x;
    }

    if((per_y) <MAX_THRESHOLD){
        if((per_y)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed
            thrust_y = -60*dir_y;
        } else {
            thrust_y = 0; // We zeroed out in this direction
        }
    } else {
        if(dir_y>0){ // && FORWARDCAMERA
            range = 30; //So we don't go up too fast
            thrust_y = (range*per_y+minT)*dir_y;
		}
    }

    //Send the calculated speed to the motor
    setStrafe(thrust_x);
    setDive(thrust_y);

}

bool NavigationControl::moveToLine(int x, int y){
    //Returns 1 if on top of the line, 0 otherwise

    int target_x = x;
    int target_y = y;

    if (!target_x && !target_y ) {
//        Centered = true;
        Begun = false;

        start_x = 0;
        start_y = 0;

        setStrafe(0);
        setDrive(0);

        return 1; //Centered
    }

    if (!Begun){ // First assignment: create starting points
        start_x = x;
        start_y = y;
        Begun = true;
//        Centered = false;
    }

    // Calculate the directions what direction do we have to move?

    int dir_x = target_x>0 ? 1 : -1; //Left -1, Right +1
    int dir_y = target_y>0 ? 1 : -1; //Reverse -1, Forward +1

    // Calculate the percentage (OR SIMPLY USE ERROR??)

    float per_x = (target_x/start_x);
    float per_y = (target_y/start_y);

    //  Control Process (calculate the right thrust)
    //  Use less than 100% based on how big the number is.

    //  Convert the distance percentage to thrust percentage

    // These are set assuming there is no bias on the voltage
    // sent to the thrusters
    int minT = 50; // to avoid sending values under the minimum.
    //maxT = 90; //To avoid moving too fast and sucking too much power
    int range = 40;

    int thrust_x = 0;
    int thrust_y = 0;

    if((per_x) <MAX_THRESHOLD ){
        if((per_x)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed
            thrust_x = -60*dir_x;
        } else {
            thrust_x = 0; // this line may be unnecessary
        }
    } else {
        thrust_x = (range*per_x+minT)*dir_x;
    }

    if((per_y) <MAX_THRESHOLD ){
        if((per_y)>MIN_THRESHOLD){ //Send a negative thrust to decrease the speed
            thrust_y = -60*dir_y;
        } else {
            thrust_y = 0; // We zeroed out in this direction
        }
    } else {
        if(dir_y>0){ //
            range = 30; //So we don't go up too fast
            thrust_y = (range*per_y+minT)*dir_y;
		}
    }

    if (!thrust_x && !thrust_y)
        return 1; //No speed means we're <1% away

    //Send the calculated speed to the motor
    setStrafe(thrust_x);
    setDrive(thrust_y);

    return 0;

}

float NavigationControl::sanitize(float rot){
    //converts the given rotation to a number between 0-180
    if (rot>=180)
	return rot-360;
    return rot;
}

void NavigationControl::LineCallback(const Robosub::Line msg) {
	if(LINEMODE == OFF)
		return;

    OnLine = moveToLine(msg.x, msg.y);
    //Once it's on top of the line, rotate
    if (!OnLine){
        return; //keep rotating
    }

    int target_rot = sanitize(msg.rotation);
    if(!target_rot){
	 start_rot = 0;
         Rotating = 0;
	 setTurn(0);
	 return; //Stoppped by Higher Level
    }
    if(!Rotating){
        start_rot = target_rot;
    }

    float per_rot = (target_rot/start_rot);

    //This needs to be implemented better (any ideas?)
    //int direction = 1; //always rotate right?
    int direction = target_rot>0 ? 1 : -1; //-1 Rotate left

    int rate = 0;
    int range=40;
    int minR = 50;

    if(abs(per_rot)<MAX_THRESHOLD ){
        if(abs(per_rot)>.01)
            rate = -60*direction;
        else
            rate = 0;
    } else {
        rate = (range*per_rot+minR)*direction;
    }

    setTurn(rate);

}

/**
 * @brief plubish to the high level motor controller topic
 *
 * @param direction The direction: Forward, Straf, Turn
 * @param motion The motion type: Manual, Offset
 * @param value The value
 */
void NavigationControl::publishMotor(std::string direction, std::string motion, float value)
{
  Robosub::HighLevelControl msg;
  msg.Direction = direction;
  msg.MotionType = motion;
  msg.Value = value;

  m_highLevelMotorPublisher.publish(msg);
}
<|endoftext|>


<commit_before>/* http_bidder_interface.cc
   Eric Robert, 2 April 2014
   Copyright (c) 2011 Datacratic.  All rights reserved.
*/

#include "http_bidder_interface.h"
#include "jml/db/persistent.h"
#include "soa/service/http_client.h"
#include "soa/utils/generic_utils.h"
#include "rtbkit/common/messages.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_request.h"
#include "rtbkit/openrtb/openrtb_parsing.h"
#include "rtbkit/core/router/router.h"

using namespace Datacratic;
using namespace RTBKIT;

namespace {
    DefaultDescription<OpenRTB::BidRequest> desc;

    std::string httpErrorString(HttpClientError code)  {
        switch (code) {
            #define CASE(code) \
                case code: \
                    return #code;
            CASE(HttpClientError::NONE)
            CASE(HttpClientError::UNKNOWN)
            CASE(HttpClientError::TIMEOUT)
            CASE(HttpClientError::HOST_NOT_FOUND)
            CASE(HttpClientError::COULD_NOT_CONNECT)
            #undef CASE
        }
        ExcCheck(false, "Invalid code path");
        return "";
    }
}

namespace RTBKIT {

Logging::Category HttpBidderInterface::print("HttpBidderInterface");
Logging::Category HttpBidderInterface::error("HttpBidderInterface Error", HttpBidderInterface::print);
Logging::Category HttpBidderInterface::trace("HttpBidderInterface Trace", HttpBidderInterface::print);

}

HttpBidderInterface::HttpBidderInterface(std::string serviceName,
                                         std::shared_ptr<ServiceProxies> proxies,
                                         Json::Value const & json)
        : BidderInterface(proxies, serviceName) {

    try {
        routerHost = json["router"]["host"].asString();
        routerPath = json["router"]["path"].asString();
        adserverHost = json["adserver"]["host"].asString();
        adserverWinPort = json["adserver"]["winPort"].asInt();
        adserverEventPort = json["adserver"]["eventPort"].asInt();
    } catch (const std::exception & e) {
        THROW(error) << "configuration file is invalid" << std::endl
                   << "usage : " << std::endl
                   << "{" << std::endl << "\t\"router\" : {" << std::endl
                   << "\t\t\"host\" : <string : hostname with port>" << std::endl
                   << "\t\t\"path\" : <string : resource name>" << std::endl
                   << "\t}" << std::endl << "\t{" << std::endl
                   << "\t{" << std::endl << "\t\"adserver\" : {" << std::endl
                   << "\t\t\"host\" : <string : hostname>" << std::endl
                   << "\t\t\"winPort\" : <int : winPort>" << std::endl
                   << "\t\t\"eventPort\" : <int eventPort>" << std::endl
                   << "\t}" << std::endl << "}";
    }

    httpClientRouter.reset(new HttpClient(routerHost));
    loop.addSource("HttpBidderInterface::httpClientRouter", httpClientRouter);

    std::string winHost = adserverHost + ':' + std::to_string(adserverWinPort);
    httpClientAdserverWins.reset(new HttpClient(winHost));
    loop.addSource("HttpBidderInterface::httpClientAdserverWins", httpClientAdserverWins);

    std::string eventHost = adserverHost + ':' + std::to_string(adserverEventPort);
    httpClientAdserverEvents.reset(new HttpClient(eventHost));
    loop.addSource("HttpBidderInterface::httpClientAdserverEvents", httpClientAdserverEvents);

}

HttpBidderInterface::~HttpBidderInterface()
{
    shutdown();
}

void HttpBidderInterface::start() {
    loop.start();
}

void HttpBidderInterface::shutdown() {
    loop.shutdown();
}

void HttpBidderInterface::sendAuctionMessage(std::shared_ptr<Auction> const & auction,
                                             double timeLeftMs,
                                             std::map<std::string, BidInfo> const & bidders) {
    using namespace std;

    auto findAgent = [=](uint64_t externalId)
        -> pair<string, shared_ptr<const AgentConfig>> {

        auto it =
        find_if(begin(bidders), end(bidders),
                [&](const pair<string, BidInfo> &bidder)
        {
            std::string agent = bidder.first;
            const auto &info = router->agents[agent];
            return info.config->externalId == externalId;
        });

        if (it == end(bidders)) {
            return make_pair("", nullptr);
        }

        return make_pair(it->first, it->second.agentConfig);

    };

    BidRequest originalRequest = *auction->request;
    OpenRTB::BidRequest openRtbRequest = toOpenRtb(originalRequest);
    bool ok = prepareRequest(openRtbRequest, originalRequest, bidders);
    /* If we took too much time processing the request, then we don't send it.  */
    if (!ok) {
        return;
    }
    StructuredJsonPrintingContext context;
    desc.printJson(&openRtbRequest, context);
    auto requestStr = context.output.toString();

    /* We need to capture by copy inside the lambda otherwise we might get
       a dangling reference if we go out of scope before receiving the http response
    */
    auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(
            [=](const HttpRequest &, HttpClientError errorCode,
                int statusCode, const std::string &, std::string &&body)
            {
                if (errorCode != HttpClientError::NONE) {
                    router->throwException("http", "Error requesting %s: %s",
                                           routerHost.c_str(),
                                           httpErrorString(errorCode).c_str());
                  }
                  // If we receive a 204 No-bid, we still need to "re-inject" it to the
                  // router otherwise we won't expire the inFlights
                  else if (statusCode == 204) {
                     Bids bids;
                     bids.resize(openRtbRequest.imp.size());
                     fill(begin(bids), end(bids), Bid());
                     for (const auto &bidder: bidders) {
                         submitBids(bidder.first, auction->id, bids, WinCostModel());
                     }
                  }

                  else if (statusCode == 200) {
                    // cerr << "Response: " << body << endl;
                     OpenRTB::BidResponse response;
                     ML::Parse_Context context("payload",
                           body.c_str(), body.size());
                     StreamingJsonParsingContext jsonContext(context);
                     static DefaultDescription<OpenRTB::BidResponse> respDesc;
                     respDesc.parseJson(&response, jsonContext);

                     for (const auto &seatbid: response.seatbid) {

                         for (const auto &bid: seatbid.bid) {
                             if (!bid.ext.isMember("external-id")) {
                                 router->throwException("http.response",
                                    "Missing external-id ext field in BidResponse");
                             }

                             if (!bid.ext.isMember("priority")) {
                                 router->throwException("http.response",
                                    "Missing priority ext field in BidResponse");
                             }

                             uint64_t externalId = bid.ext["external-id"].asUInt();

                             string agent;
                             shared_ptr<const AgentConfig> config;
                             tie(agent, config) = findAgent(externalId);
                             if (config == nullptr) {
                                 router->throwException("http.response",
                                    "Couldn't find config for externalId: %lu",
                                    externalId);
                             }

                             Bids bids;
                             Bid theBid;

                             int crid = bid.crid.toInt();
                             int creativeIndex = indexOf(config->creatives,
                                 &Creative::id, crid);

                             if (creativeIndex == -1) {
                                 router->throwException("http.response",
                                    "Unknown creative id: %d", crid);
                             }

                             theBid.creativeIndex = creativeIndex;
                             theBid.price = USD_CPM(bid.price.val);
                             theBid.priority = bid.ext["priority"].asDouble();

                             int spotIndex = indexOf(openRtbRequest.imp,
                                                    &OpenRTB::Impression::id, bid.impid);
                             if (spotIndex == -1) {
                                  router->throwException("http.response",
                                     "Unknown impression id: %s",
                                     bid.impid.toString().c_str());
                             }

                             theBid.spotIndex = spotIndex;

                             bids.push_back(std::move(theBid));

                             WinCostModel wcm =
                                 auction->exchangeConnector->getWinCostModel(*auction, *config);

                             submitBids(agent, auction->id, bids, wcm);
                         }
                     }
                 }
            }
    );

    HttpRequest::Content reqContent { requestStr, "application/json" };
    RestParams headers { { "x-openrtb-version", "2.1" } };
   // std::cerr << "Sending HTTP POST to: " << host << " " << path << std::endl;
   // std::cerr << "Content " << reqContent.str << std::endl;

    httpClientRouter->post(routerPath, callbacks, reqContent,
                     { } /* queryParams */, headers);
}

void HttpBidderInterface::sendLossMessage(std::string const & agent,
                                          std::string const & id) {

}

void HttpBidderInterface::sendWinLossMessage(MatchedWinLoss const & event) {
    if (event.type == MatchedWinLoss::Loss) return;

    auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(
        [=](const HttpRequest &, HttpClientError errorCode,
            int statusCode, const std::string &, std::string &&body)
        {
            if (errorCode != HttpClientError::NONE) {
                throw ML::Exception("Error requesting %s:%d '%s'",
                                    adserverHost.c_str(),
                                    adserverWinPort,
                                    httpErrorString(errorCode).c_str());
              }
        });

    Json::Value content;

    content["timestamp"] = event.timestamp.secondsSinceEpoch();
    content["bidRequestId"] = event.auctionId.toString();
    content["impid"] = event.impId.toString();
    content["userIds"] = event.uids.toJson();
    // ratio cannot be casted to json::value ...
    content["price"] = (double) getAmountIn<CPM>(event.winPrice);

    //requestStr["passback"];

    HttpRequest::Content reqContent { content, "application/json" };
    httpClientAdserverWins->post("/", callbacks, reqContent,
                         { } /* queryParams */);

}

void HttpBidderInterface::sendBidLostMessage(std::string const & agent,
                                             std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendCampaignEventMessage(std::string const & agent,
                                                   MatchedCampaignEvent const & event) {
    auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(
        [=](const HttpRequest &, HttpClientError errorCode,
            int statusCode, const std::string &, std::string &&body)
        {
            if (errorCode != HttpClientError::NONE) {
                throw ML::Exception("Error requesting %s:%d '%s'",
                                    adserverHost.c_str(),
                                    adserverEventPort,
                                    httpErrorString(errorCode).c_str());
              }
        });

    Json::Value content;

    content["timestamp"] = event.timestamp.secondsSinceEpoch();
    content["bidRequestId"] = event.auctionId.toString();
    content["impid"] = event.impId.toString();
    content["type"] = event.label;

    HttpRequest::Content reqContent { content, "application/json" };
    httpClientAdserverEvents->post("/", callbacks, reqContent,
                         { } /* queryParams */);

}

void HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,
                                                std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,
                                                std::string const & reason,
                                                std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,
                                              std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendTooLateMessage(std::string const & agent,
                                             std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendMessage(std::string const & agent,
                                      std::string const & message) {
}

void HttpBidderInterface::sendErrorMessage(std::string const & agent,
                                           std::string const & error,
                                           std::vector<std::string> const & payload) {
}

void HttpBidderInterface::sendPingMessage(std::string const & agent,
                                          int ping) {
    ExcCheck(ping == 0 || ping == 1, "Bad PING level, must be either 0 or 1");

    auto encodeDate = [](Date date) {
        return ML::format("%.5f", date.secondsSinceEpoch());
    };

    const std::string sentTime = encodeDate(Date::now());
    const std::string receivedTime = sentTime;
    const std::string pong = (ping == 0 ? "PONG0" : "PONG1");
    std::vector<std::string> message { agent, pong, sentTime, receivedTime };
    router->handleAgentMessage(message);
}

void HttpBidderInterface::tagRequest(OpenRTB::BidRequest &request,
                                     const std::map<std::string, BidInfo> &bidders) const
{

    for (const auto &bidder: bidders) {
        const auto &agentConfig = bidder.second.agentConfig;
        const auto &spots = bidder.second.imp;

        for (const auto &spot: spots) {
            const int adSpotIndex = spot.first;
            ExcCheck(adSpotIndex >= 0 && adSpotIndex < request.imp.size(),
                     "adSpotIndex out of range");
            auto &imp = request.imp[adSpotIndex];
            auto &ext = imp.ext;

            ext["external-ids"].append(agentConfig->externalId);
        }

    }

}

bool HttpBidderInterface::prepareRequest(OpenRTB::BidRequest &request,
                                         const RTBKIT::BidRequest &originalRequest,
                                         const std::map<std::string, BidInfo> &bidders) const {
    tagRequest(request, bidders);

    // We update the tmax value before sending the BidRequest to substract our processing time
    double processingTimeMs = originalRequest.timestamp.secondsUntil(Date::now()) * 1000;
    int oldTmax = request.tmax.value();
    int newTmax = oldTmax - static_cast<int>(std::round(processingTimeMs));
    if (newTmax <= 0) {
        return false;
    }
#if 0
        std::cerr << "old tmax = " << oldTmax << std::std::endl
                  << "new tmax = " << newTmax << std::std::endl;
#endif
    ExcCheck(newTmax <= oldTmax, "Wrong tmax calculation");
    request.tmax.val = newTmax;
    return true;
}

void HttpBidderInterface::submitBids(const std::string &agent, Id auctionId,
                                     const Bids &bids, WinCostModel wcm)
{
     Json::FastWriter writer;
     std::vector<std::string> message { agent, "BID" };
     message.push_back(auctionId.toString());
     std::string bidsStr = writer.write(bids.toJson());
     std::string wcmStr = writer.write(wcm.toJson());
     message.push_back(std::move(bidsStr));
     message.push_back(std::move(wcmStr));

     router->doBid(message);
}

//
// factory
//

namespace {

struct AtInit {
    AtInit()
    {
        BidderInterface::registerFactory("http",
        [](std::string const & serviceName,
           std::shared_ptr<ServiceProxies> const & proxies,
           Json::Value const & json)
        {
            return new HttpBidderInterface(serviceName, proxies, json);
        });
    }
} atInit;

}

<commit_msg>HttpBidderInterface: Making sure to remove the trailing characters that might be introduced by Json::FastWriter<commit_after>/* http_bidder_interface.cc
   Eric Robert, 2 April 2014
   Copyright (c) 2011 Datacratic.  All rights reserved.
*/

#include "http_bidder_interface.h"
#include "jml/db/persistent.h"
#include "soa/service/http_client.h"
#include "soa/utils/generic_utils.h"
#include "rtbkit/common/messages.h"
#include "rtbkit/plugins/bid_request/openrtb_bid_request.h"
#include "rtbkit/openrtb/openrtb_parsing.h"
#include "rtbkit/core/router/router.h"

using namespace Datacratic;
using namespace RTBKIT;

namespace {
    DefaultDescription<OpenRTB::BidRequest> desc;

    std::string httpErrorString(HttpClientError code)  {
        switch (code) {
            #define CASE(code) \
                case code: \
                    return #code;
            CASE(HttpClientError::NONE)
            CASE(HttpClientError::UNKNOWN)
            CASE(HttpClientError::TIMEOUT)
            CASE(HttpClientError::HOST_NOT_FOUND)
            CASE(HttpClientError::COULD_NOT_CONNECT)
            #undef CASE
        }
        ExcCheck(false, "Invalid code path");
        return "";
    }
}

namespace RTBKIT {

Logging::Category HttpBidderInterface::print("HttpBidderInterface");
Logging::Category HttpBidderInterface::error("HttpBidderInterface Error", HttpBidderInterface::print);
Logging::Category HttpBidderInterface::trace("HttpBidderInterface Trace", HttpBidderInterface::print);

}

HttpBidderInterface::HttpBidderInterface(std::string serviceName,
                                         std::shared_ptr<ServiceProxies> proxies,
                                         Json::Value const & json)
        : BidderInterface(proxies, serviceName) {

    try {
        routerHost = json["router"]["host"].asString();
        routerPath = json["router"]["path"].asString();
        adserverHost = json["adserver"]["host"].asString();
        adserverWinPort = json["adserver"]["winPort"].asInt();
        adserverEventPort = json["adserver"]["eventPort"].asInt();
    } catch (const std::exception & e) {
        THROW(error) << "configuration file is invalid" << std::endl
                   << "usage : " << std::endl
                   << "{" << std::endl << "\t\"router\" : {" << std::endl
                   << "\t\t\"host\" : <string : hostname with port>" << std::endl
                   << "\t\t\"path\" : <string : resource name>" << std::endl
                   << "\t}" << std::endl << "\t{" << std::endl
                   << "\t{" << std::endl << "\t\"adserver\" : {" << std::endl
                   << "\t\t\"host\" : <string : hostname>" << std::endl
                   << "\t\t\"winPort\" : <int : winPort>" << std::endl
                   << "\t\t\"eventPort\" : <int eventPort>" << std::endl
                   << "\t}" << std::endl << "}";
    }

    httpClientRouter.reset(new HttpClient(routerHost));
    loop.addSource("HttpBidderInterface::httpClientRouter", httpClientRouter);

    std::string winHost = adserverHost + ':' + std::to_string(adserverWinPort);
    httpClientAdserverWins.reset(new HttpClient(winHost));
    loop.addSource("HttpBidderInterface::httpClientAdserverWins", httpClientAdserverWins);

    std::string eventHost = adserverHost + ':' + std::to_string(adserverEventPort);
    httpClientAdserverEvents.reset(new HttpClient(eventHost));
    loop.addSource("HttpBidderInterface::httpClientAdserverEvents", httpClientAdserverEvents);

}

HttpBidderInterface::~HttpBidderInterface()
{
    shutdown();
}

void HttpBidderInterface::start() {
    loop.start();
}

void HttpBidderInterface::shutdown() {
    loop.shutdown();
}

void HttpBidderInterface::sendAuctionMessage(std::shared_ptr<Auction> const & auction,
                                             double timeLeftMs,
                                             std::map<std::string, BidInfo> const & bidders) {
    using namespace std;

    auto findAgent = [=](uint64_t externalId)
        -> pair<string, shared_ptr<const AgentConfig>> {

        auto it =
        find_if(begin(bidders), end(bidders),
                [&](const pair<string, BidInfo> &bidder)
        {
            std::string agent = bidder.first;
            const auto &info = router->agents[agent];
            return info.config->externalId == externalId;
        });

        if (it == end(bidders)) {
            return make_pair("", nullptr);
        }

        return make_pair(it->first, it->second.agentConfig);

    };

    BidRequest originalRequest = *auction->request;
    OpenRTB::BidRequest openRtbRequest = toOpenRtb(originalRequest);
    bool ok = prepareRequest(openRtbRequest, originalRequest, bidders);
    /* If we took too much time processing the request, then we don't send it.  */
    if (!ok) {
        return;
    }
    StructuredJsonPrintingContext context;
    desc.printJson(&openRtbRequest, context);
    auto requestStr = context.output.toString();

    /* We need to capture by copy inside the lambda otherwise we might get
       a dangling reference if we go out of scope before receiving the http response
    */
    auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(
            [=](const HttpRequest &, HttpClientError errorCode,
                int statusCode, const std::string &, std::string &&body)
            {
                if (errorCode != HttpClientError::NONE) {
                    router->throwException("http", "Error requesting %s: %s",
                                           routerHost.c_str(),
                                           httpErrorString(errorCode).c_str());
                  }
                  // If we receive a 204 No-bid, we still need to "re-inject" it to the
                  // router otherwise we won't expire the inFlights
                  else if (statusCode == 204) {
                     Bids bids;
                     bids.resize(openRtbRequest.imp.size());
                     fill(begin(bids), end(bids), Bid());
                     for (const auto &bidder: bidders) {
                         submitBids(bidder.first, auction->id, bids, WinCostModel());
                     }
                  }

                  else if (statusCode == 200) {
                    // cerr << "Response: " << body << endl;
                     OpenRTB::BidResponse response;
                     ML::Parse_Context context("payload",
                           body.c_str(), body.size());
                     StreamingJsonParsingContext jsonContext(context);
                     static DefaultDescription<OpenRTB::BidResponse> respDesc;
                     respDesc.parseJson(&response, jsonContext);

                     for (const auto &seatbid: response.seatbid) {

                         for (const auto &bid: seatbid.bid) {
                             if (!bid.ext.isMember("external-id")) {
                                 router->throwException("http.response",
                                    "Missing external-id ext field in BidResponse");
                             }

                             if (!bid.ext.isMember("priority")) {
                                 router->throwException("http.response",
                                    "Missing priority ext field in BidResponse");
                             }

                             uint64_t externalId = bid.ext["external-id"].asUInt();

                             string agent;
                             shared_ptr<const AgentConfig> config;
                             tie(agent, config) = findAgent(externalId);
                             if (config == nullptr) {
                                 router->throwException("http.response",
                                    "Couldn't find config for externalId: %lu",
                                    externalId);
                             }

                             Bids bids;
                             Bid theBid;

                             int crid = bid.crid.toInt();
                             int creativeIndex = indexOf(config->creatives,
                                 &Creative::id, crid);

                             if (creativeIndex == -1) {
                                 router->throwException("http.response",
                                    "Unknown creative id: %d", crid);
                             }

                             theBid.creativeIndex = creativeIndex;
                             theBid.price = USD_CPM(bid.price.val);
                             theBid.priority = bid.ext["priority"].asDouble();

                             int spotIndex = indexOf(openRtbRequest.imp,
                                                    &OpenRTB::Impression::id, bid.impid);
                             if (spotIndex == -1) {
                                  router->throwException("http.response",
                                     "Unknown impression id: %s",
                                     bid.impid.toString().c_str());
                             }

                             theBid.spotIndex = spotIndex;

                             bids.push_back(std::move(theBid));

                             WinCostModel wcm =
                                 auction->exchangeConnector->getWinCostModel(*auction, *config);

                             submitBids(agent, auction->id, bids, wcm);
                         }
                     }
                 }
            }
    );

    HttpRequest::Content reqContent { requestStr, "application/json" };
    RestParams headers { { "x-openrtb-version", "2.1" } };
   // std::cerr << "Sending HTTP POST to: " << host << " " << path << std::endl;
   // std::cerr << "Content " << reqContent.str << std::endl;

    httpClientRouter->post(routerPath, callbacks, reqContent,
                     { } /* queryParams */, headers);
}

void HttpBidderInterface::sendLossMessage(std::string const & agent,
                                          std::string const & id) {

}

void HttpBidderInterface::sendWinLossMessage(MatchedWinLoss const & event) {
    if (event.type == MatchedWinLoss::Loss) return;

    auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(
        [=](const HttpRequest &, HttpClientError errorCode,
            int statusCode, const std::string &, std::string &&body)
        {
            if (errorCode != HttpClientError::NONE) {
                throw ML::Exception("Error requesting %s:%d '%s'",
                                    adserverHost.c_str(),
                                    adserverWinPort,
                                    httpErrorString(errorCode).c_str());
              }
        });

    Json::Value content;

    content["timestamp"] = event.timestamp.secondsSinceEpoch();
    content["bidRequestId"] = event.auctionId.toString();
    content["impid"] = event.impId.toString();
    content["userIds"] = event.uids.toJson();
    // ratio cannot be casted to json::value ...
    content["price"] = (double) getAmountIn<CPM>(event.winPrice);

    //requestStr["passback"];

    HttpRequest::Content reqContent { content, "application/json" };
    httpClientAdserverWins->post("/", callbacks, reqContent,
                         { } /* queryParams */);

}

void HttpBidderInterface::sendBidLostMessage(std::string const & agent,
                                             std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendCampaignEventMessage(std::string const & agent,
                                                   MatchedCampaignEvent const & event) {
    auto callbacks = std::make_shared<HttpClientSimpleCallbacks>(
        [=](const HttpRequest &, HttpClientError errorCode,
            int statusCode, const std::string &, std::string &&body)
        {
            if (errorCode != HttpClientError::NONE) {
                throw ML::Exception("Error requesting %s:%d '%s'",
                                    adserverHost.c_str(),
                                    adserverEventPort,
                                    httpErrorString(errorCode).c_str());
              }
        });

    Json::Value content;

    content["timestamp"] = event.timestamp.secondsSinceEpoch();
    content["bidRequestId"] = event.auctionId.toString();
    content["impid"] = event.impId.toString();
    content["type"] = event.label;

    HttpRequest::Content reqContent { content, "application/json" };
    httpClientAdserverEvents->post("/", callbacks, reqContent,
                         { } /* queryParams */);

}

void HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,
                                                std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,
                                                std::string const & reason,
                                                std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,
                                              std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendTooLateMessage(std::string const & agent,
                                             std::shared_ptr<Auction> const & auction) {
}

void HttpBidderInterface::sendMessage(std::string const & agent,
                                      std::string const & message) {
}

void HttpBidderInterface::sendErrorMessage(std::string const & agent,
                                           std::string const & error,
                                           std::vector<std::string> const & payload) {
}

void HttpBidderInterface::sendPingMessage(std::string const & agent,
                                          int ping) {
    ExcCheck(ping == 0 || ping == 1, "Bad PING level, must be either 0 or 1");

    auto encodeDate = [](Date date) {
        return ML::format("%.5f", date.secondsSinceEpoch());
    };

    const std::string sentTime = encodeDate(Date::now());
    const std::string receivedTime = sentTime;
    const std::string pong = (ping == 0 ? "PONG0" : "PONG1");
    std::vector<std::string> message { agent, pong, sentTime, receivedTime };
    router->handleAgentMessage(message);
}

void HttpBidderInterface::tagRequest(OpenRTB::BidRequest &request,
                                     const std::map<std::string, BidInfo> &bidders) const
{

    for (const auto &bidder: bidders) {
        const auto &agentConfig = bidder.second.agentConfig;
        const auto &spots = bidder.second.imp;

        for (const auto &spot: spots) {
            const int adSpotIndex = spot.first;
            ExcCheck(adSpotIndex >= 0 && adSpotIndex < request.imp.size(),
                     "adSpotIndex out of range");
            auto &imp = request.imp[adSpotIndex];
            auto &ext = imp.ext;

            ext["external-ids"].append(agentConfig->externalId);
        }

    }

}

bool HttpBidderInterface::prepareRequest(OpenRTB::BidRequest &request,
                                         const RTBKIT::BidRequest &originalRequest,
                                         const std::map<std::string, BidInfo> &bidders) const {
    tagRequest(request, bidders);

    // We update the tmax value before sending the BidRequest to substract our processing time
    double processingTimeMs = originalRequest.timestamp.secondsUntil(Date::now()) * 1000;
    int oldTmax = request.tmax.value();
    int newTmax = oldTmax - static_cast<int>(std::round(processingTimeMs));
    if (newTmax <= 0) {
        return false;
    }
#if 0
        std::cerr << "old tmax = " << oldTmax << std::std::endl
                  << "new tmax = " << newTmax << std::std::endl;
#endif
    ExcCheck(newTmax <= oldTmax, "Wrong tmax calculation");
    request.tmax.val = newTmax;
    return true;
}

void HttpBidderInterface::submitBids(const std::string &agent, Id auctionId,
                                     const Bids &bids, WinCostModel wcm)
{
     Json::FastWriter writer;
     std::vector<std::string> message { agent, "BID" };
     message.push_back(auctionId.toString());

     std::string bidsStr = writer.write(bids.toJson());
     boost::trim(bidsStr);

     std::string wcmStr = writer.write(wcm.toJson());
     boost::trim(wcmStr);

     message.push_back(std::move(bidsStr));
     message.push_back(std::move(wcmStr));

     router->doBid(message);
}

//
// factory
//

namespace {

struct AtInit {
    AtInit()
    {
        BidderInterface::registerFactory("http",
        [](std::string const & serviceName,
           std::shared_ptr<ServiceProxies> const & proxies,
           Json::Value const & json)
        {
            return new HttpBidderInterface(serviceName, proxies, json);
        });
    }
} atInit;

}

<|endoftext|>


<commit_before><commit_msg>fix iterator issue in client_test<commit_after><|endoftext|>


<commit_before>// $Author: benine $
//
// Coded and compiled using c++11 standard

#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <unistd.h>
#include <functional>
#include "contig.hpp"
#include "print_time.hpp"
#include "process.hpp"
#include "read.hpp"
#include "afin_util.hpp"

using namespace std;

// TASK:: create installer with ability to test for presence of zlib? and/or install zlib
//          give installer capability to install to default directory or accept input directory to install executable to.. or just leave it in the base directory of the code
// TASK:: add signal handling
// TASK:: add support for gzipped files
// TASK:: give option to suppress output to screen
// TASK:: Review what goes into the logfile vs what gets printed to the screen
// TASK:: Look into whether N's and misses should be counted together? Or how they should relate to each other
// TASK:: Exact matching in the contig_fusion_support() may be too conservative
// TASK:: Review check_cov() and use a coverage that incorporates only the matching bp at that position
// TASK:: make global variables and options for the variables that need it
// TASK:: Change names of any functions that no longer title their function
// TASK:: Write up documentation explaining each option, its purpose, and why the default is set the way it is
// TASK:: Check limits of readlist size and other limits at all points of the program
// TASK:: Clean up functions, break long functions into smaller ones and eliminate unused functions
// TASK:: Remove using line from each file and add std:: where necessary
//
// TASK:: Throws out_of_range error when min_overlap < 4.... ? Not that it should ever be that low
//
// TASK:: add long options
// TASK:: Add processing for IUPAC DNA ambiguity codes
// TASK:: Add processing for differences in reads( ie, create new contig objects for differing sets of matches, add method for splitting matchlist between two new contig objects ), determine which contig is correct

/////////////////////////////////////////////////////////////////////////////////\
// BEGIN MAIN FUNCTION ///////////////////////////////////////////////////////////>
/////////////////////////////////////////////////////////////////////////////////
int main( int argc, char** argv ){
  //////////////////////////////////
  // Process Command Line Options //
  //////////////////////////////////
  max_search_loops = 10;
  contig_sub_len = 100;
  extend_len = 80;
  max_sort_char = 4;
  min_cov_init = 5;
  min_overlap = 20;
  max_threads = 4;
  initial_trim = 20;
  max_missed = 5;
  mismatch_threshold = 0.1;
  test_run = false;
  int c;
  Process process;

  // prevent output to stderr if erroneous option is found
  opterr = 0;

  // get all options that have been provided on the command line
  while (( c = getopt (argc, argv, "hr:c:o:s:l:x:m:i:p:t:a:b:d:e:f:g:z" )) != -1 ) {
    switch( c ) {
      case 'h':
        print_usage( argv[0] );
        exit(0);
        break;
      // max_sort_char option
      case 'm':
        max_sort_char = atoi(optarg);
        break;
      // contig_sub_len option
      case 's':
        contig_sub_len = atoi(optarg);
        break;
      // extend_len option
      case 'x':
        extend_len = atoi(optarg);
        break;
      // max_sort_char option
      case 'l':
        max_search_loops = atoi(optarg);
        break;
      // min_cov_init option
      case 'i':
        min_cov_init = atoi(optarg);
        break;
      // min_overlap option
      case 'p':
        min_overlap = atoi(optarg);
        break;
      // max_threads option
      case 't':
        max_threads = atoi(optarg);
        break;
      // initial_trim option
      case 'd':
        initial_trim = atoi(optarg);
        break;
      // max_missed option
      case 'e':
        max_missed = atoi(optarg);
        break;
      // mismatch_threshold option
      case 'g':
        mismatch_threshold = atof(optarg);
        break;
      // outputfile option
      case 'o':
        cout << "output file: " << optarg << endl;
        process.outfile = optarg;
        print_time();
        break;
      // readfile option
      case 'r':
        optind--;
        // loop through each file
        while ( optind < argc && argv[optind][0] != '-' ) {
          process.readsfiles.append( "," );
          process.readsfiles.append( argv[optind] );
          optind++;
        }
        break;
      // contig file option
      case 'c':
        optind--;
        // loop through each file
        while ( optind < argc && argv[optind][0] != '-' ) {
          process.contigsfiles.append( "," );
          process.contigsfiles.append( argv[optind] );
          optind++;
        }
        break;
      // test_run option
      case 'z':
        test_run = true;
        break;
      case '?':
        if ( optopt == 'r' ){
          fprintf( stderr, "%s: Error: Option -r requires an argument. ", argv[0] );
          print_usage( argv[0] );
        }
        else if ( optopt == 'o' ){
          fprintf( stderr, "%s: Error: Option -o requires an argument. ", argv[0] );
          print_usage( argv[0] );
        }
        else if ( optopt == 'c' ){
          fprintf( stderr, "%s: Error: Option -c requires an argument. ", argv[0] );
          print_usage( argv[0] );
        }
        else if ( isprint( optopt )){
          fprintf( stderr, "%s: Error: Unknown option -%c. \n", argv[0], optopt );
          print_usage( argv[0] );
        }
        else{
          fprintf( stderr, "%s: Error: Unknown option character %x.\n", argv[0], optopt );
          print_usage( argv[0] );
        }
        return 1;
      default:
        abort();
    }
  }

  while ( optind < argc ) {
    cout << argv[optind] << endl;
    optind++;
  }

  /////////////////
  // End Options //
  /////////////////

  ///////////////////////
  // Test Thread Queue //
  ///////////////////////

  // start run
  process.start_run();

  int length[process.contigs.size()];
  for( int i=0; i<process.contigs.size(); i++ ){
    length[i] = process.get_contig(i).length();
  }

  // print out each contig and the number of bp added
  for( int i=0; i<process.contigs.size(); i++ ){
    cout << "Contig[" << i << "]: " << process.get_contig(i) << endl;
    cout << "\tbp added: " << process.get_contig(i).length() - length[i] << endl;
  }

  cout << "exit time: ";
  print_time();

  process.print_to_outfile();

  return 0;
}

//////////////
// END MAIN //
//////////////
<commit_msg>just a couple of small changes to afin.cpp<commit_after>// $Author: benine $
//
// Coded and compiled using c++11 standard

#include <cstdio>
#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <unistd.h>
#include <functional>
#include "contig.hpp"
#include "print_time.hpp"
#include "process.hpp"
#include "read.hpp"
#include "afin_util.hpp"

using namespace std;

// TASK:: create installer with ability to test for presence of zlib? and/or install zlib
//          give installer capability to install to default directory or accept input directory to install executable to.. or just leave it in the base directory of the code
// TASK:: add signal handling
// TASK:: add support for gzipped files
// TASK:: give option to suppress output to screen
// TASK:: Review what goes into the logfile vs what gets printed to the screen
// TASK:: Look into whether N's and misses should be counted together? Or how they should relate to each other
// TASK:: Exact matching in the contig_fusion_support() may be too conservative
// TASK:: Review check_cov() and use a coverage that incorporates only the matching bp at that position
// TASK:: make global variables and options for the variables that need it
// TASK:: Change names of any functions that no longer title their function
// TASK:: Write up documentation explaining each option, its purpose, and why the default is set the way it is
// TASK:: Check limits of readlist size and other limits at all points of the program
// TASK:: Clean up functions, break long functions into smaller ones and eliminate unused functions
// TASK:: Remove using line from each file and add std:: where necessary
//
// TASK:: Throws out_of_range error when min_overlap < 4.... ? Not that it should ever be that low
//
// TASK:: add long options
// TASK:: Add processing for IUPAC DNA ambiguity codes
// TASK:: Add processing for differences in reads( ie, create new contig objects for differing sets of matches, add method for splitting matchlist between two new contig objects ), determine which contig is correct

/////////////////////////////////////////////////////////////////////////////////\
// BEGIN MAIN FUNCTION ///////////////////////////////////////////////////////////>
/////////////////////////////////////////////////////////////////////////////////
int main( int argc, char** argv ){
  //////////////////////////////////
  // Process Command Line Options //
  //////////////////////////////////
  max_search_loops = 10;
  contig_sub_len = 100;
  extend_len = 80;
  max_sort_char = 4;
  min_cov_init = 5;
  min_overlap = 20;
  max_threads = 4;
  initial_trim = 20;
  max_missed = 5;
  mismatch_threshold = 0.1;
  test_run = false;
  int c;
  Process process;

  // prevent output to stderr if erroneous option is found
  opterr = 0;

  // get all options that have been provided on the command line
  while (( c = getopt (argc, argv, "hr:c:o:s:l:x:m:i:p:t:a:b:d:e:f:g:z" )) != -1 ) {
    switch( c ) {
      case 'h':
        print_usage( argv[0] );
        exit(0);
        break;
      // max_sort_char option
      case 'm':
        max_sort_char = atoi(optarg);
        break;
      // contig_sub_len option
      case 's':
        contig_sub_len = atoi(optarg);
        break;
      // extend_len option
      case 'x':
        extend_len = atoi(optarg);
        break;
      // max_sort_char option
      case 'l':
        max_search_loops = atoi(optarg);
        break;
      // min_cov_init option
      case 'i':
        min_cov_init = atoi(optarg);
        break;
      // min_overlap option
      case 'p':
        min_overlap = atoi(optarg);
        break;
      // max_threads option
      case 't':
        max_threads = atoi(optarg);
        break;
      // initial_trim option
      case 'd':
        initial_trim = atoi(optarg);
        break;
      // max_missed option
      case 'e':
        max_missed = atoi(optarg);
        break;
      // mismatch_threshold option
      case 'g':
        mismatch_threshold = atof(optarg);
        break;
      // outputfile option
      case 'o':
        cout << "output file: " << optarg << endl;
        process.outfile = optarg;
        print_time();
        break;
      // readfile option
      case 'r':
        optind--;
        // loop through each file
        while ( optind < argc && argv[optind][0] != '-' ) {
          process.readsfiles.append( "," );
          process.readsfiles.append( argv[optind] );
          optind++;
        }
        break;
      // contig file option
      case 'c':
        optind--;
        // loop through each file
        while ( optind < argc && argv[optind][0] != '-' ) {
          process.contigsfiles.append( "," );
          process.contigsfiles.append( argv[optind] );
          optind++;
        }
        break;
      // test_run option
      case 'z':
        test_run = true;
        break;
      case '?':
        if ( optopt == 'r' ){
          fprintf( stderr, "%s: Error: Option -r requires an argument. ", argv[0] );
          print_usage( argv[0] );
        }
        else if ( optopt == 'o' ){
          fprintf( stderr, "%s: Error: Option -o requires an argument. ", argv[0] );
          print_usage( argv[0] );
        }
        else if ( optopt == 'c' ){
          fprintf( stderr, "%s: Error: Option -c requires an argument. ", argv[0] );
          print_usage( argv[0] );
        }
        else if ( isprint( optopt )){
          fprintf( stderr, "%s: Error: Unknown option -%c. \n", argv[0], optopt );
          print_usage( argv[0] );
        }
        else{
          fprintf( stderr, "%s: Error: Unknown option character %x.\n", argv[0], optopt );
          print_usage( argv[0] );
        }
        return 1;
      default:
        abort();
    }
  }

  while ( optind < argc ) {
    cout << argv[optind] << endl;
    optind++;
  }

  /////////////////
  // End Options //
  /////////////////

  ///////////////////////
  // Test Thread Queue //
  ///////////////////////

  // start run
  process.start_run();

  int length[process.contigs.size()];
  for( int i=0; i<process.contigs.size(); i++ ){
    length[i] = process.get_contig(i).length();
  }

  // print out each contig and the number of bp added
  for( int i=0; i<process.contigs.size(); i++ ){
    cout << "Contig[" << i << "]: " << process.get_contig(i) << endl;
    cout << "\tbp added: " << process.get_contig(i).length() - length[i] << endl;
  }

  cout << "exit time: ";
  print_time();

  process.print_to_outfile();

  return 0;
}

//////////////
// END MAIN //
//////////////
<|endoftext|>


<commit_before>/**
 * Application Context of Session Manager
 *
 * Copyright 2013 Thincast Technologies GmbH
 * Copyright 2013 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
 *
 * 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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/crt.h>
#include <winpr/path.h>
#include <winpr/library.h>
#include <winpr/environment.h>

#include <list>
#include <utils/StringHelpers.h>

#include "ApplicationContext.h"

#include <session/TaskSessionTimeout.h>

namespace freerds
{
	namespace sessionmanager
	{
		ApplicationContext::ApplicationContext()
		{
			wLogLayout* layout;
			wLogAppender* appender;

			initPaths();
			configureExecutableSearchPath();

			WLog_Init();

			mWLogRoot = WLog_GetRoot();

			WLog_SetLogAppenderType(mWLogRoot, WLOG_APPENDER_CONSOLE);

			appender = WLog_GetLogAppender(mWLogRoot);
			WLog_ConsoleAppender_SetOutputStream(mWLogRoot, (wLogConsoleAppender*) appender, WLOG_CONSOLE_STDERR);

			layout = WLog_GetLogLayout(mWLogRoot);
			WLog_Layout_SetPrefixFormat(mWLogRoot, layout, "[%lv:%mn] [%fl|%fn|%ln] - ");

			WLog_OpenAppender(mWLogRoot);
			WLog_SetLogLevel(mWLogRoot, WLOG_TRACE);

			setupTestingPropValues();
		}

		ApplicationContext::~ApplicationContext()
		{
			WLog_CloseAppender(mWLogRoot);
			WLog_Uninit();
		}

		std::string ApplicationContext::getHomePath()
		{

			if (mHomePath.size() == 0)
			{
				char* p;
				int length;
				char separator;
				char moduleFileName[4096];

				separator = PathGetSeparatorA(PATH_STYLE_NATIVE);
				GetModuleFileNameA(NULL, moduleFileName, sizeof(moduleFileName));

				p = strrchr(moduleFileName, separator);
				*p = '\0';
				p = strrchr(moduleFileName, separator);
				*p = '\0';

				mHomePath.assign(moduleFileName);
			}
			return mHomePath;
		}

		std::string ApplicationContext::getLibraryPath()
		{
			if (mLibraryPath.size() == 0)
			{
				mLibraryPath = getHomePath();
				mLibraryPath += "/";
				mLibraryPath += FREERDS_INSTALL_LIBDIR;
			}
			return mLibraryPath;
		}

		std::string ApplicationContext::getExecutablePath()
		{
			if (mExecutablePath.size() == 0)
			{
				mExecutablePath = getHomePath();
				mExecutablePath += "/";
				mExecutablePath += FREERDS_INSTALL_BINDIR;
			}
			return mExecutablePath;
		}

		std::string ApplicationContext::getShareDataPath()
		{
			if (mShareDataPath.size() == 0)
			{
				mShareDataPath = getHomePath();
				mShareDataPath += "/";
				mShareDataPath += FREERDS_INSTALL_DATAROOTDIR;
				mShareDataPath += "/";
				mShareDataPath += "freerds";
			}
			return mShareDataPath;
		}

		std::string ApplicationContext::getSystemConfigPath()
		{
			if (mSystemConfigPath.size() == 0)
			{

				mSystemConfigPath = getHomePath();
				mSystemConfigPath += "/";
				mSystemConfigPath += FREERDS_INSTALL_SYSCONFDIR;
				mSystemConfigPath += "/";
				mSystemConfigPath += "freerds";
			}
			return mSystemConfigPath;
		}

		void ApplicationContext::initPaths()
		{
			getHomePath();
			getLibraryPath();
			getExecutablePath();
			getShareDataPath();
			getSystemConfigPath();
		}

		void ApplicationContext::configureExecutableSearchPath()
		{
			int index;
			DWORD nSize;

			nSize = GetEnvironmentVariableA("PATH", NULL, 0);

			if (nSize)
			{
				std::string pathExtra = "";
				bool executablePathPresent = false;
				bool systemConfigPathPresent = false;

				char* lpBuffer = (LPSTR) malloc(nSize);
				nSize = GetEnvironmentVariableA("PATH", lpBuffer, nSize);

				std::string pathEnv(lpBuffer);
				std::vector<std::string> pathList = split<std::string>(pathEnv, ":");

				for (index = 0; index < pathList.size(); index++)
				{
					if (strcmp(mExecutablePath.c_str(), pathList[index].c_str()) == 0)
						executablePathPresent = true;
					else if (strcmp(mSystemConfigPath.c_str(), pathList[index].c_str()) == 0)
						systemConfigPathPresent = true;
				}

				if (!executablePathPresent)
				{
					pathExtra += mExecutablePath;
					pathExtra += ":";
				}

				if (!systemConfigPathPresent)
				{
					pathExtra += mSystemConfigPath;
					pathExtra += ":";
				}

				if (pathExtra.length() > 0)
				{
					pathEnv = pathExtra + pathEnv;
					SetEnvironmentVariableA("PATH", pathEnv.c_str());
				}
			}
		}

		sessionNS::SessionStore* ApplicationContext::getSessionStore()
		{
			return &mSessionStore;
		}

		sessionNS::ConnectionStore* ApplicationContext::getConnectionStore()
		{
			return &mConnectionStore;
		}

		configNS::PropertyManager* ApplicationContext::getPropertyManager()
		{
			return &mPropertyManager;
		}

		int ApplicationContext::startRPCEngine()
		{
#ifdef WITH_FDSAPI
			mFDSApiServer.startFDSApi();
#endif
			return mRpcEngine.startEngine();
		}

		int ApplicationContext::stopRPCEngine()
		{
#ifdef WITH_FDSAPI
			mFDSApiServer.stopFDSApi();
#endif
			return mRpcEngine.stopEngine();
		}

		SignalingQueue<callNS::Call *> * ApplicationContext::getRpcOutgoingQueue()
		{
			return &mRpcOutgoingCalls;
		}

		int ApplicationContext::loadModulesFromPath(std::string path)
		{
			LPCSTR pszExt;
			char pattern[256];

			pszExt = PathGetSharedLibraryExtensionA(0);
			sprintf_s(pattern, 256, "*freerds-module-*.%s", pszExt);

			return mModuleManager.loadModulesFromPathAndEnv(path, pattern);
		}

		moduleNS::ModuleManager* ApplicationContext::getModuleManager()
		{
			return &mModuleManager;
		}

		void ApplicationContext::setupTestingPropValues()
		{

			mPropertyManager.setPropertyString(Global, 0, "module","xsession");
			mPropertyManager.setPropertyString(Global, 0, "auth.module","PAM");
			mPropertyManager.setPropertyString(Global, 0, "auth.greeter","greeter");
			mPropertyManager.setPropertyBool(Global, 0, "session.reconnect",true);
			mPropertyManager.setPropertyNumber(Global, 0, "session.timeout",1);

			mPropertyManager.setPropertyString(Global, 0, "module.xsession.modulename","X11");
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.maxXRes",1920);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.maxYRes",1200);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.minXRes",320);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.minYRes",200);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.xres",1024);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.yres",768);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.colordepth",24);
			mPropertyManager.setPropertyString(Global, 0, "module.xsession.startwm","startwm.sh");

			mPropertyManager.setPropertyString(Global, 0, "module.greeter.modulename","Qt");
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.maxXRes",1920);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.maxYRes",1200);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.minXRes",320);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.minYRes",200);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.xres",1024);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.yres",768);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.colordepth",24);
			mPropertyManager.setPropertyString(Global, 0, "module.greeter.cmd","nice_greeter");

			mPropertyManager.setPropertyNumber(User, 0, "module.xsession.xres",800,"demo1");
			mPropertyManager.setPropertyNumber(User, 0, "module.xsession.yres",600,"demo1");
			mPropertyManager.setPropertyNumber(User, 0, "module.xsession.xres",800,"demo2");
			mPropertyManager.setPropertyNumber(User, 0, "module.xsession.yres",600,"demo2");
			mPropertyManager.setPropertyBool(User, 0, "session.reconnect",false,"demo1");
			mPropertyManager.setPropertyString(User, 0, "module","xsession","demo2");

		}

		void ApplicationContext::startTaskExecutor() {
			mTaskExecutor.start();
		}

		void ApplicationContext::stopTaskExecutor() {
			mTaskExecutor.stop();
		}

		void ApplicationContext::startSessionTimoutMonitor(){
			sessionNS::TaskSessionTimeoutPtr task(new sessionNS::TaskSessionTimeout());
			addTask(task);
		}

		bool ApplicationContext::addTask(taskNS::TaskPtr task) {
			return mTaskExecutor.addTask(task);
		}

		void ApplicationContext::rpcDisconnected() {
			// remove all connections
			getConnectionStore()->reset();
			// iterate over the session and disconnect them if they are auth sessions.
			std::list<sessionNS::SessionPtr> allSessions = getSessionStore()->getAllSessions();

			std::list<sessionNS::SessionPtr>::iterator iterator;
			for (iterator = allSessions.begin(); iterator != allSessions.end(); ++iterator) {
				sessionNS::SessionPtr currentSession = (*iterator);
				if (currentSession->isAuthSession()) {
					currentSession->stopModule();
					getSessionStore()->removeSession(currentSession->getSessionID());
				} else {
					// disconnect the session
					currentSession->setConnectState(WTSDisconnected);
				}
			}
		}

	}
}

<commit_msg>Changed default greeter from Qt/nice_greeter to X11/simple_greeter<commit_after>/**
 * Application Context of Session Manager
 *
 * Copyright 2013 Thincast Technologies GmbH
 * Copyright 2013 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
 *
 * 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.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/crt.h>
#include <winpr/path.h>
#include <winpr/library.h>
#include <winpr/environment.h>

#include <list>
#include <utils/StringHelpers.h>

#include "ApplicationContext.h"

#include <session/TaskSessionTimeout.h>

namespace freerds
{
	namespace sessionmanager
	{
		ApplicationContext::ApplicationContext()
		{
			wLogLayout* layout;
			wLogAppender* appender;

			initPaths();
			configureExecutableSearchPath();

			WLog_Init();

			mWLogRoot = WLog_GetRoot();

			WLog_SetLogAppenderType(mWLogRoot, WLOG_APPENDER_CONSOLE);

			appender = WLog_GetLogAppender(mWLogRoot);
			WLog_ConsoleAppender_SetOutputStream(mWLogRoot, (wLogConsoleAppender*) appender, WLOG_CONSOLE_STDERR);

			layout = WLog_GetLogLayout(mWLogRoot);
			WLog_Layout_SetPrefixFormat(mWLogRoot, layout, "[%lv:%mn] [%fl|%fn|%ln] - ");

			WLog_OpenAppender(mWLogRoot);
			WLog_SetLogLevel(mWLogRoot, WLOG_TRACE);

			setupTestingPropValues();
		}

		ApplicationContext::~ApplicationContext()
		{
			WLog_CloseAppender(mWLogRoot);
			WLog_Uninit();
		}

		std::string ApplicationContext::getHomePath()
		{

			if (mHomePath.size() == 0)
			{
				char* p;
				int length;
				char separator;
				char moduleFileName[4096];

				separator = PathGetSeparatorA(PATH_STYLE_NATIVE);
				GetModuleFileNameA(NULL, moduleFileName, sizeof(moduleFileName));

				p = strrchr(moduleFileName, separator);
				*p = '\0';
				p = strrchr(moduleFileName, separator);
				*p = '\0';

				mHomePath.assign(moduleFileName);
			}
			return mHomePath;
		}

		std::string ApplicationContext::getLibraryPath()
		{
			if (mLibraryPath.size() == 0)
			{
				mLibraryPath = getHomePath();
				mLibraryPath += "/";
				mLibraryPath += FREERDS_INSTALL_LIBDIR;
			}
			return mLibraryPath;
		}

		std::string ApplicationContext::getExecutablePath()
		{
			if (mExecutablePath.size() == 0)
			{
				mExecutablePath = getHomePath();
				mExecutablePath += "/";
				mExecutablePath += FREERDS_INSTALL_BINDIR;
			}
			return mExecutablePath;
		}

		std::string ApplicationContext::getShareDataPath()
		{
			if (mShareDataPath.size() == 0)
			{
				mShareDataPath = getHomePath();
				mShareDataPath += "/";
				mShareDataPath += FREERDS_INSTALL_DATAROOTDIR;
				mShareDataPath += "/";
				mShareDataPath += "freerds";
			}
			return mShareDataPath;
		}

		std::string ApplicationContext::getSystemConfigPath()
		{
			if (mSystemConfigPath.size() == 0)
			{

				mSystemConfigPath = getHomePath();
				mSystemConfigPath += "/";
				mSystemConfigPath += FREERDS_INSTALL_SYSCONFDIR;
				mSystemConfigPath += "/";
				mSystemConfigPath += "freerds";
			}
			return mSystemConfigPath;
		}

		void ApplicationContext::initPaths()
		{
			getHomePath();
			getLibraryPath();
			getExecutablePath();
			getShareDataPath();
			getSystemConfigPath();
		}

		void ApplicationContext::configureExecutableSearchPath()
		{
			int index;
			DWORD nSize;

			nSize = GetEnvironmentVariableA("PATH", NULL, 0);

			if (nSize)
			{
				std::string pathExtra = "";
				bool executablePathPresent = false;
				bool systemConfigPathPresent = false;

				char* lpBuffer = (LPSTR) malloc(nSize);
				nSize = GetEnvironmentVariableA("PATH", lpBuffer, nSize);

				std::string pathEnv(lpBuffer);
				std::vector<std::string> pathList = split<std::string>(pathEnv, ":");

				for (index = 0; index < pathList.size(); index++)
				{
					if (strcmp(mExecutablePath.c_str(), pathList[index].c_str()) == 0)
						executablePathPresent = true;
					else if (strcmp(mSystemConfigPath.c_str(), pathList[index].c_str()) == 0)
						systemConfigPathPresent = true;
				}

				if (!executablePathPresent)
				{
					pathExtra += mExecutablePath;
					pathExtra += ":";
				}

				if (!systemConfigPathPresent)
				{
					pathExtra += mSystemConfigPath;
					pathExtra += ":";
				}

				if (pathExtra.length() > 0)
				{
					pathEnv = pathExtra + pathEnv;
					SetEnvironmentVariableA("PATH", pathEnv.c_str());
				}
			}
		}

		sessionNS::SessionStore* ApplicationContext::getSessionStore()
		{
			return &mSessionStore;
		}

		sessionNS::ConnectionStore* ApplicationContext::getConnectionStore()
		{
			return &mConnectionStore;
		}

		configNS::PropertyManager* ApplicationContext::getPropertyManager()
		{
			return &mPropertyManager;
		}

		int ApplicationContext::startRPCEngine()
		{
#ifdef WITH_FDSAPI
			mFDSApiServer.startFDSApi();
#endif
			return mRpcEngine.startEngine();
		}

		int ApplicationContext::stopRPCEngine()
		{
#ifdef WITH_FDSAPI
			mFDSApiServer.stopFDSApi();
#endif
			return mRpcEngine.stopEngine();
		}

		SignalingQueue<callNS::Call *> * ApplicationContext::getRpcOutgoingQueue()
		{
			return &mRpcOutgoingCalls;
		}

		int ApplicationContext::loadModulesFromPath(std::string path)
		{
			LPCSTR pszExt;
			char pattern[256];

			pszExt = PathGetSharedLibraryExtensionA(0);
			sprintf_s(pattern, 256, "*freerds-module-*.%s", pszExt);

			return mModuleManager.loadModulesFromPathAndEnv(path, pattern);
		}

		moduleNS::ModuleManager* ApplicationContext::getModuleManager()
		{
			return &mModuleManager;
		}

		void ApplicationContext::setupTestingPropValues()
		{

			mPropertyManager.setPropertyString(Global, 0, "module","xsession");
			mPropertyManager.setPropertyString(Global, 0, "auth.module","PAM");
			mPropertyManager.setPropertyString(Global, 0, "auth.greeter","greeter");
			mPropertyManager.setPropertyBool(Global, 0, "session.reconnect",true);
			mPropertyManager.setPropertyNumber(Global, 0, "session.timeout",1);

			mPropertyManager.setPropertyString(Global, 0, "module.xsession.modulename","X11");
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.maxXRes",1920);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.maxYRes",1200);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.minXRes",320);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.minYRes",200);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.xres",1024);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.yres",768);
			mPropertyManager.setPropertyNumber(Global, 0, "module.xsession.colordepth",24);
			mPropertyManager.setPropertyString(Global, 0, "module.xsession.startwm","startwm.sh");

			mPropertyManager.setPropertyString(Global, 0, "module.greeter.modulename","X11");
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.maxXRes",1920);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.maxYRes",1200);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.minXRes",320);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.minYRes",200);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.xres",1024);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.yres",768);
			mPropertyManager.setPropertyNumber(Global, 0, "module.greeter.colordepth",24);
			mPropertyManager.setPropertyString(Global, 0, "module.greeter.cmd","simple_greeter");

			mPropertyManager.setPropertyNumber(User, 0, "module.xsession.xres",800,"demo1");
			mPropertyManager.setPropertyNumber(User, 0, "module.xsession.yres",600,"demo1");
			mPropertyManager.setPropertyNumber(User, 0, "module.xsession.xres",800,"demo2");
			mPropertyManager.setPropertyNumber(User, 0, "module.xsession.yres",600,"demo2");
			mPropertyManager.setPropertyBool(User, 0, "session.reconnect",false,"demo1");
			mPropertyManager.setPropertyString(User, 0, "module","xsession","demo2");

		}

		void ApplicationContext::startTaskExecutor() {
			mTaskExecutor.start();
		}

		void ApplicationContext::stopTaskExecutor() {
			mTaskExecutor.stop();
		}

		void ApplicationContext::startSessionTimoutMonitor(){
			sessionNS::TaskSessionTimeoutPtr task(new sessionNS::TaskSessionTimeout());
			addTask(task);
		}

		bool ApplicationContext::addTask(taskNS::TaskPtr task) {
			return mTaskExecutor.addTask(task);
		}

		void ApplicationContext::rpcDisconnected() {
			// remove all connections
			getConnectionStore()->reset();
			// iterate over the session and disconnect them if they are auth sessions.
			std::list<sessionNS::SessionPtr> allSessions = getSessionStore()->getAllSessions();

			std::list<sessionNS::SessionPtr>::iterator iterator;
			for (iterator = allSessions.begin(); iterator != allSessions.end(); ++iterator) {
				sessionNS::SessionPtr currentSession = (*iterator);
				if (currentSession->isAuthSession()) {
					currentSession->stopModule();
					getSessionStore()->removeSession(currentSession->getSessionID());
				} else {
					// disconnect the session
					currentSession->setConnectState(WTSDisconnected);
				}
			}
		}

	}
}

<|endoftext|>


<commit_before>#ifdef STAN_OPENCL

#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/copy.hpp>
#include <test/unit/util.hpp>
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include <CL/cl2.hpp>
#include <exception>

using Eigen::MatrixXd;
using Eigen::MatrixXi;
using stan::math::matrix_cl;

TEST(KernelGenerator, operation_cl_errors) {
  EXPECT_THROW(matrix_cl<double> a = stan::math::as_operation_cl(3.5),
               std::invalid_argument);
  EXPECT_THROW(stan::math::as_operation_cl(3.5).eval(), std::invalid_argument);
}

TEST(KernelGenerator, kernel_caching) {
  MatrixXd m1(3, 3);
  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  MatrixXd m2(3, 3);
  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;

  matrix_cl<double> m1_cl(m1);
  matrix_cl<double> m2_cl(m2);
  auto tmp = m1_cl + 0.1234 * m2_cl;

  using cache = stan::math::internal::multi_result_kernel_internal<
      0, stan::math::load_<matrix_cl<double>&>&&>::inner<const decltype(tmp)&>;
  using unused_cache = stan::math::internal::multi_result_kernel_internal<
      0, stan::math::load_<matrix_cl<int>&>&&>::inner<const decltype(tmp)&>;
  size_t cache_size = cache::kernel_cache_.size();
  size_t unused_cache_size = unused_cache::kernel_cache_.size();
  std::vector<int> uid = {0, 1, 2};

  EXPECT_EQ(cache::kernel_cache_.count(uid), 0);
  EXPECT_EQ(cache::kernel_cache_.size(), cache_size);
  matrix_cl<double> res_cl = tmp;
  EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);
  cl_kernel cached_kernel = cache::kernel_cache_.at(uid)();
  EXPECT_NE(cached_kernel, nullptr);

  auto tmp2 = m1_cl + 0.1234 * m2_cl;
  matrix_cl<double> res2_cl = tmp2;
  EXPECT_EQ(cache::kernel_cache_.at(uid)(), cached_kernel);
  EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);

  matrix_cl<double> res3_cl = res_cl + 0.1234 * res2_cl;
  EXPECT_EQ(cache::kernel_cache_.at(uid)(), cached_kernel);
  EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);

  EXPECT_EQ(unused_cache::kernel_cache_.size(), unused_cache_size);
}

TEST(MathMatrixCL, events_write_after_write) {
  using stan::math::matrix_cl;
  matrix_cl<double> zero_cl = stan::math::constant(0, 3, 3);
  zero_cl.wait_for_read_write_events();

  for (int j = 0; j < 3000; j++) {
    matrix_cl<double> m_cl(3, 3);

    for (int i = 0; i < 4; i++) {
      m_cl = zero_cl + i;
    }

    Eigen::MatrixXd res = stan::math::from_matrix_cl(m_cl);
    Eigen::MatrixXd correct = Eigen::MatrixXd::Constant(3, 3, 3);

    EXPECT_MATRIX_NEAR(res, correct, 1e-13);
  }
}

TEST(MathMatrixCL, events_read_after_write_and_write_after_read) {
  using stan::math::matrix_cl;
  int iters = 3000;

  matrix_cl<double> m1_cl = stan::math::constant(0, 3, 3);
  matrix_cl<double> m2_cl(3, 3);

  for (int j = 0; j < iters; j++) {
    m2_cl = m1_cl + 1;
    m1_cl = m2_cl + 1;
  }
  Eigen::MatrixXd res = stan::math::from_matrix_cl(m1_cl);
  Eigen::MatrixXd correct = Eigen::MatrixXd::Constant(3, 3, 2 * iters);

  EXPECT_MATRIX_NEAR(res, correct, 1e-13);
}

TEST(MathMatrixCL, same_operations_different_inputs) {
  MatrixXd m1(3, 3);
  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  MatrixXd m2(3, 3);
  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;

  matrix_cl<double> m1_cl(m1);
  matrix_cl<double> m2_cl(m2);

  auto m1_op = stan::math::as_operation_cl(m1_cl);
  auto m2_op = stan::math::as_operation_cl(m2_cl);

  matrix_cl<double> res1_cl = m1_op + m1_op;
  matrix_cl<double> res2_cl = m2_op + m1_op;

  EXPECT_MATRIX_EQ(stan::math::from_matrix_cl(res1_cl), m1 + m1);
  EXPECT_MATRIX_EQ(stan::math::from_matrix_cl(res2_cl), m2 + m1);
}

#endif
<commit_msg>fix cache test<commit_after>#ifdef STAN_OPENCL

#include <stan/math/opencl/kernel_generator.hpp>
#include <stan/math/opencl/matrix_cl.hpp>
#include <stan/math/opencl/copy.hpp>
#include <test/unit/util.hpp>
#include <Eigen/Dense>
#include <gtest/gtest.h>
#include <CL/cl2.hpp>
#include <exception>

using Eigen::MatrixXd;
using Eigen::MatrixXi;
using stan::math::matrix_cl;

TEST(KernelGenerator, operation_cl_errors) {
  EXPECT_THROW(matrix_cl<double> a = stan::math::as_operation_cl(3.5),
               std::invalid_argument);
  EXPECT_THROW(stan::math::as_operation_cl(3.5).eval(), std::invalid_argument);
}

TEST(KernelGenerator, kernel_caching) {
  MatrixXd m1(3, 3);
  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  MatrixXd m2(3, 3);
  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;

  matrix_cl<double> m1_cl(m1);
  matrix_cl<double> m2_cl(m2);
  auto tmp = m1_cl + 0.1234 * m2_cl;

  using cache = stan::math::internal::multi_result_kernel_internal<
      0, stan::math::load_<matrix_cl<double>&>>::inner<const decltype(tmp)&>;
  using unused_cache = stan::math::internal::multi_result_kernel_internal<
      0, stan::math::load_<matrix_cl<int>&>>::inner<const decltype(tmp)&>;
  size_t cache_size = cache::kernel_cache_.size();
  size_t unused_cache_size = unused_cache::kernel_cache_.size();
  std::vector<int> uid = {0, 1, 2};

  EXPECT_EQ(cache::kernel_cache_.count(uid), 0);
  EXPECT_EQ(cache::kernel_cache_.size(), cache_size);
  matrix_cl<double> res_cl = tmp;
  EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);
  cl_kernel cached_kernel = cache::kernel_cache_.at(uid)();
  EXPECT_NE(cached_kernel, nullptr);

  auto tmp2 = m1_cl + 0.1234 * m2_cl;
  matrix_cl<double> res2_cl = tmp2;
  EXPECT_EQ(cache::kernel_cache_.at(uid)(), cached_kernel);
  EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);

  matrix_cl<double> res3_cl = res_cl + 0.1234 * res2_cl;
  EXPECT_EQ(cache::kernel_cache_.at(uid)(), cached_kernel);
  EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);

  EXPECT_EQ(unused_cache::kernel_cache_.size(), unused_cache_size);
}

TEST(MathMatrixCL, events_write_after_write) {
  using stan::math::matrix_cl;
  matrix_cl<double> zero_cl = stan::math::constant(0, 3, 3);
  zero_cl.wait_for_read_write_events();

  for (int j = 0; j < 3000; j++) {
    matrix_cl<double> m_cl(3, 3);

    for (int i = 0; i < 4; i++) {
      m_cl = zero_cl + i;
    }

    Eigen::MatrixXd res = stan::math::from_matrix_cl(m_cl);
    Eigen::MatrixXd correct = Eigen::MatrixXd::Constant(3, 3, 3);

    EXPECT_MATRIX_NEAR(res, correct, 1e-13);
  }
}

TEST(MathMatrixCL, events_read_after_write_and_write_after_read) {
  using stan::math::matrix_cl;
  int iters = 3000;

  matrix_cl<double> m1_cl = stan::math::constant(0, 3, 3);
  matrix_cl<double> m2_cl(3, 3);

  for (int j = 0; j < iters; j++) {
    m2_cl = m1_cl + 1;
    m1_cl = m2_cl + 1;
  }
  Eigen::MatrixXd res = stan::math::from_matrix_cl(m1_cl);
  Eigen::MatrixXd correct = Eigen::MatrixXd::Constant(3, 3, 2 * iters);

  EXPECT_MATRIX_NEAR(res, correct, 1e-13);
}

TEST(MathMatrixCL, same_operations_different_inputs) {
  MatrixXd m1(3, 3);
  m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  MatrixXd m2(3, 3);
  m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;

  matrix_cl<double> m1_cl(m1);
  matrix_cl<double> m2_cl(m2);

  auto m1_op = stan::math::as_operation_cl(m1_cl);
  auto m2_op = stan::math::as_operation_cl(m2_cl);

  matrix_cl<double> res1_cl = m1_op + m1_op;
  matrix_cl<double> res2_cl = m2_op + m1_op;

  EXPECT_MATRIX_EQ(stan::math::from_matrix_cl(res1_cl), m1 + m1);
  EXPECT_MATRIX_EQ(stan::math::from_matrix_cl(res2_cl), m2 + m1);
}

#endif
<|endoftext|>