Example #1
0
 std::ostream& operator<<(std::ostream& os, const TimestampedReward& tsf)
 {
     os << "TimestampedReward: " << to_simple_string(tsf.timestamp);
     for( std::map<int,double>::const_iterator it = tsf.values.begin(); it!= tsf.values.end(); it++) {
         os  << ", " << it->first << ":" << it->second;
     }
     return os;
 }
Example #2
0
/**
 * \brief Function to return the difference between localtime and UTC time (seconds)
 * \return the difference time (seconds)
 */
long vishnu::diffLocaltimeUTCtime() {

  //the current time
  boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

  time_t currentTime = string_to_time_t(to_simple_string(now));

  long diff = currentTime-std::time(0);
  return diff;
}
Example #3
0
/**
 * \brief Function to localtime into UTC (seconds)
 * \return the diffence time (seconds)
 */
time_t vishnu::convertLocaltimeINUTCtime(const time_t& localtime) {

  //the current time
  boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

  time_t currentTime = string_to_time_t(to_simple_string(now));

  long diff = currentTime-std::time(0);
  return (localtime-diff);
}
Example #4
0
void TestStockTime::test1()
{

  date d(2002,Feb,1); //an arbitrary date

  //construct a time by adding up some durations durations
  StockTime t1(d, hours(5)+minutes(4)+seconds(2)+millisec(1));

  //construct a new time by subtracting some times
  StockTime t2 = t1 - hours(5)- minutes(4)- seconds(2)- millisec(1);

  //construct a duration by taking the difference between times
  time_duration td = t2 - t1;
    
  std::cout << to_simple_string(t2) << " - " 
         << to_simple_string(t1) << " = "
         << to_simple_string(td) << std::endl;

}
Example #5
0
bool TestLogger::log(const std::string& logName, const lib_module::LogSeverity severity, const std::string logMessage) const{

  boost::posix_time::ptime t = boost::posix_time::microsec_clock::local_time();
  std::string logTime = to_simple_string(t);

  std::cout << "[" << logTime << "]" << "[" << test_logger::sevTypes[severity] << "]" << "[" << logName << "]"
    << logMessage << std::endl;

  return true;
}
//logging function to write error message to file
void StorageConverter::logErrorMessage(string errorMessage){
	if(LOGGING_MODE_ON == true){
		ofstream writeToLogFile;
		string currentTime = to_simple_string(second_clock::local_time());
		writeToLogFile.open(LOG_FILE_NAME, ios::app);
		writeToLogFile << currentTime << endl << errorMessage << endl;
		writeToLogFile << endl;
		writeToLogFile.close();
	} 
	return;
}
 /*!\ingroup time_format
  */
 inline
 std::string
 to_iso_extended_string(ptime t)
 {
   std::string ts = gregorian::to_iso_extended_string(t.date());// + "T";
   if(!t.time_of_day().is_special()) {
     return ts + "T" + to_simple_string(t.time_of_day());
   }
   else {
     return ts;
   }
 }
Example #8
0
void MainWindow::displaySwingAddOrderHistory(TradeItem *tradeItem)
{
    QStandardItem* item1 = new QStandardItem(QString("%0").arg(tradeItem->getOrderRefId()));
    QStandardItem* item2 = new QStandardItem(QString(tradeItem->getQuoteId().c_str()));
    QStandardItem* item3 = new QStandardItem(QString(to_simple_string(tradeItem->getTradeTime()).c_str()));
    QStandardItem* item4 = new QStandardItem(QString("%0").arg(tradeItem->getBuySell()));
    QStandardItem* item5 = new QStandardItem(QString("%0").arg(tradeItem->getTradePrice()));
    QStandardItem* item6 = new QStandardItem(QString("%0").arg(tradeItem->getQty()));
    QStandardItem* item7 = new QStandardItem(QString("%0").arg(tradeItem->getStatus()));
    QList<QStandardItem *> data;
    data << item1 << item2 << item3 << item4 << item5 << item6 << item7;
    swingorderhistorymodel_->insertRow(0, data);
}
Example #9
0
	void Account::InitFliterConfig(const std::string& aFliterConfig)
	{
		boost::property_tree::ptree lpt;
		read_xml(aFliterConfig,lpt);

		FliterStruct fliter;
		int iID;
		int iTime;
		std::string strStopTime;
		std::string strStartTime;

		m_FilterSetting.Time1 = lpt.get<int>("Time1");
		m_FilterSetting.Time2 = lpt.get<int>("Time2");
		m_FilterSetting.Time3 = lpt.get<int>("Time3");
		iTime = lpt.get<int>("TotalTimeProfit.Time");
		m_FilterSetting.TotalTimeProfit[iTime] = lpt.get<int>("TotalTimeProfit.Profit");
		m_FilterSetting.TotalProfitStop = lpt.get<int>("TotalProfitStop");
		strStopTime = to_simple_string(boost::gregorian::day_clock::local_day())+" "+lpt.get<std::string>("SignalFliter.Item.StopTime");
		m_FilterSetting.StopTime = boost::posix_time::time_from_string(strStopTime);
		strStartTime = to_simple_string(boost::gregorian::day_clock::local_day())+" "+lpt.get<std::string>("SignalFliter.Item.StartTime");
		m_FilterSetting.StartTime = boost::posix_time::time_from_string(strStartTime);
	}
Example #10
0
         void logTextview::writeLog(std::string const& _s)
         {
            // Add a timestamp.
            boost::posix_time::ptime t(boost::posix_time::second_clock::local_time());
            std::string timestamp = to_simple_string(t);

            // Add the string.
            Glib::ustring us("[" + timestamp + "] " + _s + "\n");
            Gtk::TextIter iter = get_buffer()->end();
            get_buffer()->insert(iter, us);

            // Scroll to the end of the buffer.
            scroll_to_mark(get_buffer()->create_mark("end", get_buffer()->end()), 0.0);
         }
Example #11
0
int main()
{
	
	std::cout << "Hello world!" << std::endl;
	while (true)
	{
		ptime now = second_clock::local_time();
		date today = now.date();
		std::cout << to_simple_string(now) << std::endl;
		std::cout << to_iso_string(now) << std::endl;
		
	}
	
	return 0;
}
void TestSupportLibrary::compareTasks(Task firstTask, Task secondTask) {
	Assert::AreEqual(firstTask.getTaskName(), secondTask.getTaskName());
	Assert::AreEqual(firstTask.getTaskIsDone(), secondTask.getTaskIsDone());
	compareTaskTags(firstTask.getTaskTags(), secondTask.getTaskTags());
	Assert::AreEqual(to_simple_string(firstTask.getTaskStartTime()), 
		to_simple_string(secondTask.getTaskStartTime()));
	Assert::AreEqual(to_simple_string(firstTask.getTaskEndTime()), 
		to_simple_string(secondTask.getTaskEndTime()));
	Assert::AreEqual(to_simple_string(firstTask.getTaskDeadline()), 
		to_simple_string(secondTask.getTaskDeadline()));
	return;
}
Example #13
0
Mask::Mask(int timeInterval, bool customMask, string customMaskPath, bool downsampleMask, CamPixFmt format, bool updateMask):
mUpdateInterval(timeInterval), mUpdateMask(updateMask) {

    mMaskToCreate = false;
    updateStatus = false;
    refDate = to_simple_string(boost::posix_time::second_clock::universal_time());
    satMap = boost::circular_buffer<Mat>(2);

    // Load a mask from file.
    if(customMask) {

        mOriginalMask = imread(customMaskPath, CV_LOAD_IMAGE_GRAYSCALE);
        SaveImg::saveJPEG(mOriginalMask, "/home/fripon/mOriginalMask");
        if(!mOriginalMask.data)
            throw "Fail to load the mask from its path.";

        if(downsampleMask)
            pyrDown(mOriginalMask, mOriginalMask, Size(mOriginalMask.cols/2, mOriginalMask.rows/2));

        mOriginalMask.copyTo(mCurrentMask);

    }else{

        mMaskToCreate = true;

    }

    // Estimate saturated value.
    switch(format) {

        case MONO12 :

                saturatedValue = 4092;

            break;

        default :

                saturatedValue = 254;

    }

}
Example #14
0
void MainWindow::displaySwingAddPositions(Position *position)
{
    QStandardItem *data = new QStandardItem(QString(position->getQuoteId().c_str()));
    list<TradeItem *> tradeList = position->getTradeList();
    for(list<TradeItem *>::const_iterator it = tradeList.begin(); it != tradeList.end(); ++it)
    {
        QStandardItem* item1 = new QStandardItem(QString("%0").arg((*it)->getOrderRefId()));
        QStandardItem* item2 = new QStandardItem(QString((*it)->getQuoteId().c_str()));
        QStandardItem* item3 = new QStandardItem(QString(to_simple_string((*it)->getTradeTime()).c_str()));
        QStandardItem* item4 = new QStandardItem(QString("%0").arg((*it)->getBuySell()));
        QStandardItem* item5 = new QStandardItem(QString("%0").arg((*it)->getTradePrice()));
        QStandardItem* item6 = new QStandardItem(QString("%0").arg((*it)->getQty()));
        QStandardItem* item7 = new QStandardItem(QString("%0").arg((*it)->getStatus()));
        QList<QStandardItem *> child;
        child << item1 << item2 << item3 << item4 << item5 << item6 << item7;
        data->appendRow(child);
    }
    swingpositionsmodel_->insertRow(0, data);
}
		void ReservationConfirmationEMailSubjectInterfacePage::display(
			std::ostream& stream,
			const ReservationTransaction& resa,
			VariablesMap& variables,
			const server::Request* request /*= NULL*/
		) const	{
			ParametersVector pv;
			pv.push_back(to_simple_string((*resa.getReservations().begin())->getDepartureTime().date())); // 0
			pv.push_back((*resa.getReservations().begin())->getDeparturePlaceName()); // 1
			pv.push_back((*resa.getReservations().rbegin())->getArrivalPlaceName()); // 2


			InterfacePage::_display(
				stream
				, pv
				, variables
				, static_cast<const void*>(&resa)
				, request
			);
		}
void save(Archive & ar, 
          const posix_time::time_duration& td, 
          unsigned int version)
{
  // serialize a bool so we know how to read this back in later
  bool is_special = td.is_special();
  ar & make_nvp("is_special", is_special);
  if(is_special) {
    std::string s = to_simple_string(td);
    ar & make_nvp("sv_time_duration", s);
  }
  else {
    // Write support for earlier versions allows for upgrade compatibility testing
    // See load comments for version information
    if (version == 0) {
        save_td<int32_t>(ar, td);
    } else {
        save_td<int64_t>(ar, td);
    }
  }
}
void save(Archive & ar, 
          const posix_time::time_duration& td, 
          unsigned int /*version*/)
{
  // serialize a bool so we know how to read this back in later
  bool is_special = td.is_special();
  ar & make_nvp("is_special", is_special);
  if(is_special) {
    std::string s = to_simple_string(td);
    ar & make_nvp("sv_time_duration", s);
  }
  else {
    typename posix_time::time_duration::hour_type h = td.hours();
    typename posix_time::time_duration::min_type m = td.minutes();
    typename posix_time::time_duration::sec_type s = td.seconds();
    typename posix_time::time_duration::fractional_seconds_type fs = td.fractional_seconds();
    ar & make_nvp("time_duration_hours", h);
    ar & make_nvp("time_duration_minutes", m);
    ar & make_nvp("time_duration_seconds", s);
    ar & make_nvp("time_duration_fractional_seconds", fs);
  }
}
Example #18
0
  //! Converts a date to a tm struct. Throws out_of_range exception if date is a special value
  inline
  std::tm to_tm(const date& d) 
  {
    if(d.is_pos_infinity() || d.is_neg_infinity() || d.is_not_a_date()){
#if defined(USE_DATE_TIME_PRE_1_33_FACET_IO)
      std::string s("tm unable to handle date value of " + to_simple_string(d));
      throw std::out_of_range(s);
#else
      std::stringstream ss;
      ss << "tm unable to handle date value of " << d;
      throw std::out_of_range(ss.str());
#endif // USE_DATE_TIME_PRE_1_33_FACET_IO
    }
    std::tm datetm;
    boost::gregorian::date::ymd_type ymd = d.year_month_day();
    datetm.tm_year = ymd.year-1900; 
    datetm.tm_mon = ymd.month-1; 
    datetm.tm_mday = ymd.day;
    datetm.tm_wday = d.day_of_week();
    datetm.tm_yday = d.day_of_year()-1;
    datetm.tm_hour = datetm.tm_min = datetm.tm_sec = 0;
    datetm.tm_isdst = -1; // negative because not enough info to set tm_isdst
    return datetm;
  }
Example #19
0
void BoostDateTimeTestCase::test_gregorian_lastDayOftheMonths()
{
    // get a month and a year from the user

    boost::gregorian::greg_year year(2000);
    boost::gregorian::greg_month month(1);

    try 
    {
        int y(2022), m(11);

        year = boost::gregorian::greg_year(y);
        month = boost::gregorian::greg_month(m);
    }
    catch(boost::gregorian::bad_year by) 
    {
        std::cout << "Invalid Year Entered: " << by.what() << '\n'
            << "Using minimum values for month and year." << std::endl;
    }
    catch(boost::gregorian::bad_month bm) 
    {
        std::cout << "Invalid Month Entered" << bm.what() << '\n'
            << "Using minimum value for month. " << std::endl;
    }

    boost::gregorian::date start_of_next_year(year + 1, boost::gregorian::Jan, 1);
    boost::gregorian::date d(year, month, 1);

    // add another month to d until we enter the next year.
    while(d < start_of_next_year)
    {
        std::cout << to_simple_string(d.end_of_month()) << std::endl;
        d += boost::gregorian::months(1);
    }

}
Example #20
0
WLogEntry& WLogEntry::operator<< (const WLogger::TimeStamp&)
{
  std::string dt = to_simple_string(microsec_clock::local_time());

  return *this << '[' << dt << ']';
}
Example #21
0
 std::ostream& operator<<(std::ostream& os, const TimestampedString& tss)
 {
     os << "TimestampedString: " << to_simple_string(tss.timestamp) << ", " << tss.text;
     return os;
 }
Example #22
0
		void DBLogPurgeAction::run(Request& request)
		{
			// Action
			DBLogEntryTableSync::Purge(_dbLog->getFactoryKey(), _endDate);

			// Log
			DBLog::AddSimpleEntry(_dbLog->getFactoryKey(), DBLogEntry::DB_LOG_INFO, "Log purge -> " + to_simple_string(_endDate), request.getUser().get());
		}
Example #23
0
void 
book_manager::run() {
    try {
        zmq::socket_t receiver(*_context, ZMQ_SUB); 
        const char* filter = "";
        receiver.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));
        receiver.bind(_connectAddr.c_str());
        fprintf(stdout, "book_manager: connect address: %s\n", _connectAddr.c_str());
        fprintf(stdout, "book_manager: stop requested: %d\n", _stopRequested);

        capkproto::instrument_bbo bbo;
        while (1 && _stopRequested == false) {
            // Extract the message from protobufs
            zmq::message_t msg;
            receiver.recv(&msg);
            bbo.ParseFromArray(msg.data(), msg.size());
            //char mic[MIC_LEN];
            //STRCPY5(mic, bbo.mic());
            capk::venue_id_t bid_venue_id = bbo.bid_venue_id();
            capk::venue_id_t ask_venue_id = bbo.ask_venue_id();
#ifdef DEBUG
            fprintf(stderr, "BID VENUE_ID: %d ASK VENUE_ID: %d", bid_venue_id, ask_venue_id);
#endif
            char sym[SYMBOL_LEN];
            STRCPY8(sym, bbo.symbol());
            double bid_size = bbo.bid_size();
            double ask_size = bbo.ask_size();
            double bid_price = bbo.bid_price();
            double ask_price = bbo.ask_price();
#ifdef DEBUG
            boost::posix_time::ptime time_start(boost::posix_time::microsec_clock::local_time());
#endif

            bool found_symbol = false;
            bool found_venue = false;

            // Add the price to the correct orderbook
            // That is, receive an update for a SINGLE symbol on a SINGLE mic
            // so just blindly update it in the book 
            for (unsigned int i = 0; i < SYMBOL_COUNT; i++) {
                if (strncmp(sym, instruments[i].symbol, SYMBOL_LEN) == 0) {
                    found_symbol = true;
                    for (unsigned int j = 0; j < VENUE_COUNT; j++) {
                        // update the specific book that the price came from
                        if (instruments[i].venues[j].venue_id != capk::kNULL_VENUE_ID && 
                            instruments[i].venues[j].venue_id == bid_venue_id &&                                instruments[i].venues[j].venue_id == ask_venue_id) {
                                found_venue = true;
                                instruments[i].venues[j].bid_price = bid_price; 
                                instruments[i].venues[j].ask_price = ask_price; 
                                instruments[i].venues[j].bid_size = bid_size; 
                                instruments[i].venues[j].ask_size = ask_size; 
                                clock_gettime(CLOCK_MONOTONIC, &instruments[i].venues[j].last_update);
                                break;
                        }
                    }
                } 
            }

            if (!found_symbol) {
                std::cerr << "No matching symbol(book_manager): " << sym << "\n";
            }
            if (!found_venue) {
                std::cerr << "No matching venue(book_manager): BID(" 
                                                               << bid_venue_id 
                                                               << ") ASK(" 
                                                               << ask_venue_id 
                                                               << ")" << "\n";
            }
			
			// Now go through all the books and pick the bbo
            // check the time since last update and reset if too long
            double bb = INT_MIN;
            double ba = INT_MAX;
            //char* bbmic = 0;
            //char* bamic = 0;
            double bbvol = 0;
            double bavol = 0;
            capk::venue_id_t bb_venue_id = capk::kNULL_VENUE_ID;
            capk::venue_id_t ba_venue_id = capk::kNULL_VENUE_ID;
            timespec now;
            std::string msg_str;
			unsigned long last_update_millis;

			// find the symbol and mic in the book structure
            for (unsigned int i = 0; i < SYMBOL_COUNT; i++) {
                if (strncmp(sym, instruments[i].symbol, SYMBOL_LEN) == 0) {
                    found_symbol = true;

                    for (unsigned int j = 0; j < VENUE_COUNT; j++) {
                        if(instruments[i].venues[j].venue_id != capk::kNULL_VENUE_ID) {
                            // check the elapsed time since last update
                            clock_gettime(CLOCK_MONOTONIC, &now);
                            last_update_millis = 
                                capk::timespec_delta_millis(instruments[i].venues[j].last_update, now);
                            // was the item ever updated? 
                            /*
							if (isZeroTimespec(instruments[i].mics[j].last_update)) {
								    fprintf(stderr, "<%s:%s>: NEVER UPDATED\n", 
                                        instruments[i].mics[j].MIC_name,
                                        instruments[i].symbol);
							}
							*/
							fprintf(stderr, "<%d:%s>: %f@%f (last update: %lu ms)", 
									instruments[i].venues[j].venue_id,
									instruments[i].symbol,
									instruments[i].venues[j].bid_price, 
									instruments[i].venues[j].ask_price, 
									last_update_millis);
							if (last_update_millis > UPDATE_TIMEOUT_MILLIS) { 
								fprintf(stderr, "*** TIMEOUT ****");
								instrument_reset(instruments[i].venues[j]);
							}
							fprintf(stderr, "\n");
#ifdef DEBUG
							std::cerr << "Last update: " << instruments[i].venues[j].last_update << std::endl;
							std::cerr << "Now        : " << now << std::endl;
                            timespec tdelta = 
                                capk::timespec_delta(instruments[i].venues[j].last_update, now);
							std::cerr << "Tdelta     : " << tdelta << std::endl;
                            fprintf(stderr, "<%s:%s>: ms since last update: %lu\n", 
                                    instruments[i].symbol, 
                                    capk::venue_id_to_mic_string(instruments[i].venues[j].venue_id), 
									last_update_millis);
							fprintf(stderr, "<%s:%s>: %f@%f\n", 
									capk::venue_id_to_mic_string(instruments[i].venues[j].venue_id),
									instruments[i].symbol,
									instruments[i].venues[j].bid_price, 
									instruments[i].venues[j].ask_price);
#endif 
						}
                        
						if (instruments[i].venues[j].bid_price > bb) {
							bb = instruments[i].venues[j].bid_price;
							bb_venue_id = instruments[i].venues[j].venue_id;	
							bbvol = instruments[i].venues[j].bid_size; 
						} 
						if (instruments[i].venues[j].ask_price < ba) {
							ba = instruments[i].venues[j].ask_price;
							ba_venue_id = instruments[i].venues[j].venue_id;
							bavol = instruments[i].venues[j].ask_size; 
						} 
					}
				}
			}
            
            // Setup BBO and re-broadcast
            fprintf(stderr, "\n***\n<%s> BB: %d:%f-%f BA: %d:%f-%f\n***\n", 
                    sym, 
                    bb_venue_id, 
                    bb, 
                    bbvol, 
                    ba_venue_id, 
                    ba, 
                    bavol);

            capkproto::instrument_bbo ins_bbo;

            ins_bbo.set_symbol(sym);

            ins_bbo.set_bid_venue_id(bb_venue_id);
            ins_bbo.set_bid_price(bb);
            ins_bbo.set_bid_size(bbvol);

            ins_bbo.set_ask_venue_id(ba_venue_id);
            ins_bbo.set_ask_price(ba);
            ins_bbo.set_ask_size(bavol); 

            int msgsize = bbo.ByteSize();
            if (msgsize > MSGBUF_SIZ) {
                fprintf(stderr, "**\nins_bbo msg too large for buffer - DROPPING MSG!\n***");
                //s_send(*bcast_sock, "ERR");
                continue;
            }
            else {
                ins_bbo.SerializeToString(&msg_str);
#ifdef DEBUG 
                fprintf(stderr, "Sending %d bytes\n", msgsize);
                fprintf(stderr, "Sending %s \n", ins_bbo.DebugString().c_str());
#endif
            }

			s_sendmore(*bcast_sock, sym);
			s_send(*bcast_sock, msg_str);
#ifdef DEBUG 
            boost::posix_time::ptime time_end(boost::posix_time::microsec_clock::local_time());
            boost::posix_time::time_duration duration(time_end - time_start);
            fprintf(stderr, "BookUpdate Time(us) to recv and parse: %s\n", to_simple_string(duration).c_str());
#endif
        }
    }
    catch (std::exception& e) {
        std::cerr << "EXCEPTION: " << __FILE__ << __LINE__ << e.what();
    }
}
int main(int argc, char ** argv) {
    if (argc < 2) {
        std::cout << "ps7a [input file]" << std::endl;
        return -1;
    }

    std::ifstream inputfile(argv[1]);  ///< Opens input file based on argv[1]
    if (!inputfile) {
        std::cout << "Could not open " << argv[1] << std::endl;
        return -1;
    }

    std::ofstream outputfile;  ///< Opens output file based on argv[1] w/ .rpt
    std::string outputfilename = argv[1];
    outputfilename += ".rpt";
    outputfile.open(outputfilename.c_str());
    if (!outputfile) {
        std::cout << "Could not open output file" << std::endl;
        return -1;
    }

    int linenum = 0;   ///< Keeps track of line number in file
    std::string temp;   ///< Stores line to use regex with
    bool test = false;   ///< To help determine if failure or not
    std::string tdatet;   ///< Stores the terminating time
    std::string datet;    ///< Stores the beginning time

    boost::regex expression(".*\\(log\\.c\\.166\\) server started");
    boost::regex expression2("[0-9]{2}:[0-6][0-9]:[0-9]{2}");
    boost::regex expression3
    (".*oejs\\.AbstractConnector:Started SelectChannelConnector");
    boost::smatch fmatch;
    boost::smatch dmatch;
    boost::smatch sumatch;


    /**
     *  This while loop gets a line from the file
     *
     *  It then increases the line count since the linenum starts at
     *  0 but the file starts at line 1
     *
     *  The loop then checks to see if we already found success denoted by test. If
     *  test is true we then check to see if we match the correct terminating command
     *  If the command matches using regex, we than extract the time and subtract it from
     *  The starting time, we set test to false, and we output all this to the file.
     *
     *  If test is true and we find another instance of the server starting, there was a failure
     *
     *  The most important part of this loop tests to see when (log.c.166) is called which
     *  is an instance of the server starting. We record the line number its on, when it starts
     *  and then we move on to our checks by setting test to true.
     *
     */
    while (std::getline(inputfile, temp)) {
        ++linenum;
        if (test) {
            if (boost::regex_search(temp, sumatch, expression3)) {
                outputfile << " success";
                tdatet = sumatch[0];
                if (boost::regex_search(tdatet, dmatch, expression2)) {
                    tdatet = dmatch[0];
                    boost::posix_time::time_duration time2
                    (boost::posix_time::duration_from_string(datet));
                    boost::posix_time::time_duration time1
                    (boost::posix_time::duration_from_string(tdatet));
                    time2 = time1 - time2;
                    std::string time = to_simple_string(time2);
                    outputfile << " " << time << std::endl;
                }
                test = false;
            } else {
                if (boost::regex_search(temp, fmatch, expression)) {
                    outputfile << " failure" << std::endl;
                    test = false;
                }
            }
        } else {
            if (boost::regex_search(temp, fmatch, expression)) {
                datet = fmatch[0];
                if (boost::regex_search(datet, dmatch, expression2)) {
                    outputfile << linenum << " " << datet;
                    datet = dmatch[0];
                    test = true;
                }
            }
        }
    }

    /**
     * 
     *  If for some reason we reach the end of the file and the server was never
     *  properly shutdown, we get a success as it will do that automatically.
     *
     */
    if (test) {
        outputfile << " success" << std::endl;
    }

    outputfile.close();
    inputfile.close();

    return 0;
}
Example #25
0
void
worker::run () {
    try {
        assert(_context != NULL);
        assert(_connectAddr.c_str() != NULL);
        fprintf(stdout, "worker: connect address: %s\n",  _connectAddr.c_str());
        fprintf(stdout, "worker: stop requested: %d\n", _stopRequested);
        zmq::socket_t subscriber(*_context, ZMQ_SUB);
        subscriber.connect(_connectAddr.c_str());
        const char* filter = "";
        subscriber.setsockopt(ZMQ_SUBSCRIBE, filter, strlen(filter));
        //capkproto::instrument_bbo bbo;
        
        _inproc = new zmq::socket_t(*_context, ZMQ_PUB);
        assert(_inproc);
        _inproc->connect(_inprocAddr.c_str());
        
        zmq::message_t msg;
        while (1 && _stopRequested == false) {
            subscriber.recv(&msg);
#ifdef DEBUG
            boost::posix_time::ptime time_start(boost::posix_time::microsec_clock::local_time());
#endif

			int64_t more;
			size_t more_size;
			more_size = sizeof(more);
			subscriber.getsockopt(ZMQ_RCVMORE, &more, &more_size);
            // send to orderbook on inproc socket - no locks needed according to zmq
            _inproc->send(msg, more ? ZMQ_SNDMORE : 0);

#ifdef DEBUG
            boost::posix_time::ptime time_end(boost::posix_time::microsec_clock::local_time());
            boost::posix_time::time_duration duration(time_end - time_start);
            fprintf(stderr, "Inbound from md interface time to receive and parse: %s\n", to_simple_string(duration).c_str()); 
#endif
        }
    } 
    catch (std::exception& e) {
        std::cerr << "EXCEPTION: " << __FILE__ << __LINE__ << e.what();
    }
}
Example #26
0
void solve_const_value_in_wherecondition(Node *&cur)
{
	if(cur==NULL)return;
	switch(cur->type)
	{
		case t_name:
		{
			Columns *col=(Columns *)cur;

		}break;
		case t_name_name:
		{
			Columns *col=(Columns *)cur;

		}break;
		case t_query_stmt:
		{

		}break;
		case t_expr_cal:
		{
			Expr_cal *node=(Expr_cal*)cur;
			solve_const_value_in_wherecondition(node->lnext);
			solve_const_value_in_wherecondition(node->rnext);
		}break;
		case t_expr_func:
		{
			Expr_func* node=(Expr_func *)cur;
			string datestr;
			date constdate(from_string("1990-10-01"));
			if(strcmp(node->funname,"FDATE_ADD")==0)
			{
				if(node->args->type==t_stringval)
				{
					datestr=string(((Expr *)node->args)->data);
					Expr_func *datefunc=(Expr_func *)node->parameter1;

					assert(((Expr *)datefunc->args)->type==t_intnum);

					if(strcmp(datefunc->funname,"INTERVAL_DAY")==0)
					{
						date_duration dd(atof(((Expr *)datefunc->args)->data));
						constdate=date(from_string(datestr))+dd;
//						date_duration *dd=new date_duration(atof(((Expr *)datefunc->args)->data));
//						constdate=from_string(datestr)+(*(date_duration *)dd);
					}
					else if(strcmp(datefunc->funname,"INTERVAL_WEEK")==0)
					{
						weeks dd(atof(((Expr *)datefunc->args)->data));
						constdate=date(from_string(datestr))+dd;
					}
					else if(strcmp(datefunc->funname,"INTERVAL_MONTH")==0)
					{
						months dd(atof(((Expr *)datefunc->args)->data));
						constdate=date(from_string(datestr))+dd;
					}
					else if(strcmp(datefunc->funname,"INTERVAL_YEAR")==0)
					{
						years dd(atof(((Expr *)datefunc->args)->data));
						constdate=date(from_string(datestr))+dd;
					}
					else if(strcmp(datefunc->funname,"INTERVAL_QUARTER")==0)
					{
						months dd(atof(((Expr *)datefunc->args)->data)*3);
						constdate=date(from_string(datestr))+dd;
					}
					datestr=to_iso_extended_string(constdate);
					char *datechar=(char *)malloc(datestr.length()+2);
					strcpy(datechar,datestr.c_str());
//					SQLParse_log("the date result after date_add, string= %s ------------------\n",datechar);
					//free(cur);
					cur=(Node *)newExpr(t_stringval,datechar);
				}

			}
			else if(strcmp(node->funname,"FDATE_SUB")==0)
			{
				if(node->args->type==t_stringval)
				{
					datestr=string(((Expr *)node->args)->data);
					Expr_func *datefunc=(Expr_func *)node->parameter1;

					assert(((Expr *)datefunc->args)->type==t_intnum);

					if(strcmp(datefunc->funname,"INTERVAL_DAY")==0)
					{
						date_duration dd(atof(((Expr *)datefunc->args)->data));
						constdate=date(from_string(datestr))-dd;
					}
					else if(strcmp(datefunc->funname,"INTERVAL_WEEK")==0)
					{
						weeks dd(atof(((Expr *)datefunc->args)->data));
						constdate=date(from_string(datestr))-dd;
					}
					else if(strcmp(datefunc->funname,"INTERVAL_MONTH")==0)
					{
						months dd(atof(((Expr *)datefunc->args)->data));
						constdate=date(from_string(datestr))-dd;
					}
					else if(strcmp(datefunc->funname,"INTERVAL_YEAR")==0)
					{
						years dd(atof(((Expr *)datefunc->args)->data));
						constdate=date(from_string(datestr))-dd;
					}
					else if(strcmp(datefunc->funname,"INTERVAL_QUARTER")==0)
					{
						months dd(atof(((Expr *)datefunc->args)->data)*3);
						constdate=date(from_string(datestr))-dd;
					}
					datestr=to_simple_string(constdate);
					char *datechar=(char *)malloc(datestr.length()+2);
					strcpy(datechar,datestr.c_str());
//					SQLParse_log("the date result after date_sub, string= %s ------------------\n",datechar);
					//free(cur);
					cur=(Node *)newExpr(t_stringval,datechar);
				}
			}
			else
			{

			}
		}break;
		case t_expr_list:
		{
			Expr_list * node=(Expr_list *)cur;

		}break;
		default:
		{
				SQLParse_log("solve_const_value_in_wherecondition can't know the type=%d\n",cur->type);
		}
	}
}
Example #27
0
bool Mask::applyMask(Mat &currFrame) {

    if(mMaskToCreate) {

        mOriginalMask = Mat(currFrame.rows, currFrame.cols, CV_8UC1,Scalar(255));
        mOriginalMask.copyTo(mCurrentMask);
        mMaskToCreate = false;

    }

    if(mUpdateMask) {

        if(updateStatus) {

            if(mCurrentMask.rows != currFrame.rows || mCurrentMask.cols != currFrame.cols) {

                throw "Mask's size is not correct according to frame's size.";

            }

            // Reference date.
            refDate = to_simple_string(boost::posix_time::second_clock::universal_time());

            Mat saturateMap = ImgProcessing::buildSaturatedMap(currFrame, saturatedValue);

            // Dilatation of the saturated map.
            int dilation_size = 10;
            Mat element = getStructuringElement(MORPH_RECT, Size(2*dilation_size + 1, 2*dilation_size+1), Point(dilation_size, dilation_size));
            cv::dilate(saturateMap, saturateMap, element);

            satMap.push_back(saturateMap);

            if(satMap.size() == 2) {

                Mat temp = satMap.front() & satMap.back();
                bitwise_not(temp,temp);
                temp.copyTo(mCurrentMask, mOriginalMask);

            }

            Mat temp; currFrame.copyTo(temp, mCurrentMask);
            temp.copyTo(currFrame);

            updateStatus = false;
            return true; // Mask not applied, only computed.

        }

        string nowDate = to_simple_string(boost::posix_time::second_clock::universal_time());
        boost::posix_time::ptime t1(boost::posix_time::time_from_string(refDate));
        boost::posix_time::ptime t2(boost::posix_time::time_from_string(nowDate));
        boost::posix_time::time_duration td = t2 - t1;
        long diffTime = td.total_seconds();

        if(diffTime >= mUpdateInterval) {

            updateStatus = true;

        }

        cout << "NEXT MASK : " << (mUpdateInterval - (int)diffTime) << "s" << endl;

    }

    if(!mCurrentMask.data || (mCurrentMask.rows != currFrame.rows && mCurrentMask.cols != currFrame.cols)) {
        mMaskToCreate = true;
        return true;
    }

    Mat temp; currFrame.copyTo(temp, mCurrentMask);
    temp.copyTo(currFrame);

    return false; // Mask applied.

}
Example #28
0
int main( ) {
   boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ;
   std::cout << to_simple_string( t ) << std::endl ;
   return 0 ;
}
Example #29
0
/*
* Converts a date to today / tomorrow if it happens to match those dates
*/
std::string DisplayFeed::reprDate(std::string date){
    if(date == to_simple_string(boost::gregorian::day_clock::local_day())){date = "Today";}
    else if(date == to_simple_string(boost::gregorian::day_clock::local_day()+boost::gregorian::date_duration(1))){date = "Tomorrow";}
    return date;
}
Example #30
0
void NMEAServer::receiveCommand(Command_ptr command){
        if(command->getCommand()=="exit" || command->getCommand()=="logout" || command->getCommand()=="close"){
            //TODO call exit on all endpoints
            raise(SIGTERM);
        }
        else if(command->getCommand()=="endpoints"){
            std::ostringstream ss;
            ss << "Currently " << online.size() << " endpoints connected" << std::endl << "---------------------------------------" << std::endl;
            for (std::list<Endpoint_ptr>::const_iterator endpoint = online.begin(), end = online.end(); endpoint != end; ++endpoint) {
                std::string state = getEndpointState();
                if(state.length()>0){
                    state = "("+state+")";
                }
                ss << (*endpoint)->getId() << '\t' << state << std::endl;
            }
            command->answer(ss.str(), this->shared_from_this());
        }
        else if(command->getCommand()=="time"){
            command->answer(to_simple_string(boost::posix_time::microsec_clock::local_time())+"\n", this->shared_from_this());
        }
        else if(command->getCommand()=="add"){
            boost::regex reg("^([[:alnum:]]*)\\h?$");
            boost::regex regArg("^([[:alnum:]]*)\\s([[:print:]]+)\\h?$");
            boost::cmatch matches;
            std::string type;
            std::string args;
            bool matched=false;
            if(boost::regex_search(command->getArguments().c_str(), matches, regArg)){
                type=std::string(matches[1].first, matches[1].second);
                args=std::string(matches[2].first, matches[2].second);
                matched=true;
            }
            else if(boost::regex_search(command->getArguments().c_str(), matches, reg)){
                type=std::string(matches[1].first, matches[1].second);
                args=std::string("");
                matched=true;
            }
            if(matched){
                if(type=="file" || type=="File"){
                    try
                    {
                        FileEndpoint::factory(this->shared_from_this(), args);
                        command->answer("New file Endpoint successfully created\n", this->shared_from_this());
                    }
                    catch (std::exception& e)
                    {
                        std::ostringstream oss;
                        oss << "FileEndpoint Exception: " << e.what();
                        log(oss.str());
                    }
                }
                else if(type=="tcp" || type=="TCP"){
                    try
                    {
                        TCPServer::factory(this->shared_from_this(), std::atoi(args.c_str()));
                        command->answer("New tcp Endpoint successfully created\n", this->shared_from_this());
                    }
                    catch (std::exception& e)
                    {
                        std::ostringstream oss;
                        oss << "TCPSession Exception: " << e.what();
                        log(oss.str());
                    }
                }
                else if(type=="serial"){
                    std::vector<std::string> strs;
                    try
                    {
                        boost::split(strs, args, boost::is_any_of("\t "));
                        if(strs.size()==2){
                            unsigned int boud = lexical_cast<unsigned int>(strs[1]);
                            SerialPort::factory(this->shared_from_this(), strs[0] ,boud);
                            command->answer("New SerialPort successfully created\n", this->shared_from_this());
                        }
                        else{
                            command->answer(Answer::WRONG_ARGS,"Cannot create serial. Argument must be \"device boudrate\"\n", this->shared_from_this());
                        }
                    }
                    catch (std::exception& e)
                    {
                        std::cerr << "serial: " << e.what() << "\n";
                        command->answer(Answer::WRONG_ARGS,"Cannot create serial. Argument must be \"device boudrate\"\n", this->shared_from_this());
                    }
                }
                else if(type=="GPSreceiver"){
                    GPSEndpoint::factory(this->shared_from_this());
                    command->answer("New GPSEndpoint successfully created\n", this->shared_from_this());
                }
                else if(type=="TimeEndpoint"){
                    TimeEndpoint::factory(this->shared_from_this());
                    command->answer("New TimeEndpoint successfully created\n", this->shared_from_this());
                }
                else if(type=="AISreceiver"){
                    AISEndpoint::factory(this->shared_from_this());
                    command->answer("New AISEndpoint successfully created\n", this->shared_from_this());
                }
                else if(type=="virtualAIVDO"){
                    try
                    {
                        if(args.length()==9){
                            unsigned int mmsi = lexical_cast<unsigned int>(args);
                            AIVDOEndpoint::factory(this->shared_from_this(), mmsi);
                            command->answer("New virtualAIVDO successfully created\n", this->shared_from_this());
                            
                        }
                        else{
                            command->answer(Answer::WRONG_ARGS,"Cannot create virtualAIVDO. MMSI Arguemnt must be 9 digits\n", this->shared_from_this());
                        }
                    }
                    catch (std::exception& e)
                    {
                        std::cerr << "virtualAIVDO: " << e.what() << "\n";
                        command->answer(Answer::WRONG_ARGS,"Cannot create virtualAIVDO. MMSI Arguemnt must be 9 digits\n", this->shared_from_this());
                    }
                }
                else if(type=="MemoryStore"){
                    MemoryStoreEndpoint::factory(this->shared_from_this(), args);
                    command->answer("New MemoryStoreEndpoint successfully created\n", this->shared_from_this());
                }
                else if(type=="Compass"){
                    CompassEndpoint::factory(this->shared_from_this());
                    command->answer("New CompassEndpoint successfully created\n", this->shared_from_this());
                }
                else{
                    command->answer(Answer::WRONG_ARGS, "Cannot understand command Argument "+command->getArguments()+" for Command "+command->getCommand()+". No such endpoint type to create.\n", this->shared_from_this());
                }
            }
            else{
                command->answer(Answer::WRONG_ARGS, "Cannot understand command Argument "+command->getArguments()+" for Command "+command->getCommand()+"\n", this->shared_from_this());
            }
        }
        else{
            CommandEndpoint::receive(command);
        }
}