void Polyhedron_algorithms::openFromFile(const std::string &filename)
{
    clear();

    FileParsing::SimplestParsing is;

    is.load(filename.c_str());

    int ent;
    is.jumpSeparators();
    is()>>ent;
    is.jumpSeparators();
    is()>>ent; //get the number of points
    is.find("\n");
    is.jumpSeparators();
    for (int g=0; g<ent; g++)
    {
        Scalar y[3];
        is()>>y[0];//get the coords
        is.jumpSeparators();
        is()>>y[1];//get the coords
        is.jumpSeparators();
        is()>>y[2];//get the coords
        is.jumpSeparators();

        S_PolyhedronVertex *v;
        v=new S_PolyhedronVertex();
        v->setCordinates(y[0],y[1],y[2]);
        v->setNumber(unsigned (vertexes_.size()));
        vertexes_.push_back(v);

    }

    while (is.find("normal:"))//get the normals
    {
        is.jumpSeparators();
        Scalar y[3];

        PolyhedronTriangle t;

        is()>>y[0];
        is.jumpSeparators();
        is()>>y[1];
        is.jumpSeparators();
        is()>>y[2];
        is.jumpSeparators();

        t.normal.Set(y[0],y[1],y[2]);
        t.normal.normalize();

        is.find("vertices");//get the indexes
        is.find("p");
        is()>>t.a;
        is.find("p");
        is.jumpSeparators();
        is()>>t.b;
        is.find("p");
        is.jumpSeparators();
        is()>>t.c;



        //updatingNeighbors
        vertexes_[t.a]->addNeighbor(vertexes_[t.b]);
        vertexes_[t.a]->addNeighbor(vertexes_[t.c]);

        vertexes_[t.b]->addNeighbor(vertexes_[t.a]);
        vertexes_[t.b]->addNeighbor(vertexes_[t.c]);

        vertexes_[t.c]->addNeighbor(vertexes_[t.a]);
        vertexes_[t.c]->addNeighbor(vertexes_[t.b]);

        triangles_.push_back(t);



    }

    for (unsigned int i=0; i<vertexes_.size(); i++)
    {
        vertexes_[i]->updateFastArrays();
    }

    deleteVertexesWithoutNeighbors();
}
Example #2
0
AUD_SndFileWriter::AUD_SndFileWriter(std::string filename, AUD_DeviceSpecs specs,
									 AUD_Container format, AUD_Codec codec, unsigned int bitrate) :
	m_specs(specs)
{
	SF_INFO sfinfo;

	sfinfo.channels = specs.channels;
	sfinfo.samplerate = int(specs.rate);

	switch(format)
	{
	case AUD_CONTAINER_FLAC:
		sfinfo.format = SF_FORMAT_FLAC;
		switch(specs.format)
		{
		case AUD_FORMAT_S16:
			sfinfo.format |= SF_FORMAT_PCM_16;
			break;
		case AUD_FORMAT_S24:
			sfinfo.format |= SF_FORMAT_PCM_24;
			break;
		case AUD_FORMAT_S32:
			sfinfo.format |= SF_FORMAT_PCM_32;
			break;
		case AUD_FORMAT_FLOAT32:
			sfinfo.format |= SF_FORMAT_FLOAT;
			break;
		case AUD_FORMAT_FLOAT64:
			sfinfo.format |= SF_FORMAT_DOUBLE;
			break;
		default:
			sfinfo.format = 0;
			break;
		}
		break;
	case AUD_CONTAINER_OGG:
		if(codec == AUD_CODEC_VORBIS)
			sfinfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS;
		else
			sfinfo.format = 0;
		break;
	case AUD_CONTAINER_WAV:
		sfinfo.format = SF_FORMAT_WAV;
		switch(specs.format)
		{
		case AUD_FORMAT_U8:
			sfinfo.format |= SF_FORMAT_PCM_U8;
			break;
		case AUD_FORMAT_S16:
			sfinfo.format |= SF_FORMAT_PCM_16;
			break;
		case AUD_FORMAT_S24:
			sfinfo.format |= SF_FORMAT_PCM_24;
			break;
		case AUD_FORMAT_S32:
			sfinfo.format |= SF_FORMAT_PCM_32;
			break;
		case AUD_FORMAT_FLOAT32:
			sfinfo.format |= SF_FORMAT_FLOAT;
			break;
		case AUD_FORMAT_FLOAT64:
			sfinfo.format |= SF_FORMAT_DOUBLE;
			break;
		default:
			sfinfo.format = 0;
			break;
		}
		break;
	default:
		sfinfo.format = 0;
		break;
	}

	if(sfinfo.format == 0)
		AUD_THROW(AUD_ERROR_SPECS, format_error);

	m_sndfile = sf_open(filename.c_str(), SFM_WRITE, &sfinfo);

	if(!m_sndfile)
		AUD_THROW(AUD_ERROR_FILE, fileopen_error);
}
Example #3
0
CError NegotiatorIPCHandler::NegotiateChannel(std::string tag, UInt32 & cid)
{
    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>START");

    CError err = CSError(CSError::ERROR_OTHER);

    //get channel id from the map
    UInt32 channelId = m_map->getNextFreeChannelId();
    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>channel"+  convertIntegerToString(channelId));

    Notification * noti = NULL;

    noti = new AllocateNotification(tag.c_str(), channelId);
    std::stringstream messageToBeSent;

    noti->Write(messageToBeSent);
    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()=>Message: \n==========\n" + messageToBeSent.str()+"\n===========\n");

    m_negotiatorTube->sendDataTube(messageToBeSent.str().c_str());

    messageToBeSent.str(std::string());

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>WAIT FOR NEGOTIATED");
    m_negotiatorStates->mStateCond.lock();
    if(m_negotiatorStates->GetTagState(tag.c_str()) != NegotiaterStates::NEGOTIATED)
    {
        m_negotiatorStates->mStateCond.wait();
    }
    m_negotiatorStates->mStateCond.unlock();

    //here both messages received
    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>NEGOTIATED"+  convertIntegerToString(channelId));

    //get remote notification
    AllocateNotification * remoteNotification =
        (AllocateNotification *) m_negotiatorStates->GetNotification(tag.c_str());

    UInt32 remoteCid = 0;

    ErrorCode errc;
    const char * errstr;

    remoteNotification->GetError(errc, errstr);
    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>remote notification error"+(std::string)(errstr));

    if (errc == ERRORCODE_SUCCESS)
    {
        remoteCid = remoteNotification->GetChannelId();
        if (remoteCid >= channelId)   //use remote
        {
            if (!m_map->isChannelok(remoteCid))
            {
                if (noti)
                    delete noti;
                noti = 0;
                return err;
            }

            else
                channelId = remoteCid;
        }
    }
    else
    {
        if (noti)
            delete noti;
        noti = 0;

        return err;
    }

    if (noti)
        delete noti;
    noti = 0;
    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()=>Map Check...."+(std::string)(errstr));

    //create map Notification message
    noti = new MapCheckNotification(tag.c_str(), channelId);

    //send the message
    noti->Write(messageToBeSent);
    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()=>Message: \n==========\n"
                    + messageToBeSent.str()+"\n===========\n");

    m_negotiatorTube->sendDataTube(messageToBeSent.str().c_str());

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>WAIT FOR CHECKEDINMAP");

    m_negotiatorStates->mStateCond.lock();
    if(m_negotiatorStates->GetTagState(tag.c_str()) != NegotiaterStates::CHECKEDINMAP)
    {
        m_negotiatorStates->mStateCond.wait();
    }
    m_negotiatorStates->mStateCond.unlock();

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>CHECKEDINMAP"
                    + convertIntegerToString(channelId));

    //get remote notification
    MapCheckNotification * mapRemoteNotification =
        (MapCheckNotification *) m_negotiatorStates->GetNotification(tag.c_str());

    mapRemoteNotification->GetError(errc, errstr);
    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>remote Error"
                    + convertIntegerToString((int)errc)+(std::string)(errstr));

    if (errc == ERRORCODE_SUCCESS)
    {
        cid = channelId;
        err = CError(CError::NO_ERROR, "ChannelSupervisorProcess");
    }
    else
    {
        err = CSError(CSError::ERROR_OTHER);
    }
    if (noti)
        delete noti;
    return err;
}
Example #4
0
bool TestModule(const char *module, asIScriptEngine *engine)
{
	bool fail = false;
	int r;
	CBufferedOutStream bout;
	COutStream out;
	asIScriptModule *mod = engine->GetModule(module);

	// Test that it is possible to declare a class that inherits from another
	// Test that the inherited properties are available in the derived class
	// Test that the inherited methods are available in the derived class
	// Test that it is possible to override the inherited methods
	// Test that it is possible to call base class methods from within overridden methods in derived class 
	asIScriptObject *obj = (asIScriptObject*)engine->CreateScriptObject(mod->GetTypeIdByDecl("Derived"));
	asIScriptContext *ctx = engine->CreateContext();
	ctx->Prepare(obj->GetObjectType()->GetMethodByDecl("void func()"));
	ctx->SetObject(obj);
	r = ctx->Execute();
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}
	ctx->Release();
	obj->Release();

	// Test that implicit cast from derived to base is working
	r = ExecuteString(engine, "Derived d; Base @b = @d; assert( b !is null );", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// Test that cast from base to derived require explicit cast
	engine->SetMessageCallback(asMETHOD(CBufferedOutStream, Callback), &bout, asCALL_THISCALL);
	bout.buffer = "";
	r = ExecuteString(engine, "Base b; Derived @d = @b;", mod);
	if( r >= 0 )
	{
		TEST_FAILED;
	}
	if( bout.buffer != "ExecuteString (1, 22) : Error   : Can't implicitly convert from 'Base@&' to 'Derived@&'.\n" )
	{
		TEST_FAILED;
		printf("%s", bout.buffer.c_str());
	}

	// Test that it is possible to explicitly cast to derived class
	engine->SetMessageCallback(asMETHOD(COutStream, Callback), &out, asCALL_THISCALL);
	r = ExecuteString(engine, "Derived d; Base @b = @d; assert( cast<Derived>(b) !is null );", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// Test the explicit cast behaviour for a non-handle script object
	r = ExecuteString(engine, "Base b; assert( cast<Derived>(b) is null );", mod);
	if( r != asEXECUTION_FINISHED )
	{
		fail= true;
	}

	// Test that it is possible to implicitly assign derived class to base class
	r = ExecuteString(engine, "Derived d; Base b = d;", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// Test that it is possible to pass a derived class to a function expecting a reference to the base class
	// This actually creates an instance of the Base class and assigns the Derived instance to it.
	// This is because the parameter is &in and not const &in
	// TODO: May be able to avoid this by having a specific behaviour for 
	//       duplicating objects, rather than using assignment
	r = ExecuteString(engine, "Derived d; foo(d);", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// Test polymorphing
	r = ExecuteString(engine, "Derived d; Base @b = @d; b.a = 3; b.f2(); assert( b.a == 2 );", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// Base class' destructor must be called when object is destroyed
	r = ExecuteString(engine, "baseDestructorCalled = derivedDestructorCalled = false; { Derived d; }\n"
								      "assert( derivedDestructorCalled ); \n"
		                              "assert( baseDestructorCalled );\n", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// If the base class is garbage collected, then the derived class must also be garbage collected
	// This also tests that it is possible to call the default constructor of the base class, even though it is not declared
	engine->GarbageCollect();
	r = ExecuteString(engine, "DerivedGC b; @b.b = @b;", mod);
	if( r != asEXECUTION_FINISHED ) 
	{
		TEST_FAILED;
	}

	asUINT gcSize;
	engine->GetGCStatistics(&gcSize);
	assert( gcSize == 2 );
	engine->GarbageCollect();
	engine->GetGCStatistics(&gcSize);
	assert( gcSize == 0 );

	// Test that the derived class inherits the interfaces that the base class implements
	r = ExecuteString(engine, "Intf @a; Derived b; @a = @b;", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// Test that an implemented constructor calls the base class' default constructor
	r = ExecuteString(engine, "baseConstructorCalled = derivedConstructorCalled = false; Derived d(1); \n"
		                              "assert( baseConstructorCalled ); \n"
									  "assert( derivedConstructorCalled ); \n", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// Test that the default constructor calls the base class' default constructor
	r = ExecuteString(engine, "baseConstructorCalled = false; Derived d; \n"
		                              "assert( baseConstructorCalled ); \n", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// Test that it is possible to manually call the base class' constructor
	// Test that the default constructor for the base class isn't called 
	//   when a manual call to another constructor is made
	r = ExecuteString(engine, "baseConstructorCalled = baseFloatConstructorCalled = false; DerivedS d(1.4f); \n"
		                              "assert( baseFloatConstructorCalled ); \n"
									  "assert( !baseConstructorCalled ); \n", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}

	// Test that it is possible to determine base class from object type interface
	asIObjectType *d = engine->GetObjectTypeById(mod->GetTypeIdByDecl("Derived"));
	if( d == 0 )
	{
		TEST_FAILED;
	}
	else if( d->GetBaseType() == 0 )
	{
		TEST_FAILED;
	}
	else if( strcmp(d->GetBaseType()->GetName(), "Base") != 0 )
	{
		TEST_FAILED;
	}

	// Test factory id
	if( d->GetFactoryCount() != 2 )
		TEST_FAILED;
	asIScriptFunction *fid = d->GetFactoryByDecl("Derived@ Derived(int)");
	if( fid < 0 )
		TEST_FAILED;
	if( fid != d->GetFactoryByIndex(1) )
		TEST_FAILED;

	// Test various levels of inheritance
	printResult = "";
	r = ExecuteString(engine, "C3 c; c.Call();", mod);
	if( r != asEXECUTION_FINISHED )
	{
		TEST_FAILED;
	}
	if( printResult != "C2:Fun" )
	{
		printf("%s\n", printResult.c_str());
		TEST_FAILED;
	}

	// TODO: not related to inheritance, but it should be possible to call another constructor from within a constructor. 
	//       We can follow D's design of using this(args) to call the constructor

	return fail;
}
Example #5
0
//FIXME: the recommandBuyRegions should be of const
bool Forecaster::getHitRateOfBuying(const std::string& aDBName, std::list<Forecaster::DateRegion>& recommandBuyRegions) {
    LOGD(LOGTAG, "Enter getHitRateOfBuying, aDBName:%s", aDBName.c_str());
    if (recommandBuyRegions.size() < 1) {
        return true;
    }
    std::string sql, targetColumns;
    sqlite3_stmt* stmt = NULL;
    int intRet = -1;

    targetColumns += STRING_DATE;
    targetColumns += ", ";
    targetColumns += STRING_BEGIN_PRICE;
    targetColumns += ", ";
    targetColumns += STRING_END_PRICE;
    sql = SELECT_COLUMNS(mResultTableName, targetColumns);

    LOGI(LOGTAG, "sql:%s", sql.c_str());
    intRet = sqlite3_prepare(mOriginDB,
                             sql.c_str(),
                             -1,
                             &stmt,
                             NULL);

    if (intRet != SQLITE_OK) {
        LOGE(LOGTAG, "Fail to prepare stmt to Table: %s, ret:%d", mResultTableName.c_str(), intRet);
        return false;
    }

    int index = 0;
    std::list<Forecaster::DateRegion>::iterator itr = recommandBuyRegions.begin();
    std::list<Forecaster::PriceRegion> realPriceRegions;
    Forecaster::PriceRegion tmpPriceRegion;

    std::list<Forecaster::DateRegion>::iterator debugDateRegionItr = recommandBuyRegions.begin();
    //while (debugDateRegionItr != recommandBuyRegions.end()) {
    //    LOGI(LOGTAG, "mStartDate in recommandRegions:%s, mEndDate:%s", (*debugDateRegionItr).mStartDate.c_str(), (*debugDateRegionItr).mEndDate.c_str());
    //    debugDateRegionItr++;
    //}

    //Step 1: compare the Date
    while (sqlite3_step(stmt) == SQLITE_ROW && itr != recommandBuyRegions.end()) {
        //NOTE: Assume that the recommandBuyRegions are ordered by date.
        std::string date = (char*)sqlite3_column_text(stmt, 0);
        if (date < (*itr).mStartDate) {
            // have not reach the edge, need not to compare
            continue;
        } else if (date == (*itr).mStartDate) {
            // record the beginningPrice
            // once beggingPrice is set, a new block of region start.
            // so clear the endPrice.
            LOGD(LOGTAG, "Find the the startDate in recommandRegions:%s", date.c_str());
            tmpPriceRegion.mBeginPrice = sqlite3_column_double(stmt, 2);
            continue;
        } else if (date == (*itr).mEndDate) {
            // record the endPrice
            LOGD(LOGTAG, "Find the the EndDate in recommandRegions:%s", date.c_str());
            tmpPriceRegion.mEndPrice = sqlite3_column_double(stmt, 2);
            LOGD(LOGTAG, "the EndPrice:%f , the BeginPrice:%f in tmpPriceRegion:%f", tmpPriceRegion.mEndPrice, tmpPriceRegion.mBeginPrice);
            realPriceRegions.push_back(tmpPriceRegion);
            itr++;
        } else {
            LOGD(LOGTAG, "Normal Date %s", date.c_str());
        }
    }

    intRet = sqlite3_finalize(stmt);
    if (intRet != SQLITE_OK) {
        LOGE(LOGTAG, "Fail to finalize the stmt to finalize table:%s", mResultTableName.c_str());
        return false;
    }


    //Step 2: ensure UP DOWN
    if (realPriceRegions.size() != recommandBuyRegions.size()) {
        LOGE(LOGTAG, "The size of PriceRegions does not equal to that of recommandBuyRegions"); LOGI(LOGTAG, "realPriceRegions length:%d, recommandBuyRegions:%d", realPriceRegions.size(), recommandBuyRegions.size());
        return false;
    }

    std::list<Forecaster::PriceRegion>::iterator debugPriceRegionItr = realPriceRegions.begin();
    debugDateRegionItr = recommandBuyRegions.begin();
    while (debugPriceRegionItr!= realPriceRegions.end()) {
        LOGD(LOGTAG, "mStartDate in PriceRegions mBeginPrice:%f, mEndPrice:%f", (*debugPriceRegionItr).mBeginPrice, (*debugPriceRegionItr).mEndPrice);
        debugPriceRegionItr++;
    }

    double count = 0.0;
    std::list<Forecaster::PriceRegion>::iterator itrOfPriceRegion = realPriceRegions.begin();
    debugDateRegionItr = recommandBuyRegions.begin();
    for (int i = 0; i < realPriceRegions.size(); i++, debugDateRegionItr++) {
        double diff = (*itrOfPriceRegion).mEndPrice - (*itrOfPriceRegion).mBeginPrice;
        if (diff >= 0.01) {
            count = count + 1.0;
        }
        sumIncome = sumIncome + (diff / (*itrOfPriceRegion).mBeginPrice);
        LOGI(LOGTAG, "dbname:%s, begindate:%s, enddate:%s", aDBName.c_str(), (*debugDateRegionItr).mStartDate.c_str(), (*debugDateRegionItr).mEndDate.c_str());
        LOGI(LOGTAG, "beginPrice:%f, endPrice:%f, diff:%f, sumIncome:%f ", (*itrOfPriceRegion).mBeginPrice, (*itrOfPriceRegion).mEndPrice, diff, sumIncome);
        itrOfPriceRegion++;
    }

    sumShots += count;
    sumForcasters += realPriceRegions.size();

    //Step 3: compute HintRate
    double hitRate = count/realPriceRegions.size();
    LOGI(LOGTAG, "HitRate for Suggesting Buy:%f, shot count:%f, sum count:%d", hitRate, count, realPriceRegions.size());
    LOGI(LOGTAG, "\n\n======sum of reallly HitShots:%f, sum of Forcasters:%f, hitRate:%f, sumIncome:%f\n\n", sumShots, sumForcasters, hitRate, sumIncome);

    return true;
}
Example #6
0
void GraphModeler::loadPreset(Node *parent, std::string presetFile,
        std::string *filenames,
        std::string translation,
        std::string rotation,
        std::string scale)
{


    xml::BaseElement* newXML=NULL;

    newXML = xml::loadFromFile (presetFile.c_str() );
    if (newXML == NULL) return;

    //bool collisionNodeFound=false;
    //xml::BaseElement *meshMecha=NULL;
    xml::BaseElement::child_iterator<> it(newXML->begin());
    for (; it!=newXML->end(); ++it)
    {

        if (it->getType() == std::string("MechanicalObject"))
        {
            updatePresetNode(*it, std::string(), translation, rotation, scale);
        }
        if (it->getType() == std::string("MeshObjLoader") || it->getType() == std::string("SparseGrid"))
        {
            updatePresetNode(*it, filenames[0], translation, rotation, scale);
            //meshMecha = it;
        }
        if (it->getType() == std::string("OglModel"))
        {
            updatePresetNode(*it, filenames[1], translation, rotation, scale);
        }

        if (it->getName() == std::string("VisualNode"))
        {
            xml::BaseElement* visualXML = it;

            xml::BaseElement::child_iterator<> it_visual(visualXML->begin());
            for (; it_visual!=visualXML->end(); ++it_visual)
            {
                if (it_visual->getType() == std::string("OglModel"))
                {
                    updatePresetNode(*it_visual, filenames[1], translation, rotation, scale);
                }
            }
        }
        if (it->getName() == std::string("CollisionNode"))
        {
            //collisionNodeFound=true;
            xml::BaseElement* collisionXML = it;

            xml::BaseElement::child_iterator<> it_collision(collisionXML->begin());
            for (; it_collision!=collisionXML->end(); ++it_collision)
            {

                if (it_collision->getType() == std::string("MechanicalObject"))
                {
                    updatePresetNode(*it_collision, std::string(), translation, rotation, scale);
                }
                if (it_collision->getType() == std::string("MeshObjLoader"))
                {
                    updatePresetNode(*it_collision, filenames[2], translation, rotation, scale);
                }
            }
        }
    }



    if (!newXML->init()) std::cerr<< "Objects initialization failed.\n";
    Node *presetNode = dynamic_cast<Node*> ( newXML->getObject() );
    if (presetNode) addNode(parent,presetNode);
}
Example #7
0
void GraphModeler::save(const std::string &filename)
{
    Node *node = getNode(this->firstChild());
    simulation::getSimulation()->exportXML(node, filename.c_str());
    emit graphClean();
}
Example #8
0
void DirMonInvoker::reportExistingIn(const std::string dir, FW::WatchID watchid) {
#ifndef WIN32
	DIR *dp;
	dp = opendir(dir.c_str());
	if (dp == NULL) {
		LOG(ERROR) << "Error opening directory " << dir << ": " << strerror(errno);
		return;
	}
	// iterate all entries and see what changed
	struct dirent* entry;
	while((entry = readdir(dp))) {
		std::string dname = entry->d_name;
#else
	WIN32_FIND_DATA ffd;
	HANDLE hFind = INVALID_HANDLE_VALUE;
	TCHAR szDir[MAX_PATH];
	StringCchCopy(szDir, MAX_PATH, dir.c_str());
	StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

	hFind = FindFirstFile(szDir, &ffd);
	do {
		std::string dname = ffd.cFileName;
#endif

		if (boost::iequals(dname, ".") || boost::iequals(dname, ".."))
			continue;

		char* filename;
		asprintf(&filename, "%s/%s", dir.c_str(), dname.c_str());

		struct stat fileStat;
		if (stat(filename, &fileStat) != 0) {
			LOG(ERROR) << "Error with stat on directory entry " << filename << ": " << strerror(errno);
			free(filename);
			continue;
		}

		if (fileStat.st_mode & S_IFDIR) {
			if (_recurse) {
				reportExistingIn(filename, watchid);
			} else {
				free(filename);
				continue;
			}
		}

		if (!filter(dname)) {
			free(filename);
			continue;
		}

		handleFileAction(watchid, dir, filename, FW::Actions::Existing);
#ifndef WIN32
	}
	closedir(dp);
#else
	}
	while (FindNextFile(hFind, &ffd) != 0);
	FindClose(hFind);
#endif

}
Example #9
0
void GB2ShapeCache::addShapesWithFile(const std::string &plist) {
    
	//const char *fullName = CCFileUtils::sharedFileUtils()->fullPathForFilename(plist.c_str()).c_str();
    
    CCDictionary *dict = CCDictionary::createWithContentsOfFile(plist.c_str());
    // not triggered - cocos2dx delivers empty dict if non was found

	CCAssert(dict != NULL, "Shape-file not found");
    
    CCAssert(dict->count() != 0, "plist file empty or not existing");
	
	CCDictionary *metadataDict = (CCDictionary *)dict->objectForKey("metadata");
    
    int format = static_cast<CCString *>(metadataDict->objectForKey("format"))->intValue();
    ptmRatio = static_cast<CCString *>(metadataDict->objectForKey("ptm_ratio"))->floatValue();
    CCLOG("ptmRatio = %f",ptmRatio);
	CCAssert(format == 1, "Format not supported");

    
	CCDictionary *bodyDict = (CCDictionary *)dict->objectForKey("bodies");

    b2Vec2 vertices[b2_maxPolygonVertices];
    
    CCDictElement *dictElem;
    std::string bodyName;
	CCDictionary *bodyData;
    //iterate body list
    CCDICT_FOREACH(bodyDict,dictElem )
    {
        bodyData = (CCDictionary*)dictElem->getObject();
        bodyName = dictElem->getStrKey();
        
        
        BodyDef *bodyDef = new BodyDef();
        bodyDef->anchorPoint = CCPointFromString(static_cast<CCString *>(bodyData->objectForKey("anchorpoint"))->getCString());
        CCArray *fixtureList = (CCArray*)(bodyData->objectForKey("fixtures"));
        FixtureDef **nextFixtureDef = &(bodyDef->fixtures);
        
        //iterate fixture list
        CCObject *arrayElem;
        CCARRAY_FOREACH(fixtureList, arrayElem)
        {
            b2FixtureDef basicData;
            CCDictionary* fixtureData = (CCDictionary*)arrayElem;
            
            basicData.filter.categoryBits = static_cast<CCString *>(fixtureData->objectForKey("filter_categoryBits"))->intValue();
            
            basicData.filter.maskBits = static_cast<CCString *>(fixtureData->objectForKey("filter_maskBits"))->intValue();
            basicData.filter.groupIndex = static_cast<CCString *>(fixtureData->objectForKey("filter_groupIndex"))->intValue();
            basicData.friction = static_cast<CCString *>(fixtureData->objectForKey("friction"))->floatValue();
            
            basicData.density = static_cast<CCString *>(fixtureData->objectForKey("density"))->floatValue();
            
            basicData.restitution = static_cast<CCString *>(fixtureData->objectForKey("restitution"))->floatValue();
            
            basicData.isSensor = (bool)static_cast<CCString *>(fixtureData->objectForKey("isSensor"))->intValue();
           
            CCString *cb = static_cast<CCString *>(fixtureData->objectForKey("userdataCbValue"));
            
            int callbackData = 0;

			if (cb)
				callbackData = cb->intValue();

			std::string fixtureType = static_cast<CCString *>(fixtureData->objectForKey("fixture_type"))->m_sString;

			if (fixtureType == "POLYGON") {
				CCArray *polygonsArray = (CCArray *)(fixtureData->objectForKey("polygons"));
				
                CCObject *dicArrayElem;
                CCARRAY_FOREACH(polygonsArray, dicArrayElem)
                {
                    FixtureDef *fix = new FixtureDef();
                    fix->fixture = basicData; // copy basic data
                    fix->callbackData = callbackData;
                    
                    b2PolygonShape *polyshape = new b2PolygonShape();
                    int vindex = 0;
                    
                    CCArray *polygonArray = (CCArray*)dicArrayElem;
                    
                    assert(polygonArray->count() <= b2_maxPolygonVertices);
                    
                    CCObject *piter;
                    CCARRAY_FOREACH(polygonArray, piter)
                    {
                        CCString *verStr = (CCString*)piter;
                        CCPoint offset = CCPointFromString(verStr->getCString());
                        vertices[vindex].x = (offset.x / ptmRatio) ;
                        vertices[vindex].y = (offset.y / ptmRatio) ;
                        vindex++;
                    }
Example #10
0
inline bool order_caps_load(OrderCaps & caps, std::string const & filename)
{
    return order_caps_load(caps, filename.c_str());
}
Example #11
0
void SQLUtility::executeExpectErrorMsgStartWith(const std::string &sql,
                                                const std::string &errmsg) {
  std::string errout = execute(sql, false);
  EXPECT_STREQ(errmsg.c_str(), errout.substr(0, errmsg.size()).c_str());
}
Example #12
0
inline bool bitmap_caps_load(BitmapCaps & caps, std::string const & filename)
{
    return bitmap_caps_load(caps, filename.c_str());
}
Example #13
0
inline bool general_caps_load(GeneralCaps & caps, std::string const & filename)
{
    return general_caps_load(caps, filename.c_str());
}
Example #14
0
	bool Level_::LoadLevelData( irr::io::IFileSystem *fileSystem, const std::string& levelFile,
		irr::scene::ISceneManager *smgr )
	{
		using namespace irr;
		using namespace std;

		auto *levelReader = fileSystem->createXMLReaderUTF8( levelFile.c_str() );
		if( levelReader == nullptr )
		{
			return false;
		}

		while( levelReader->read() )
		{
			if( levelReader->getNodeType() == io::EXN_ELEMENT )
			{
				string name( levelReader->getNodeName() );
				// get the entry position (where the ball starts) coordinates
				if( name == "entry\0" )
				{
					entryX = levelReader->getAttributeValueAsFloat( "x" );
					entryY = levelReader->getAttributeValueAsFloat( "y" );
					entryZ = levelReader->getAttributeValueAsFloat( "z" );
				}
				// get the exit position coordinates
				else if( name == "exit\0" )
				{
					exitX = levelReader->getAttributeValueAsFloat( "x" );
					exitY = levelReader->getAttributeValueAsFloat( "y" );
					exitZ = levelReader->getAttributeValueAsFloat( "z" );
				}
				// get the vent coordinates and attributes and add it to the vector
				else if( name == "vent\0" )
				{
					VentInfo *v = new VentInfo;
					v->x = levelReader->getAttributeValueAsFloat( "x" );
					v->y = levelReader->getAttributeValueAsFloat( "y" );
					v->z = levelReader->getAttributeValueAsFloat( "z" );
					v->strength = levelReader->getAttributeValueAsInt( "strength" );
					v->direction = CalcDirection( v->x, v->y, v->z );
					vents.push_back( v );
				}
				else if( name == "bgmusic\0" )
				{
					AddPairToSoundFilenameMap( "bgmusic", levelReader->getAttributeValueSafe( "file" ) );
				}
				else if( name == "collisionSound\0" )
				{
					AddPairToSoundFilenameMap( "collision", levelReader->getAttributeValueSafe( "file" ) );
				}
				else if( name == "ventSound\0" )
				{
					AddPairToSoundFilenameMap( "vent", levelReader->getAttributeValueSafe( "file" ) );
				}
				else if( name == "jetSound\0" )
				{
					AddPairToSoundFilenameMap( "jet", levelReader->getAttributeValueSafe( "file" ) );
				}
				else if( name == "rollSound\0" )
				{
					AddPairToSoundFilenameMap( "roll", levelReader->getAttributeValueSafe( "file" ) );
				}
				else if( name == "trigger\0" )
				{
					Trigger trigger(smgr);
					char* eventName = (char*)levelReader->getAttributeValue("event");
					if ( eventName == 0 )
					{
						trigger.type = triggerLocation;
						irr::core::vector3di loc(levelReader->getAttributeValueAsInt("x"), 
							levelReader->getAttributeValueAsInt("y"), 
							levelReader->getAttributeValueAsInt("z") );
						trigger.blockLoc = loc;
					}
					else
					{
						trigger.type = triggerNamed;
						trigger.name = eventName;
					}
					trigger.prompt = (char*)levelReader->getAttributeValueSafe( "prompt" );
					triggers.push_back(trigger);
				}
			}
		}

		delete levelReader;
		return true;
	}
Example #15
0
 RuntimeError(const std::string& message) : 
   std::runtime_error(message.c_str()) { }
Example #16
0
void tracef(const std::string &msg, float f, ExecutionContext *_context)
{
    char buf[64];
    snprintf(buf, 64, "%s: %f", msg.c_str(), f);
    TRACE_CALL_TREE(_context->callTree, buf);
}
//! Remove file names specified in filenameList from argv, except for 'exceptFilename'
void
CommandlineProcessing::removeAllFileNamesExcept ( vector<string> & argv, Rose_STL_Container<std::string> filenameList, std::string exceptFilename )
   {
#if 0
     printf ("In CommandlineProcessing::removeAllFileNamesExcept exceptFilename = %s \n",exceptFilename.c_str());
     printf ("In removeAllFileNamesExcept (at top): argv         = \n%s \n",StringUtility::listToString(argv).c_str());
     printf ("In removeAllFileNamesExcept (at top): filenameList = \n%s \n",StringUtility::listToString(filenameList).c_str());
#endif

#if 0 // Liao 11/15/2012. this code is confusing. 
     for (unsigned int i=0; i < argv.size(); i++)
        {
          string argString = argv[i];
#if 0
          printf ("i = %u argString = %s \n",i,argString.c_str());
#endif
          Rose_STL_Container<std::string>::iterator filenameIterator = filenameList.begin();
          while (filenameIterator != filenameList.end())
             {
#if 0
               printf ("filenameIterator = %s \n",filenameIterator->c_str());
#endif
            // DQ (1/17/2009): This is a match with filenameIterator = a.out and argString = a.out.new!
            // I think we only want to do anything about exact matches.
            // if ( argString.substr(0,filenameIterator->size()) == *filenameIterator )
               if ( argString == *filenameIterator )
                  {
#if 0
                    printf ("Found a file name (removeAllFileNamesExcept): %s \n",argString.c_str());
#endif
                    if (*filenameIterator != exceptFilename)
                       {
#if 0
                         printf ("*filenameIterator != exceptFilename so erase end of argv for i = %u \n",i);
#endif
                      // This is not an iterator invalidation error, but it is strange code!
                         argv.erase(argv.begin() + i);
                         --i; // To counteract the i++ in the loop header
#if 0
                         printf ("After erase: i = %u argv = \n%s \n",i,StringUtility::listToString(argv).c_str());
#endif
                       }
                  }

               filenameIterator++;
             }
        }
#endif
    vector<string>::iterator argv_iter = argv.begin();
    while (argv_iter != argv.end())
    {
      string argString = *(argv_iter);
      bool shouldDelete = false; 

      Rose_STL_Container<std::string>::iterator filenameIterator = filenameList.begin();
      while (filenameIterator != filenameList.end())
      {
        // DQ (1/17/2009): This is a match with filenameIterator = a.out and argString = a.out.new!
        // I think we only want to do anything about exact matches.
        // if ( argString.substr(0,filenameIterator->size()) == *filenameIterator )
        if ( argString == *filenameIterator )
        {
          if (*filenameIterator != exceptFilename)
          {
            shouldDelete = true;
            break;
          }
        }
        filenameIterator++;
      } // end while filename iterator

      if (shouldDelete)
      {
        //vector::erase() return a random access iterator pointing to the new location of the element that followed the last element erased by the function call
        //Essentially, it returns an iterator points to next element. 
        argv_iter = argv.erase (argv_iter);
      }
      else
        argv_iter ++;
    } // end while argv_iter

#if 0
     printf ("Leaving removeAllFileNamesExcept (at bottom): argv         = \n%s \n",StringUtility::listToString(argv).c_str());
#endif
   }
Example #18
0
void tracei(const std::string &msg, int i, ExecutionContext *_context)
{
    char buf[64];
    snprintf(buf, 64, "%s %d", msg.c_str(), i);
    TRACE_CALL_TREE(_context->callTree, buf);
}
Example #19
0
void GraphModeler::updatePresetNode(xml::BaseElement &elem, std::string meshFile, std::string translation, std::string rotation, std::string scale)
{
    if (elem.presenceAttribute(std::string("filename")))     elem.setAttribute(std::string("filename"),     meshFile.c_str());
    if (elem.presenceAttribute(std::string("fileMesh")))     elem.setAttribute(std::string("fileMesh"),     meshFile.c_str());
    if (elem.presenceAttribute(std::string("fileTopology"))) elem.setAttribute(std::string("fileTopology"), meshFile.c_str());

    if (elem.presenceAttribute(std::string("translation")))  elem.setAttribute(std::string("translation"), translation.c_str());
    if (elem.presenceAttribute(std::string("rotation")))     elem.setAttribute(std::string("rotation"),    rotation.c_str());
    if (elem.presenceAttribute(std::string("scale3d")))      elem.setAttribute(std::string("scale3d"),     scale.c_str());
}
Example #20
0
        bool LoadJvmLibrary(const std::string& path)
        {
            HMODULE mod = LoadLibraryA(path.c_str());

            return mod != NULL;
        }
Example #21
0
TEST(Frame, AnonymousParseCompile)
{
    using uavcan::Frame;
    using uavcan::CanFrame;
    using uavcan::TransferID;
    using uavcan::TransferType;

    Frame frame;

    /*
     * Priority
     * Discriminator
     * Message Type ID
     * Service Not Message
     * Source Node ID
     */
    const uint32_t can_id =
        (16383 << 10) | // Discriminator
        (1 << 8);       // Message Type ID

    const std::string payload_string = "hello\xd4"; // SET = 110, TID = 20

    uavcan::TransferCRC payload_crc;
    payload_crc.add(reinterpret_cast<const uint8_t*>(payload_string.c_str()), unsigned(payload_string.length()));

    /*
     * Parse
     */
    ASSERT_TRUE(frame.parse(makeCanFrame(can_id, payload_string, EXT)));

    EXPECT_EQ(TransferID(20), frame.getTransferID());
    EXPECT_TRUE(frame.isStartOfTransfer());
    EXPECT_TRUE(frame.isEndOfTransfer());
    EXPECT_FALSE(frame.getToggle());
    EXPECT_TRUE(frame.getSrcNodeID().isBroadcast());
    EXPECT_TRUE(frame.getDstNodeID().isBroadcast());
    EXPECT_EQ(uavcan::TransferTypeMessageBroadcast, frame.getTransferType());
    EXPECT_EQ(1, frame.getDataTypeID().get());
    EXPECT_EQ(0, frame.getPriority().get());

    EXPECT_EQ(payload_string.length() - 1, frame.getPayloadLen());
    EXPECT_TRUE(std::equal(frame.getPayloadPtr(), frame.getPayloadPtr() + frame.getPayloadLen(),
                           reinterpret_cast<const uint8_t*>(&payload_string[0])));

    std::cout << frame.toString() << std::endl;

    /*
     * Compile
     */
    const uint32_t DiscriminatorMask = 0x00FFFC00;
    const uint32_t NoDiscriminatorMask = 0xFF0003FF;

    CanFrame can_frame;
    ASSERT_TRUE(frame.parse(makeCanFrame(can_id, payload_string, EXT)));

    ASSERT_TRUE(frame.compile(can_frame));
    ASSERT_EQ(can_id & NoDiscriminatorMask & uavcan::CanFrame::MaskExtID,
              can_frame.id & NoDiscriminatorMask & uavcan::CanFrame::MaskExtID);

    EXPECT_EQ(payload_string.length(), can_frame.dlc);
    EXPECT_TRUE(std::equal(can_frame.data, can_frame.data + can_frame.dlc,
                           reinterpret_cast<const uint8_t*>(&payload_string[0])));

    EXPECT_EQ((can_frame.id & DiscriminatorMask & uavcan::CanFrame::MaskExtID) >> 10, payload_crc.get() & 16383);

    /*
     * Comparison
     */
    ASSERT_FALSE(Frame() == frame);
    ASSERT_TRUE(Frame() != frame);
    frame = Frame();
    ASSERT_TRUE(Frame() == frame);
    ASSERT_FALSE(Frame() != frame);
}
Example #22
0
/*---------------------------------------------------------------
						sendString
 ---------------------------------------------------------------*/
void  CClientTCPSocket::sendString( const std::string &str )
{
	Write( str.c_str(), str.size() );
}
Example #23
0
bool Forecaster::getBuyDateRegionsContinueFlowinFFP(const std::string& aDBName, std::list<Forecaster::DateRegion>& recommandBuyDateRegions) {
    std::string sql, targetColumns;
    sqlite3_stmt* stmt = NULL;
    int intRet = -1;

    targetColumns += STRING_DATE;
    targetColumns += ",";
    targetColumns += STRING_TURNOVER_SALE;
    targetColumns += ",";
    targetColumns += STRING_TURNOVER_BUY;
    targetColumns += ",";
    targetColumns += STRING_TURNOVER_FLOWIN_ONE_DAY;
    targetColumns += ",";
    targetColumns += STRING_TURNOVER_FLOWIN_TEN_DAYS;
    targetColumns += ",";
    targetColumns += STRING_BEGIN_PRICE;
    targetColumns += ",";
    targetColumns += STRING_END_PRICE;
    sql = SELECT_COLUMNS(mResultTableName, targetColumns);

    LOGD(LOGTAG, "sql:%s", sql.c_str());
    intRet = sqlite3_prepare(mOriginDB,
                          sql.c_str(),
                          -1,
                          &stmt,
                          NULL);

    if (intRet != SQLITE_OK) {
        LOGE(LOGTAG, "Fail to prepare stmt to Table:%s, errno:%d", mResultTableName.c_str(), errno);
        return false;
    }

    Forecaster::DateRegion tmpDateRegion;
    int count = 0;
    int lastingDays = 0;
    //block of continious positive flowinoneday
    bool newContiniousBlockStarted = false;
    //block of buy/sale
    bool newBuySaleBlockStarted = false;
    double startPrice = 0.0;
    std::string startDate, endDate;
            tmpDateRegion.mStartDate = startDate;
            tmpDateRegion.mEndDate   = endDate;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        
        std::string date    = (char*)sqlite3_column_text(stmt, 0);
        double turnoverSale = sqlite3_column_double(stmt, 1);
        double turnoverBuy  = sqlite3_column_double(stmt, 2);
        double flowinOneDay = sqlite3_column_double(stmt, 3);
        double flowinTenDay = sqlite3_column_double(stmt, 4);
        double beginPrice   = sqlite3_column_double(stmt, 5);
        double endPrice     = sqlite3_column_double(stmt, 6);

        LOGD(LOGTAG, "aDBName:%s, Date:%s, TurnoverSale:%f, TurnoverBuy:%f, flowinOneDay:%f, beginPrice:%f, endPrice:%f",
                      aDBName.c_str(), date.c_str(), turnoverSale, turnoverBuy, flowinOneDay, beginPrice, endPrice);
        //Step 1: find the starting day: there has been DEFAULT_LASTING_LEN days whose flowinOneDay is positive
        if (flowinOneDay > MIN_TURNOVER && !newBuySaleBlockStarted) {
            if (!newContiniousBlockStarted) {
                newContiniousBlockStarted= true;
                startPrice = beginPrice;
            }
            ++lastingDays;
            // If the length of lastingDays is less than DEFAULT_LASTING_LEN,
            // which means we still want lastingDays to graw up
            // Else it is time to check other contidions
            if (lastingDays < DEFAULT_LASTING_LEN) {
                countInTurnOver(date, false, turnoverBuy, turnoverSale);
                //compute the days whose flowinOneDay/turnoverSale > 30%
                if ((flowinOneDay/turnoverSale) > 0.5) {
                    LOGD(LOGTAG, "Meet the contition to start counting:flowinOneDay:%f, turnoverSale:%f, DBName:%s, date:%s", flowinOneDay, turnoverSale, aDBName.c_str(), date.c_str());
                    count++;
                }
                //If we decide to buy it now through SumFlowin/out, then do it.
                if (!shouldBuyInNow()) {
                    continue;
                }
            }
        } else if ((flowinOneDay < -MIN_TURNOVER) && !newBuySaleBlockStarted) {
            // reset the count & lastingDays & beginPrice
            countInTurnOver(date, true);
            count = lastingDays = 0;
            newContiniousBlockStarted = false;
            tmpDateRegion.mStartDate = tmpDateRegion.mEndDate = "";
            continue;
        }

        //Step 2: check whether the Turnover & Price meets our need
        if (newContiniousBlockStarted
            && ((shouldBuyInNow() && lastingDays >= (DEFAULT_LASTING_LEN/2))
            || flowinTenDay > 1.3 * flowinOneDay 
            || lastingDays >= DEFAULT_LASTING_LEN)) {
            //|| (shouldBuyInNow() && lastingDays >= (DEFAULT_LASTING_LEN/2)))) {
            countInTurnOver(date, false, turnoverBuy, turnoverSale);
            if ( count >= 1 || lastingDays >= DEFAULT_LASTING_LEN) {
                LOGD(LOGTAG, "Meet the contition to start the newBuySaleBlockStarted, DBName:%s, date:%s", aDBName.c_str(), date.c_str());
                newBuySaleBlockStarted = true;
                tmpDateRegion.mStartDate = date;
                count = lastingDays = 0;
            }
            continue;
        }

        //Step 3: get the dateNO on which we should sale it.
        if (newBuySaleBlockStarted && newBuySaleBlockStarted
            && ((flowinOneDay > MIN_TURNOVER) || (flowinOneDay < -MIN_TURNOVER))) {
            //FIXME:compute the sale-date, 
            //TODO: Needs more complicated Algorithm to determine when to sale it
            //if (flowinOneDay / turnoverSale < 0.1) {
            if (shouldSaleOut(turnoverBuy, turnoverSale)) {
                tmpDateRegion.mEndDate = date;
                LOGD(LOGTAG, "Meet the contition to end the newBuySaleBlockStarted, DBName:%s, date:%s", aDBName.c_str(), date.c_str());
                recommandBuyDateRegions.push_back(tmpDateRegion);
                //reset everything
                tmpDateRegion.mStartDate = tmpDateRegion.mEndDate = "";
                newContiniousBlockStarted = false;
                newBuySaleBlockStarted = false;
            }
        }
    }
    if (SQLITE_OK != sqlite3_finalize(stmt)) {
        LOGE(LOGTAG, "Fail to finalize stmt in getBuyDateRegionsContinueFlowinFFP aDBName:%s", aDBName.c_str());
        return false;
    }

    return true;
}
Example #24
0
std::string XsltMapper::apply( const std::string& o) const
{
	DocumentReader reader( o.c_str(), o.size());
	DocumentReader mapped( apply( reader));
	return mapped.getContent();
}
Example #25
0
 void DrawingArea::DrawString(const int x, const int y, const int size, const std::string Text, const SSDL::Color Color) {
     //        gfxPrimitivesSetFont(&SDL_gfx_font_9x18B_fnt, 9, 18); // TODO: SDL_ttf?
     stringRGBA(this->surface, x, y, Text.c_str(), Color.GetRed(), Color.GetGreen(), Color.GetBlue(), Color.GetAlpha());
 }
void ForexConnectWrapper::saveHistoricalDataToFile(const std::string filename, const std::string symbol, const std::string tf, int totalItemsToDownload) {
        IO2GTimeframeCollection *timeframeCollection = mRequestFactory->getTimeFrameCollection();
        IO2GTimeframe *timeframeObject = NULL;
        int timeframeCollectionSize = timeframeCollection->size();
        for (int i = 0; i < timeframeCollectionSize; i++) {
            IO2GTimeframe *searchTimeframeObject = timeframeCollection->get(i);
            if ( tf == searchTimeframeObject->getID() ) {
                timeframeObject = searchTimeframeObject;
                break;
            } else {
                searchTimeframeObject->release();
            }
        }
        timeframeCollection->release();

        if (!timeframeObject) {
            log("Could not find timeframe");
            throw "Could not find timeframe";
        }


        double timeFrom = 0, timeTo = 0;

        time_t rawtime = time(NULL);
        struct tm timeinfo = *localtime(&rawtime);
        timeinfo.tm_year = 50;
        timeinfo.tm_mon = 0;
        timeinfo.tm_mday = 1;
        timeinfo.tm_hour = 0;
        timeinfo.tm_min = 0;
        timeinfo.tm_sec = 0;

        CO2GDateUtils::CTimeToOleTime(&timeinfo, &timeFrom);
        std::string dd;
        formatDate(timeFrom, dd);

        std::ofstream outputFile;
        outputFile.open(filename.c_str());
        Listener *ll = new Listener(session);
        while (totalItemsToDownload > 0) {
            IO2GRequest *marketDataRequest = mRequestFactory->createMarketDataSnapshotRequestInstrument(symbol.c_str(), timeframeObject, totalItemsToDownload > 300 ? 300 : totalItemsToDownload);
            if (!marketDataRequest) {
                std::ostringstream errorMsg;
                errorMsg << "Failed to create MarketDataSnapshotRequestInstrument for " << symbol.c_str();
                throw  errorMsg.str();
            }
            mRequestFactory->fillMarketDataSnapshotRequestTime(marketDataRequest, timeFrom, timeTo, false);
            IO2GResponse *marketDataResponse = ll->sendRequest(marketDataRequest);
            if (!marketDataResponse) {
                throw "no response to marketDataRequest";
            }

            IO2GMarketDataSnapshotResponseReader *marketSnapshotReader = mResponseReaderFactory->createMarketDataSnapshotReader(marketDataResponse);
            if (!marketSnapshotReader) {
                throw "Failed to create marketSnapshotReader";
            }
            int snapshotSize = marketSnapshotReader->size();
            for (int i = snapshotSize - 1; i >= 0; i--) {
                double date = marketSnapshotReader->getDate(i);
                std::string dateTimeStr;
                formatDate(date, dateTimeStr);
                outputFile << dateTimeStr << "\t" << double2str(marketSnapshotReader->getAskOpen(i)) << "\t" << double2str(marketSnapshotReader->getAskHigh(i)) << "\t" << double2str(marketSnapshotReader->getAskLow(i)) << "\t" << double2str(marketSnapshotReader->getAskClose(i)) << "\t" << std::endl;

            }

            totalItemsToDownload -= snapshotSize;
            if (totalItemsToDownload > 0) {
                timeTo = marketSnapshotReader->getDate(0);
            }
            marketSnapshotReader->release();
        }
        timeframeObject->release();
        ll->release();
        outputFile.close();
}
Example #27
0
void NegotiatorIPCHandler::ProcessIPCClientMessage(std::string message, std::string &response)
{
    LOG4CPLUS_TRACE_METHOD(msLogger, "NegotiatorIPCHandler::ProcessIPCClientMessage()==>START=====");
    Message * msg = NULL;
    CError err = CSError(CSError::ERROR_OTHER);

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::ProcessIPCClientMessage() message = \n" + message);

    pugi::xml_document* doc = new pugi::xml_document();
    ParseResponse(doc, (Int8*) message.c_str());

    if (m_state == IDLE) //process allocate and deallocate
    {

        LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::ProcessIPCClientMessage()==>IDLE=====");
        if (Notification::NOTIFICATIONTTYPE_ALLOCATE == Notification::GetNotificationType(doc))
        {
            LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::ProcessIPCClientMessage()==>ALLOCATE=====");
            AllocateChannelRequest * request = new AllocateChannelRequest(doc);
            std::string tag = request->GetTag();
            UInt32 channel = 0;
            err = NegotiateChannel(tag, channel);
            LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::ProcessIPCClientMessage()==>IDLE=====" + convertIntegerToString(channel));
            msg = new AllocateChannelResponse(tag.c_str(), channel);

            if (!err.isNoError())
            {
                if (err.getCode() == CSError::UPDATE_MAP_WRONG_CID)
                    ((AllocateChannelResponse*) msg)->SetError(ERRORCODE_WRONG_CHANNELID, "wrong cid");
                else if (err.getCode() == CSError::UPDATE_MAP_TIMEOUT)
                    ((AllocateChannelResponse*) msg)->SetError(ERRORCODE_TIMEOUT_OCCURRED, "timeout");
                else
                    ((AllocateChannelResponse*) msg)->SetError(ERRORCODE_OTHER, "other error");
            }

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

            m_state = NEGOTIATED;
        }
        else if (Notification::NOTIFICATIONTTYPE_DEALLOCATE == Notification::GetNotificationType(doc))
        {
            LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::ProcessIPCClientMessage()==>DEALLOCATE=====");
            DeallocateChannelRequest * request = new DeallocateChannelRequest(doc);
            std::string tag = request->GetTag();
            UInt32 channel = request->GetChannelId();
            err = ChannelDeallocated(tag, channel);
            msg = new DeallocateChannelResponse(tag.c_str(), channel);

            if (!err.isNoError())
            {
                if (err.getCode() == CSError::DEALLOCATION_CHANNEL_MAP_WRONG_CID)
                    ((DeallocateChannelResponse*) msg)->SetError(ERRORCODE_WRONG_CHANNELID, "wrong cid");
                else if (err.getCode() == CSError::DEALLOCATION_CHANNEL_MAP_TIMEOUT)
                    ((DeallocateChannelResponse*) msg)->SetError(ERRORCODE_TIMEOUT_OCCURRED, "timeout");
                else
                    ((DeallocateChannelResponse*) msg)->SetError(ERRORCODE_OTHER, "other error");
            }

            if (request)
                delete request;
            request = 0;

            m_state = IDLE;
        }
        else
        {
            msg = new CommandRejectResponse("");
        }
    }
    else if (m_state == NEGOTIATED) //process update map only
    {
        LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::ProcessIPCClientMessage()==>CA_ALLOCATION_DONE=====");
        if (Request::REQUESTTYPE_CA_ALLOCATION_DONE == Request::GetRequestType(doc))
        {
            CAAllocateDoneRequest * request = new CAAllocateDoneRequest(doc);
            std::string tag = request->GetTag();
            UInt32 channel  = request->GetChannelId();
            err = UpdateMap(tag, channel);

            msg = new CAAllocateDoneResponse(tag.c_str(), channel);

            if (!err.isNoError())
            {
                if (err.getCode() == CSError::UPDATE_MAP_WRONG_CID)
                    ((CAAllocateDoneResponse*) msg)->SetError(ERRORCODE_WRONG_CHANNELID, "wrong cid");
                else if (err.getCode() == CSError::UPDATE_MAP_TIMEOUT)
                    ((CAAllocateDoneResponse*) msg)->SetError(ERRORCODE_TIMEOUT_OCCURRED, "timeout");
                else
                    ((CAAllocateDoneResponse*) msg)->SetError(ERRORCODE_OTHER, "other error");
            }

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

            m_state = IDLE;
        }
        else
        {
            LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::ProcessIPCClientMessage()==>REJECT=====");
            msg = new CommandRejectResponse("");
        }
    }
    else //error here
    {
        LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::ProcessIPCClientMessage()==>ERROR===== State = "+  convertIntegerToString((int)m_state));
        msg = new CommandRejectResponse("");
    }

    std::stringstream messageToBeSent;

    msg->Write(messageToBeSent);
    response = messageToBeSent.str();

    if (msg)
        delete msg;
    msg = NULL;
}
Example #28
0
bool Player::SelectProgram(std::string &key)
{
	return manager.selectProgram(atoi(key.c_str()));
}
Example #29
0
CError NegotiatorIPCHandler::UpdateMap(std::string tag, UInt32 cid)
{
    CError err = CSError(CSError::ERROR_OTHER);

    //store in the map
    ChannelInfo chInfo;
    chInfo.tag = tag;

    chInfo.timeStamp = time(NULL);

    Notification * noti = new CAAllocationNotification(tag.c_str(), cid);
    std::stringstream messageToBeSent;

    noti->Write(messageToBeSent);
    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::UpdateMap()=>Message: \n==========\n" + messageToBeSent.str()+"\n===========\n");
    m_negotiatorTube->sendDataTube(messageToBeSent.str().c_str());

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>WAIT FOR CAALLOCATED");

    m_negotiatorStates->mStateCond.lock();
    if(m_negotiatorStates->GetTagState(tag.c_str()) != NegotiaterStates::CAALLOCATED)
    {
        m_negotiatorStates->mStateCond.wait();
    }
    m_negotiatorStates->mStateCond.unlock();

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>CAALLOCATED");

    delete noti;

    messageToBeSent.str(std::string());

    m_map->addChannelInfo(cid, chInfo);

    noti = new UpdateMapNotification(tag.c_str(), cid);
    noti->Write(messageToBeSent);

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::UpdateMap()=>Message: \n==========\n"
                    + messageToBeSent.str()+"\n===========\n");
    m_negotiatorTube->sendDataTube(messageToBeSent.str().c_str());

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::UpdateMap()=> Current state is "+convertIntegerToString((int)m_negotiatorStates->GetTagState(tag.c_str())));
    m_negotiatorTube->sendDataTube(messageToBeSent.str().c_str());

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>WAIT FOR ALLOCDONE");

    m_negotiatorStates->mStateCond.lock();
    //if(m_negotiatorStates->GetTagState(tag.c_str()) != NegotiaterStates::ALLOCDONE)
    if(m_negotiatorStates->GetTagState(tag.c_str()) != NegotiaterStates::IDLE)
    {
        m_negotiatorStates->mStateCond.wait();
    }
    m_negotiatorStates->mStateCond.unlock();

    LOG4CPLUS_TRACE(msLogger, "NegotiatorIPCHandler::NegotiateChannel()==>ALLOCDONE / IDLE");

    //get remote notification
    UpdateMapNotification * remoteNotification =
        (UpdateMapNotification *) m_negotiatorStates->GetNotification(tag.c_str());

    ErrorCode errc;
    const char * errstr;
    remoteNotification->GetError(errc, errstr);

    if (errc == ERRORCODE_SUCCESS)
    {
        err = CSError::NoCSError("no error");
    }
    if (noti) delete noti;
    return err;
}
Example #30
0
//*******************************************************************
bool GLFont::Create(const std::string &file_name, int tex)
{
	return Create(file_name.c_str(), tex);
}