Esempio n. 1
0
void const_graph_visitort::graph_explore_BC(
  event_grapht &egraph,
  event_idt next,
  std::list<event_idt> &old_path,
  std::set<unsigned> &edges,
  bool porw)
{
  /* TODO: restricts to C_1 U ... U C_n for perf improvement */
  assert(!old_path.empty());

  fence_inserter.instrumenter.message.debug() << "(BC) explore "
                                              << old_path.front()
                                              << " --...--> " << next
                                              << messaget::eom;

  if(visited_nodes.find(next)!=visited_nodes.end())
     return;
  visited_nodes.insert(next);

  /* if all the incoming pos were already visited, add */
  bool no_other_pos = true;
  for(wmm_grapht::edgest::const_iterator it=
    egraph.po_out(next).begin();
    it!=egraph.po_out(next).end();
    ++it)
    if(visited_nodes.find(it->first)==visited_nodes.end())
    {
      no_other_pos = false;
      break;
    }

  if(egraph.po_out(next).empty() || no_other_pos)
  {
    /* inserts all the pos collected from old_path in edges */
    std::list<event_idt>::const_iterator it=old_path.begin();
    std::list<event_idt>::const_iterator next_it=it;
    ++next_it;
    for( ; next_it!=old_path.end() && it!=old_path.end(); ++it, ++next_it)
    {
      const abstract_eventt &e1=egraph[*it];
      const abstract_eventt &e2=egraph[*next_it];
      if(!porw ||
         (e1.operation==abstract_eventt::operationt::Read &&
          e2.operation==abstract_eventt::operationt::Write))
        edges.insert(fence_inserter.add_edge(edget(*it, *next_it)));
    }
    assert(it!=old_path.end());
  }
  else
  {
    for(wmm_grapht::edgest::const_iterator
      next_it=egraph.po_out(next).begin();
      next_it!=egraph.po_out(next).end();
      ++next_it)
    {
      old_path.push_back/*front*/(next_it->first);
      graph_explore_BC(egraph, next_it->first, old_path, edges);
      old_path.pop_back/*front*/();
    }
  }
}
Esempio n. 2
0
// where everything begins...
int main(int argc, char** argv)
{
  const unsigned ONECHAR_ARG = 3, TWOCHAR_ARG = 4;

  // check that syntax is ok
  if (argc < 3)
  {
    std::cerr << "syntax: regress [OPTIONS] <xml file> <output file>" << std::endl;
    return -1;
  }

  // get all options
  for (int i=1; i< argc-2; i++)
  {
    // get the option
    std::string option(argv[i]);

    // process options
    if (option.find("-oi") != std::string::npos)
      OUTPUT_ITER_NUM = true;
    else if (option.find("-or") != std::string::npos)
      OUTPUT_SIM_RATE = true;
    else if (option.find("-s=") != std::string::npos)
    {
      STEP_SIZE = std::atof(&argv[i][ONECHAR_ARG]);
      assert(STEP_SIZE >= 0.0 && STEP_SIZE < 1);
    }
    else if (option.find("-mi=") != std::string::npos)
    {
      MAX_ITER = std::atoi(&argv[i][TWOCHAR_ARG]);
      assert(MAX_ITER > 0);
    }
    else if (option.find("-mt=") != std::string::npos)
    {
      MAX_TIME = std::atof(&argv[i][TWOCHAR_ARG]);
      assert(MAX_TIME > 0);
    }
    else if (option.find("-p=") != std::string::npos)
      read_plugin(&argv[i][ONECHAR_ARG]);
  }

  // setup the simulation 
  READ_MAP = XMLReader::read(std::string(argv[argc-2]));

  // get the (only) simulation object
  boost::shared_ptr<Simulator> s;
  for (std::map<std::string, BasePtr>::const_iterator i = READ_MAP.begin(); i != READ_MAP.end(); i++)
  {
    s = boost::dynamic_pointer_cast<Simulator>(i->second);
    if (s)
      break;
  }

  // make sure that a simulator was found
  if (!s)
  {
    std::cerr << "regress: no simulator found in " << argv[argc-2] << std::endl;
    return -1;
  } 

  // setup the output file
  outfile.open(argv[argc-1]);

  // call the initializers, if any
  if (!INIT.empty())
  {
    BOOST_FOREACH(init_t i, INIT)
      (*i)(NULL, READ_MAP, STEP_SIZE);
  }

  // begin timing
  start_time = clock();

  // begin rendering
  while (step((void*) &s))
  {
  }

  // close the loaded library
  if (HANDLE)
    dlclose(HANDLE);

  // write the number of clock ticks elapsed
  clock_t end_time = clock();
  Real elapsed = (end_time - start_time) / (Real) CLOCKS_PER_SEC;
  outfile << elapsed << std::endl;

  // close the output file
  outfile.close();
}
Esempio n. 3
0
void extract_peers_from_bootstrap_nodes_dat(const unsigned char *buffer, std::list<Contact *>& bootstrap_list)
{
    /*
        The header is so composed:
          uint32_t reserved0          set to zero
          uint32_t reserved1          set to 0x00000003
          uint32_t bootstrap_edition  nodes.dat bootstrap version
          uint32_t num_entries        number of entries in the file
    */

    if(!bootstrap_list.empty())
        return;

    uint32_t reserved0 = *(uint32_t *)&(buffer[0]);
    uint32_t reserved1 = *(uint32_t *)&(buffer[4]);
    uint32_t num_entries = *(uint32_t *)&(buffer[12]);

    if(reserved0 != 0 || reserved1 != 3)
        // wow: this bootstrap nodes.dat is invalid
        return;

    unsigned char *peer = (unsigned char *)&(buffer[16]);

    /*
        The peer is so composed:
          uint64_t low_peer_id        128-bit peer identifier (MD4 of node ID)
          uint64_t high_peer_id
          uint32_t peer_ip            IP address of the peer
          uint16_t udp_port           peer UDP port number
          uint16_t tcp_port           peer TCP port number
          unsigned char version       peer contact version
    */

    for(unsigned int i = 0; i < num_entries; i++, peer += 25)
    {
        uint32_t peer_ip = ntohl(*(uint32_t *)&(peer[16]));
        uint16_t udp_port = *(uint16_t *)&(peer[20]);
        uint16_t tcp_port = *(uint16_t *)&(peer[22]);
        unsigned char version = peer[24];

        if(version > 7)
        {
            // Only the 50 closest nodes, please
            uint128_t distance(Kad::get_instance().get_client_id());
            uint128_t peer_id = uint128_t::get_from_buffer(peer);
            distance ^= peer_id;

            if(bootstrap_list.size() < 50 || bootstrap_list.back()->get_distance() > distance)
            {
                Contact *new_peer = new Contact(uint128_t::get_from_buffer(peer),
                                                peer_ip,
                                                udp_port,
                                                tcp_port,
                                                version,
                                                0,
                                                false);

                bool peer_added = false;
                for(std::list<Contact *>::iterator peerIt = bootstrap_list.begin();
                    peerIt != bootstrap_list.end();
                    peerIt++)
                {
                    if((*peerIt)->get_distance() > distance)
                    {
                        bootstrap_list.insert(peerIt, new_peer);
                        peer_added = true;
                        break;
                    }
                }

                if(!peer_added)
                {
                    bootstrap_list.push_back(new_peer);
                }
                else if(bootstrap_list.size() > 50)
                {
                    delete bootstrap_list.back();
                    bootstrap_list.pop_back();
                }
            }
        }
    }
}
Esempio n. 4
0
        void UpdateAI(const uint32 diff)
        {
            if (!UpdateVictim())
                return;

            _DoAggroPulse(diff);
            events.Update(diff);
            ConstructTimer += diff;

            if (me->HasUnitState(UNIT_STAT_CASTING))
                return;

            while (uint32 eventId = events.ExecuteEvent())
            {
                switch (eventId)
                {
                    case EVENT_JET:
                        me->MonsterTextEmote(EMOTE_JETS, 0, true);
                        DoCastAOE(SPELL_FLAME_JETS);
                        events.DelayEvents(5000, 1);
                        events.ScheduleEvent(EVENT_JET, urand(35000, 40000));
                        break;
                    case EVENT_SLAG_POT:
                        if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 100, true))
                        {
                            DoScriptText(SAY_SLAG_POT, me);
                            SlagPotGUID = target->GetGUID();
                            DoCast(target, SPELL_GRAB);
                            events.ScheduleEvent(EVENT_GRAB_POT, 500);
                        }
                        events.ScheduleEvent(EVENT_SLAG_POT, RAID_MODE(30000, 15000), 1);
                        break;
                    case EVENT_GRAB_POT:
                        if (Unit* SlagPotTarget = Unit::GetUnit(*me, SlagPotGUID))
                        {
                            SlagPotTarget->CastCustomSpell(SPELL_GRAB_ENTER_VEHICLE, SPELLVALUE_BASE_POINT0, 1, me, true);
                            events.ScheduleEvent(EVENT_CHANGE_POT, 1000);
                        }
                        break;
                    case EVENT_CHANGE_POT:
                        if (Unit* SlagPotTarget = Unit::GetUnit(*me, SlagPotGUID))
                        {
                            SlagPotTarget->AddAura(SPELL_SLAG_POT, SlagPotTarget);
                            SlagPotTarget->ExitVehicle();
                            SlagPotTarget->CastCustomSpell(SPELL_GRAB_ENTER_VEHICLE, SPELLVALUE_BASE_POINT0, 2, me, true);
                            SlagPotTarget->ClearUnitState(UNIT_STAT_ONVEHICLE); // Hack
                            SlagPotGUID = 0;
                        }
                        break;
                    case EVENT_SCORCH:
                        DoScriptText(RAND(SAY_SCORCH_1, SAY_SCORCH_2), me);
                        if (Unit* target = me->getVictim())
                            me->SummonCreature(NPC_GROUND_SCORCH, *target, TEMPSUMMON_TIMED_DESPAWN, 45000);
                        DoCast(SPELL_SCORCH);
                        events.ScheduleEvent(EVENT_SCORCH, 25000);
                        break;
                    case EVENT_CONSTRUCT:
                    {
                        DoScriptText(SAY_SUMMON, me);
                        if (!creatureList.empty())
                        {
                            std::list<Creature*>::iterator itr = creatureList.begin();
                            std::advance(itr, urand(0, creatureList.size()-1));
                            if (Creature* construct = (*itr))
                            {
                                construct->RemoveAurasDueToSpell(SPELL_FREEZE_ANIM);
                                construct->SetReactState(REACT_AGGRESSIVE);
                                construct->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_STUNNED | UNIT_FLAG_DISABLE_MOVE);
                                construct->AI()->AttackStart(me->getVictim());
                                construct->AI()->DoZoneInCombat();
                                DoCast(me, SPELL_STRENGTH, true);
                                creatureList.erase(itr);
                            }
                        }
                        DoCast(SPELL_ACTIVATE_CONSTRUCT);
                        events.ScheduleEvent(EVENT_CONSTRUCT, RAID_MODE(40000, 30000));
                        break;
                    }
                    case EVENT_BERSERK:
                        DoCast(me, SPELL_BERSERK, true);
                        DoScriptText(SAY_BERSERK, me);
                        break;
                }
            }
            DoMeleeAttackIfReady();
        }
Esempio n. 5
0
void VDAVIOutputSegmentedVideoStream::finish() {
	mbEnded = true;
	if (!mPendingRuns.empty())
		mPendingRuns.back().mbClosed = true;
}
Esempio n. 6
0
void
TrackerHelper::trackMarkers(const std::list<TrackMarkerPtr >& markers,
                             int start,
                             int end,
                             int frameStep,
                             OverlaySupport* overlayInteract)
{
    if ( markers.empty() ) {
        Q_EMIT trackingFinished();
        return;
    }

    TrackerParamsProviderPtr provider = _imp->provider.lock();
    if (!provider) {
        Q_EMIT trackingFinished();
        return;
    }

    NodePtr trackerNode = provider->getTrackerNode();
    if (!trackerNode) {
        Q_EMIT trackingFinished();
        return;
    }

    if (trackerNode->hasMandatoryInputDisconnected()) {
        Q_EMIT trackingFinished();
        return;
    }

    ViewerInstancePtr viewer;
    if (overlayInteract) {
        viewer = overlayInteract->getInternalViewerNode();
    }


    // The channels we are going to use for tracking
    bool enabledChannels[3];
    provider->getTrackChannels(&enabledChannels[0], &enabledChannels[1], &enabledChannels[2]);


    double formatWidth, formatHeight;
    Format f;
    trackerNode->getApp()->getProject()->getProjectDefaultFormat(&f);
    formatWidth = f.width();
    formatHeight = f.height();

    bool autoKeyingOnEnabledParamEnabled = provider->canDisableMarkersAutomatically();

    /// The accessor and its cache is local to a track operation, it is wiped once the whole sequence track is finished.
    boost::shared_ptr<TrackerFrameAccessor> accessor( new TrackerFrameAccessor(trackerNode, enabledChannels, formatHeight) );
    boost::shared_ptr<mv::AutoTrack> trackContext( new mv::AutoTrack( accessor.get() ) );
    std::vector<TrackMarkerAndOptionsPtr > trackAndOptions;
    mv::TrackRegionOptions mvOptions;
    /*
     Get the global parameters for the LivMV track: pre-blur sigma, No iterations, normalized intensities, etc...
     */
    _imp->beginLibMVOptionsForTrack(&mvOptions);

    /*
     For the given markers, do the following:
     - Get the "User" keyframes that have been set and create a LibMV marker for each keyframe as well as for the "start" time
     - Set the "per-track" parameters that were given by the user, that is the mv::TrackRegionOptions
     - t->mvMarker will contain the marker that evolves throughout the tracking
     */
    int trackIndex = 0;
    for (std::list<TrackMarkerPtr >::const_iterator it = markers.begin(); it != markers.end(); ++it, ++trackIndex) {

        if (autoKeyingOnEnabledParamEnabled) {
            (*it)->setEnabledAtTime(start, true);
        }

        TrackMarkerAndOptionsPtr t(new TrackMarkerAndOptions);
        t->natronMarker = *it;

        int mode_i = (*it)->getMotionModelKnob()->getValue();
        mvOptions.mode = motionModelIndexToLivMVMode(mode_i);

        // Set a keyframe on the marker to initialize its position
        {
            KnobDoublePtr centerKnob = (*it)->getCenterKnob();
            std::vector<double> values(2);
            values[0] = centerKnob->getValueAtTime(start, DimIdx(0));
            values[1] = centerKnob->getValueAtTime(start, DimIdx(1));
            centerKnob->setValueAtTimeAcrossDimensions(start, values);
        }

        // For a translation warp, we do not need to add an animation curve for the pattern which stays constant.
        if (mvOptions.mode != libmv::TrackRegionOptions::TRANSLATION) {
            KnobDoublePtr patternCorners[4];
            patternCorners[0] = (*it)->getPatternBtmLeftKnob();
            patternCorners[1] = (*it)->getPatternBtmRightKnob();
            patternCorners[2] = (*it)->getPatternTopRightKnob();
            patternCorners[3] = (*it)->getPatternTopLeftKnob();
            for (int c = 0; c < 4; ++c) {
                KnobDoublePtr k = patternCorners[c];
                std::vector<double> values(2);
                values[0] = k->getValueAtTime(start, DimIdx(0));
                values[1] = k->getValueAtTime(start, DimIdx(1));
                k->setValueAcrossDimensions(values);
            }
        }

        std::set<double> userKeys;
        t->natronMarker->getMasterKeyFrameTimes(ViewIdx(0), &userKeys);

        if ( userKeys.empty() ) {
            // Set a user keyframe on tracking start if the marker does not have any user keys
            t->natronMarker->setKeyFrame(start, ViewSetSpec(0), 0);
        }

        PreviouslyTrackedFrameSet previousFramesOrdered;

        // Make sure to create a marker at the start time
        userKeys.insert(start);


        // Add a libmv marker for all keyframes
        for (std::set<double>::iterator it2 = userKeys.begin(); it2 != userKeys.end(); ++it2) {

            // Add the marker to the markers ordered only if it can contribute to predicting its next position
            if ( ( (frameStep > 0) && (*it2 <= start) ) || ( (frameStep < 0) && (*it2 >= start) ) ) {
                previousFramesOrdered.insert( PreviouslyComputedTrackFrame(*it2, true) );
            }
        }


        //For all already tracked frames which are not keyframes, add them to the AutoTrack too
        std::set<double> centerKeys;
        t->natronMarker->getCenterKeyframes(&centerKeys);

        for (std::set<double>::iterator it2 = centerKeys.begin(); it2 != centerKeys.end(); ++it2) {
            if ( userKeys.find(*it2) != userKeys.end() ) {
                continue;
            }

            // Add the marker to the markers ordered only if it can contribute to predicting its next position
            if ( ( ( (frameStep > 0) && (*it2 < start) ) || ( (frameStep < 0) && (*it2 > start) ) ) ) {
                previousFramesOrdered.insert( PreviouslyComputedTrackFrame(*it2, false) );
            }
        }


        // Taken from libmv, only initialize the filter to this amount of frames (max)
        const int max_frames_to_predict_from = 20;
        std::list<mv::Marker> previouslyComputedMarkersOrdered;

        // Find the first keyframe that's not considered to go before start or end
        PreviouslyTrackedFrameSet::iterator prevFramesIt = previousFramesOrdered.lower_bound(PreviouslyComputedTrackFrame(start, false));
        if (frameStep < 0) {
            if (prevFramesIt != previousFramesOrdered.end()) {
                while (prevFramesIt != previousFramesOrdered.end() && (int)previouslyComputedMarkersOrdered.size() != max_frames_to_predict_from) {

                    mv::Marker mvMarker;

                    TrackerHelperPrivate::natronTrackerToLibMVTracker(true, enabledChannels, *t->natronMarker, trackIndex, prevFramesIt->frame, frameStep, formatHeight, &mvMarker);
                    trackContext->AddMarker(mvMarker);

                    // insert in the front of the list so that the order is reversed
                    previouslyComputedMarkersOrdered.push_front(mvMarker);
                    ++prevFramesIt;
                }
            }
            // previouslyComputedMarkersOrdered is now ordererd by decreasing order
        } else {

            if (prevFramesIt != previousFramesOrdered.end()) {
                while (prevFramesIt != previousFramesOrdered.begin() && (int)previouslyComputedMarkersOrdered.size() != max_frames_to_predict_from) {

                    mv::Marker mvMarker;

                    TrackerHelperPrivate::natronTrackerToLibMVTracker(true, enabledChannels, *t->natronMarker, trackIndex, prevFramesIt->frame, frameStep, formatHeight, &mvMarker);
                    trackContext->AddMarker(mvMarker);

                    // insert in the front of the list so that the order is reversed
                    previouslyComputedMarkersOrdered.push_front(mvMarker);
                    --prevFramesIt;
                }
                if (prevFramesIt == previousFramesOrdered.begin() && (int)previouslyComputedMarkersOrdered.size() != max_frames_to_predict_from) {
                    mv::Marker mvMarker;

                    TrackerHelperPrivate::natronTrackerToLibMVTracker(true, enabledChannels, *t->natronMarker, trackIndex, prevFramesIt->frame, frameStep, formatHeight, &mvMarker);
                    trackContext->AddMarker(mvMarker);

                    // insert in the front of the list so that the order is reversed
                    previouslyComputedMarkersOrdered.push_front(mvMarker);

                }
            }
            // previouslyComputedMarkersOrdered is now ordererd by increasing order
        }


        // There must be at least 1 marker at the start time
        assert( !previouslyComputedMarkersOrdered.empty() );

        // Initialise the kalman state with the marker at the position

        std::list<mv::Marker>::iterator mIt = previouslyComputedMarkersOrdered.begin();
        t->mvState.Init(*mIt, frameStep);
        ++mIt;
        for (; mIt != previouslyComputedMarkersOrdered.end(); ++mIt) {
            mv::Marker predictedMarker;
            if ( !t->mvState.PredictForward(mIt->frame, &predictedMarker) ) {
                break;
            } else {
                t->mvState.Update(*mIt);
            }
        }


        t->mvOptions = mvOptions;
        trackAndOptions.push_back(t);
    }
    
    
    /*
     Launch tracking in the scheduler thread.
     */
    boost::shared_ptr<TrackArgs> args( new TrackArgs(start, end, frameStep, trackerNode->getApp()->getTimeLine(), viewer, trackContext, accessor, trackAndOptions, formatWidth, formatHeight, autoKeyingOnEnabledParamEnabled) );
    _imp->scheduler->track(args);
} // TrackerHelper::trackMarkers
Esempio n. 7
0
 void CountTargets(std::list<WorldObject*>& targetList)
 {
     _didHit = !targetList.empty();
 }
Esempio n. 8
0
std::string StringUtil::getXMLData2(std::string xml,std::string xml_uppercase, std::list<std::string> listnodes)
{
	if(listnodes.empty())
		return xml;

	long elements = 0;
	std::string node = *(listnodes.begin());
	listnodes.pop_front();

	std::vector<std::string> vec = StringUtil::split(node,"=");

	if(vec.size() == 1)
	{
		elements = 1;
	}
	else
	{
		elements = StringUtil::longValue(vec[1]) + 1;
	}

	node = vec[0];

	std::string node_ini = "<" + node;
	std::string node_fin = "</" + node;

	while(elements > 1)
	{
		elements--;


		std::string::size_type pos_fin = xml_uppercase.find(node_fin);
		if(pos_fin == std::string::npos)
		{
			throw new exceptions::XMLException(-1,"Bad tag format1: " + node);
		}

		std::string::size_type pos_fin_mayor = xml_uppercase.find(">",pos_fin);
		if(pos_fin_mayor == std::string::npos)
		{
			throw new exceptions::XMLException(-1,"Bad tag format2: " + node);
		}

		xml = xml.substr(pos_fin_mayor + 1);
		xml_uppercase = xml_uppercase.substr(pos_fin_mayor + 1);
	}

	std::string::size_type pos_ini = xml_uppercase.find(node_ini);
	std::string::size_type pos_fin = xml_uppercase.find(node_fin);

	if((pos_ini == std::string::npos)||(pos_fin == std::string::npos))
	{
		throw new exceptions::XMLException(-1,"Bad tag name: " + node);
	}

	std::string::size_type pos_ini_mayor = xml_uppercase.find(">",pos_ini);
	
	if(pos_ini_mayor == std::string::npos)
	{
		throw new exceptions::XMLException(-1,"Bad tag format3: " + node);
	}

	xml = xml.substr(pos_ini_mayor + 1,pos_fin - pos_ini_mayor - 1);
	xml_uppercase = xml_uppercase.substr(pos_ini_mayor + 1,pos_fin - pos_ini_mayor - 1);

	return getXMLData2(xml,xml_uppercase,listnodes);
}
matcher_status single_char_test_matcher::match(const std::list<char>& input)
{
    assert(!input.empty());
    return match(input.begin(), input.end());
}
Esempio n. 10
0
// Use Deb's "Fast Nondominated Sorting" (2002)
// Ref.: "A fast and elitist multiobjective genetic algorithm: NSGA-II"
void ranking(const std::list<solution> &population, std::vector< std::list<solution> > *output, bool feasible){
	if( population.empty() ) return;
	vector<solution> solutions(population.begin(), population.end() );

	vector< list<int> > intOutput;
	intOutput.resize(solutions.size() + 2);  // start from 1, end with null Qi 
	output->resize(1);

	// record each solutions' dominated solution
	vector< list<int> > dominated;
	dominated.resize(solutions.size());

	// record # of solutions dominate this solution
	vector<int> counter;
	counter.resize(solutions.size());

	// record the rank of solutions
	vector<int> rank;
	rank.resize(solutions.size());

	
	// for each solution
	for(unsigned int p = 0; p < solutions.size(); p++){
		for(unsigned int q = 0; q < solutions.size(); q++){
			if( feasible ){
				if( solution::fdominate(solutions[p], solutions[q]) ){
					dominated[p].push_back(q);  // Add q to the set of solutions dominated by p
				}else if( solution::fdominate(solutions[q], solutions[p]) ){
					counter[p]++;
				}
			}else{
				if( solution::idominate(solutions[p], solutions[q]) ){
					dominated[p].push_back(q);  // Add q to the set of solutions dominated by p
				}else if( solution::idominate(solutions[q], solutions[p]) ){
					counter[p]++;
				}
			}
		}
		
		if(counter[p] == 0){  // p belongs to the first front
			rank[p] = 1;
			intOutput[1].push_back(p);
			(*output)[0].push_back(solutions[p]);
		}
	}

	int curRank = 1;
	while( intOutput[curRank].size() > 0 ){
		list<int> Qi;  // Used to store the members of the next front
		list<solution> Qs;

		for(list<int>::iterator p = intOutput[curRank].begin(); p != intOutput[curRank].end(); p++){
		for(list<int>::iterator q = dominated[(*p)].begin(); q != dominated[(*p)].end(); q++){
			counter[(*q)]--;
			if(counter[(*q)] == 0){  // q belongs to the next front
				rank[(*q)] = curRank + 1;
				Qi.push_back(*q);
				Qs.push_back(solutions[(*q)]);
			}
		}}

		curRank++;
		intOutput[curRank] = Qi;
		if(Qi.size() > 0) output->push_back(Qs);
	}

	// remove duplicate solution in same rank
	for(unsigned int rank = 0; rank < output->size(); ++rank){
		(*output)[rank].sort();
		(*output)[rank].unique();
	}
}
Esempio n. 11
0
bool CLocalFileSystem::RecursiveDelete(std::list<wxString> dirsToVisit, wxWindow* parent)
{
	// Under Windows use SHFileOperation to delete files and directories.
	// Under other systems, we have to recurse into subdirectories manually
	// to delete all contents.

#ifdef __WXMSW__
	// SHFileOperation accepts a list of null-terminated strings. Go through all
	// paths to get the required buffer length

	;
	int len = 1; // String list terminated by empty string

	for (std::list<wxString>::const_iterator const_iter = dirsToVisit.begin(); const_iter != dirsToVisit.end(); const_iter++)
		len += const_iter->Length() + 1;

	// Allocate memory
	wxChar* pBuffer = new wxChar[len];
	wxChar* p = pBuffer;

	for (std::list<wxString>::iterator iter = dirsToVisit.begin(); iter != dirsToVisit.end(); iter++)
	{
		wxString& path = *iter;
		if (path.Last() == wxFileName::GetPathSeparator())
			path.RemoveLast();
		if (GetFileType(path) == unknown)
			continue;

		_tcscpy(p, path);
		p += path.Length() + 1;
	}
	if (p != pBuffer)
	{
		*p = 0;

		// Now we can delete the files in the buffer
		SHFILEOPSTRUCT op;
		memset(&op, 0, sizeof(op));
		op.hwnd = parent ? (HWND)parent->GetHandle() : 0;
		op.wFunc = FO_DELETE;
		op.pFrom = pBuffer;

		if (parent)
		{
			// Move to trash if shift is not pressed, else delete
			op.fFlags = wxGetKeyState(WXK_SHIFT) ? 0 : FOF_ALLOWUNDO;
		}
		else
			op.fFlags = FOF_NOCONFIRMATION;

		SHFileOperation(&op);
	}
	delete [] pBuffer;

	return true;
#else
	if (parent)
	{
		if (wxMessageBox(_("Really delete all selected files and/or directories?"), _("Confirmation needed"), wxICON_QUESTION | wxYES_NO, parent) != wxYES)
			return true;
	}

	for (std::list<wxString>::iterator iter = dirsToVisit.begin(); iter != dirsToVisit.end(); iter++)
	{
		wxString& path = *iter;
		if (path.Last() == wxFileName::GetPathSeparator() && path != wxFileName::GetPathSeparator())
			path.RemoveLast();
	}

	bool encodingError = false;

	// Remember the directories to delete after recursing into them
	std::list<wxString> dirsToDelete;

	// Process all dirctories that have to be visited
	while (!dirsToVisit.empty())
	{
		const wxString path = dirsToVisit.front();
		dirsToVisit.pop_front();
		dirsToDelete.push_front(path);

		if (GetFileType(path) != dir)
		{
			wxRemoveFile(path);
			continue;
		}

		wxDir dir;
		if (!dir.Open(path))
			continue;

		// Depending on underlying platform, wxDir does not handle
		// changes to the directory contents very well.
		// See bug [ 1946574 ]
		// To work around this, delete files after enumerating everything in current directory
		std::list<wxString> filesToDelete;

		wxString file;
		for (bool found = dir.GetFirst(&file); found; found = dir.GetNext(&file))
		{
			if (file == _T(""))
			{
				encodingError = true;
				continue;
			}

			const wxString& fullName = path + wxFileName::GetPathSeparator() + file;

			if (CLocalFileSystem::GetFileType(fullName) == CLocalFileSystem::dir)
				dirsToVisit.push_back(fullName);
			else
				filesToDelete.push_back(fullName);
		}

		// Delete all files and links in current directory enumerated before
		for (std::list<wxString>::const_iterator iter = filesToDelete.begin(); iter != filesToDelete.end(); iter++)
			wxRemoveFile(*iter);
	}

	// Delete the now empty directories
	for (std::list<wxString>::const_iterator iter = dirsToDelete.begin(); iter != dirsToDelete.end(); iter++)
		wxRmdir(*iter);

	return !encodingError;
#endif
}
void eventpos::reinit(real time_, rvec r, 
                      const deque<mol> &meas_mols, 
                      const deque<mol> &ref_mols, t_pbc *pbc,
                      matrix ref_trans,
                      rvec com_meas_tot, rvec com_meas_tot_dx,
                      rvec com_ref_tot, rvec com_ref_tot_dx,
                      real weight_sigma, int closest_n, event_type type_,
                      event_direction evdir_,
                      bool calc_r_, std::list<anchor> &spare_anchor_list,
                      real ref_dist_sq_)
{
    event_happened=false;
    checked=true; // because we don't want cumulative dxes to start at t=0
    time=time_;
    type=type_;

    ref_dist_sq = ref_dist_sq_;

    // remove all the existing anchors
    spare_anchor_list.splice(spare_anchor_list.begin(), anchors);

    if (weight_sigma > 0)
    {
        weight_sigmasq = weight_sigma*weight_sigma;
        use_weights=true;
        if (closest_n > 0)
        {
            gmx_fatal(FARGS, "ERRROR: both closest_n >0 and weight_sigma >0");
        }
    }
    else if (closest_n > 0)
    {
        use_weights=true;
    }
    else
    {
        weight_sigmasq=0;
        use_weights=false;
    }
        
    weight_norm = 1./sqrt(2.*M_PI*weight_sigmasq);

    real com_weight=0.;

    evdir=evdir_;

    anchor_d=0.;

    if (use_weights)
    {
        if (closest_n > 0)
        {
            const mol* closest[closest_n];
            double dsq_max[closest_n];
            for(int i=0;i<closest_n;i++)
            {
                closest[i] = NULL;
                dsq_max[i] = 1e20;
            }
            int k=0;

            // now find the closest n mols
            for(deque<mol>::const_iterator i=ref_mols.begin(); 
                i!=ref_mols.end(); ++i)
            {
                rvec dxvec;
                rvec lcom;
                i->get_com(lcom);

                // calculate distance vector
                pbc_dx(pbc, r, lcom, dxvec); 
                // and calculate distance to base weights on
                real dsq;
                switch(evdir)
                {
                    case evdir_xyz:
                    default:
                        dsq = (dxvec[XX]*dxvec[XX] + dxvec[YY]*dxvec[YY] + 
                               dxvec[ZZ]*dxvec[ZZ]);
                        break;
                    case evdir_xy:
                        dsq = dxvec[XX]*dxvec[XX] + dxvec[YY]*dxvec[YY];
                        break;
                    case evdir_z:
                        dsq = dxvec[ZZ]*dxvec[ZZ];
                        break;
                }
                k++;
                /* check whether it's closer than any before */
                if (dsq < dsq_max[closest_n-1])
                {
                    int j;
                    for(j=closest_n - 1; j >= 0; j--)
                    {
                        if (dsq < dsq_max[j])
                        {
                            // shift everything one place up
                            if (j < closest_n - 1)
                            {
                                dsq_max[j+1] = dsq_max[j];
                                closest[j+1] = closest[j];
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    // we always overshoot by 1
                    j++;
                    dsq_max[j] = dsq;
                    closest[j] = &(*i);
                }
            }
            for(int i=0;i<closest_n;i++)
            {
                /*printf("closest[%d], dsq=%g, p=%p\n", i, sqrt(dsq_max[i]),
                       closest[i]);
                fflush(stdout);*/
                // add the anchors
                if (spare_anchor_list.empty())
                {
                    for(int i=0;i<1000;i++)
                    {
                        spare_anchor_list.push_back(anchor());
                    }
                }

                rvec lcom;
                closest[i]->get_com(lcom);
                std::list<anchor>::iterator newelem=spare_anchor_list.begin();
                newelem->reinit(closest[i], 1., lcom);
                anchors.splice(anchors.begin(), spare_anchor_list, newelem);
                com_weight += 1.;
                anchor_d += sqrt(dsq_max[i]);
            }
            anchor_d /= com_weight;
        }
        else
        {
            for(deque<mol>::const_iterator i=ref_mols.begin(); 
                i!=ref_mols.end(); ++i)
            {
                rvec dxvec;
                rvec lcom;
                i->get_com(lcom);

                // calculate distance vector
                pbc_dx(pbc, r, lcom, dxvec); 
                // and calculate distance to base weights on
                real dsq;
                switch(evdir)
                {
                    case evdir_xyz:
                    default:
                        dsq = (dxvec[XX]*dxvec[XX] + dxvec[YY]*dxvec[YY] + 
                               dxvec[ZZ]*dxvec[ZZ]);
                        break;
                    case evdir_xy:
                        dsq = dxvec[XX]*dxvec[XX] + dxvec[YY]*dxvec[YY];
                        break;
                    case evdir_z:
                        dsq = dxvec[ZZ]*dxvec[ZZ];
                        break;
                }

                real weight=weightfn( dsq );

                if (weight > 0.01)
                {
                    if (spare_anchor_list.empty())
                    {
                        for(int i=0;i<1000;i++)
                        {
                            spare_anchor_list.push_back(anchor());
                        }
                    }
                    // add the anchors
                    std::list<anchor>::iterator newelem=spare_anchor_list.begin();
                    newelem->reinit(&(*i), weight, lcom);
                    anchors.splice(anchors.begin(), spare_anchor_list, newelem);
                    //anchors.push_back(anchor(&(*i), weight, lcom));
                    com_weight += weight;
                    anchor_d += sqrt(dsq) * weight;
                }
            }
            anchor_d /= com_weight;
        }
        if (com_weight == 0.)
        {
            /*printf("ERRRORRREEEERROOORRR no weight\n");*/
            printf("WARNING no weight. Using total  COM as ref point\n");
            com_weight=1.;
        }
    }
    else
    {
        com_weight=1.;
    }

    { // calculate position relative to reference pos.
        rvec dxvec;

        pbc_dx(pbc, r, com_ref_tot, dxvec); 
        // now do reference transformation
        mvmul(ref_trans, dxvec, refp);

        //z_val_start=dxvec[ZZ];
        real_start_pos[XX] = r[XX];
        real_start_pos[YY] = r[YY];
        real_start_pos[ZZ] = r[ZZ];
    }

    // calculate r_val
    if (calc_r_)
    {
        r_val=0.;
#if 0
        r_val=FLT_MAX;
        bool found0=false;
        for(list<mol>::iterator i=meas_mols.begin(); i!=meas_mols.end(); ++i)
        {
            // calcualte the closest distance > 0
            rvec dxvec;
            rvec lcom;
            i->get_com(lcom);
            if (lcom[XX] != r[XX] || lcom[YY]!=r[YY] || lcom[ZZ]!=r[ZZ] )
            {

                // calculate distance vector
                pbc_dx(pbc, r, lcom, dxvec); 
                // and calculate distance to base weights on
                real dsq;
                switch(evdir)
                {
                    case evdir_xyz:
                    default:
                        dsq = (dxvec[XX]*dxvec[XX] + dxvec[YY]*dxvec[YY] + 
                               dxvec[ZZ]*dxvec[ZZ]);
                        break;
                    case evdir_xy:
                        dsq = dxvec[XX]*dxvec[XX] + dxvec[YY]*dxvec[YY];
                        break;
                    case evdir_z:
                        dsq = dxvec[ZZ]*dxvec[ZZ];
                        break;
                }
                if (dsq > 0 && dsq < r_val)
                {
#ifdef GMX_DOUBLE
                    r_val = sqrt(dsq);
#else
                    r_val = sqrtf(dsq);
#endif
                }
            }
            else
                found0=true;
        }
        //printf("r_val = %g\n", r_val);
        if (!found0)
        {
            printf("0 not found!\n");
            exit(1);
        }
        if (r_val > 1e5)
        {
            printf("r_val=%g!\n",r_val);
            exit(1);
        }
#endif
    }
    else
    {
        r_val=0.;
    }

    com_dx[XX] = com_dx[YY] = com_dx[ZZ] = 0;
    dx[XX] = dx[YY] = dx[ZZ] = 0;
#if 0
    printf(" r=(%g,%g,%g)\n", r[XX], r[YY], r[ZZ]);
#endif
}
Esempio n. 13
0
        void UpdateAI(uint32 diff) override
        {
            events.Update(diff);
            while (uint32 eventId = events.ExecuteEvent())
            {
                switch(eventId)
                {
                case EVENT_START: //Begin script if playersInvolved is not empty
                {
                    updatePlayerList();
                    if (playersInvolved.empty())
                        events.ScheduleEvent(1, 600);
                    else
                    {
                        me->MonsterSay("Keep those creatures at bay while I meditate. We'll soon have the answers we seek...", LANG_UNIVERSAL, 0);
                        me->SetReactState(REACT_PASSIVE);
                        timer = 0;
                        events.ScheduleEvent(EVENT_SPAWN_MOBS, 5000); //spawn mobs
                        events.ScheduleEvent(EVENT_PROGRESS, 1000); //update time
                        events.ScheduleEvent(EVENT_END, 90000); //end quest
                    }
                    break;
                }
                case EVENT_SPAWN_MOBS: //Spawn 3 mobs
                {
                    updatePlayerList();
                    for(int i = 0; i < std::max((int)playersInvolved.size()*3,3); i++)
                    {
                        if (TempSummon* temp = me->SummonCreature(59637, 1144.55f, 3435.65f, 104.97f, 3.3f,TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 10000))
                        {
                            if (temp->AI())
                                temp->AI()->AttackStart(me);

                            temp->AddThreat(me, 250.0f);
                            temp->GetMotionMaster()->Clear();
                            temp->GetMotionMaster()->MoveChase(me);
                        }
                    }
                    events.ScheduleEvent(EVENT_SPAWN_MOBS, 20000); //spawn mobs
                    break;
                }
                case EVENT_PROGRESS: //update energy
                {
                    timer++;

                    if (timer == 25 && !lifei)
                    {
                        if (lifei = me->SummonCreature(54856, 1130.162231f, 3435.905518f, 105.496597f, 0.0f,TEMPSUMMON_MANUAL_DESPAWN))
                            lifei->MonsterSay("The way of the Tushui... enlightenment through patience and mediation... the principled life", LANG_UNIVERSAL, 0);
                    }

                    if (timer == 30)
                        if (lifei)
                            lifei->MonsterSay("It is good to see you again, Aysa. You've come with respect, and so I shall give you the answers you seek.", LANG_UNIVERSAL, 0);

                    if (timer == 42)
                        if (lifei)
                            lifei->MonsterSay("Huo, the spirit of fire, is known for his hunger. He wants for tinder to eat. He needs the caress of the wind to rouse him.", LANG_UNIVERSAL, 0);

                    if (timer == 54)
                        if (lifei)
                            lifei->MonsterSay("If you find these things and bring them to his cave, on the far side of Wu-Song Village, you will face a challenge within.", LANG_UNIVERSAL, 0);

                    if (timer == 66)
                        if (lifei)
                            lifei->MonsterSay("Overcome that challenge, and you shall be graced by Huo's presence. Rekindle his flame, and if your spirit is pure, he shall follow you.", LANG_UNIVERSAL, 0);

                    if (timer == 78)
                        if (lifei)
                            lifei->MonsterSay("Go, children. We shall meet again very soon.", LANG_UNIVERSAL, 0);

                    if (timer == 85)
                    {
                        if (lifei)
                            lifei->UnSummon();

                        lifei = NULL;
                    }

                    updatePlayerList();
                    for (auto player: playersInvolved)
                    {
                        if (!player->HasAura(116421))
                            player->CastSpell(player, 116421);

                        player->ModifyPower(POWER_ALTERNATE_POWER, timer/25);
                        player->SetMaxPower(POWER_ALTERNATE_POWER, 90);
                    }

                    events.ScheduleEvent(EVENT_PROGRESS, 1000);
                    break;
                }
                case EVENT_END: //script end
                {
                    if (lifei)
                    {
                        lifei->UnSummon();
                        lifei = NULL;
                    }
                    events.ScheduleEvent(EVENT_START, 10000);
                    events.CancelEvent(EVENT_SPAWN_MOBS);
                    events.CancelEvent(EVENT_PROGRESS);
                    me->MonsterSay("And so our path lays before us. Speak to Master Shang Xi, he will tell you what comes next.", LANG_UNIVERSAL, 0);
                    updatePlayerList();
                    me->SetReactState(REACT_DEFENSIVE);
                    for(auto player: playersInvolved)
                    {
                        player->KilledMonsterCredit(54856, 0);
                        player->RemoveAura(116421);
                    }
                    break;
                }
                }
            }
        }
Esempio n. 14
0
int hexchat_plugin_deinit(hexchat_plugin *plugin_handle)
{
	/******************************************/
	/****** Remove the Icon from the tray *****/
	/******************************************/
	StopBlink(g_hXchatWnd, 1, g_hIcons[0]);
	RemoveIcon(g_hXchatWnd, 1);
	
	/*******************************************/
	/*******************************************/
	/*******************************************/
	if(g_dwPrefs & (1<<PREF_DNSIT))
	{
		DWORD dwStyle;
		dwStyle = GetWindowLong(g_hXchatWnd, GWL_STYLE);
		dwStyle &= ~(1<<WS_CHILD);
		SetWindowLongPtr(g_hXchatWnd, GWL_STYLE, (LONG_PTR)dwStyle);
		SetWindowLongPtr(g_hXchatWnd, GWL_HWNDPARENT, NULL);
	}

	/******************************************/
	/****** Unload our resources **************/
	/******************************************/
	DestroyMenu(g_hTrayMenu);

	for(int i = 0; i <= 11; i++)
	{
		DestroyIcon(g_hIcons[i]);
	}

	/******************************************/
	/****** Remove our window hook ************/
	/******************************************/
	SetWindowLongPtr(g_hXchatWnd, GWLP_WNDPROC, (LONG_PTR)g_hOldProc);

	/******************************************/
	/****** Remove our hotkey, and destroy ****/
	/****** the window that receives its   ****/
	/****** messages                       ****/
	/******************************************/
	UnregisterHotKey(g_hHotkeyWnd, 1);
	DestroyWindow(g_hHotkeyWnd);
	DestroyWindow(g_hPrefDlg);

	/******************************************/
	/************* Clean up Isle 7 ************/
	/******************************************/
	if(sdAlertNum())
	{
		sdCloseAlerts();
	}
	/******************************************/
	/****** remove our hexchat_hook_*s **********/
	/******************************************/
	while(!g_vHooks.empty())
	{
		if(g_vHooks.back() != NULL)
		{
			hexchat_unhook(ph, g_vHooks.back());
		}
		g_vHooks.pop_back();
	}

	return 1;
}
Esempio n. 15
0
 void clear() noexcept {
     assert(!m_chunks.empty());
     m_chunks.erase(std::next(m_chunks.begin()), m_chunks.end());
     m_chunks.front().clear();
 }
Esempio n. 16
0
bool Pickup::do_pickup( const tripoint &pickup_target_arg, bool from_vehicle,
                        std::list<int> &indices, std::list<int> &quantities, bool autopickup )
{
    bool got_water = false;
    int cargo_part = -1;
    vehicle *veh = nullptr;
    bool weight_is_okay = ( g->u.weight_carried() <= g->u.weight_capacity() );
    bool volume_is_okay = ( g->u.volume_carried() <= g->u.volume_capacity() );
    bool offered_swap = false;
    // Convert from player-relative to map-relative.
    tripoint pickup_target = pickup_target_arg + g->u.pos();
    // Map of items picked up so we can output them all at the end and
    // merge dropping items with the same name.
    PickupMap mapPickup;

    if( from_vehicle ) {
        const cata::optional<vpart_reference> vp = g->m.veh_at( pickup_target ).part_with_feature( "CARGO",
                false );
        if( !vp ) {
            // Can't find the vehicle! bail out.
            add_msg( m_info, _( "Lost track of vehicle." ) );
            return false;
        }
        veh = &vp->vehicle();
        cargo_part = vp->part_index();
    }

    bool problem = false;
    while( !problem && g->u.moves >= 0 && !indices.empty() ) {
        // Pulling from the back of the (in-order) list of indices insures
        // that we pull from the end of the vector.
        int index = indices.back();
        int quantity = quantities.back();
        // Whether we pick the item up or not, we're done trying to do so,
        // so remove it from the list.
        indices.pop_back();
        quantities.pop_back();

        item *target = nullptr;
        if( from_vehicle ) {
            target = g->m.item_from( veh, cargo_part, index );
        } else {
            target = g->m.item_from( pickup_target, index );
        }

        if( target == nullptr ) {
            continue; // No such item.
        }

        problem = !pick_one_up( pickup_target, *target, veh, cargo_part, index, quantity,
                                got_water, offered_swap, mapPickup, autopickup );
    }

    if( !mapPickup.empty() ) {
        show_pickup_message( mapPickup );
    }

    if( got_water ) {
        add_msg( m_info, _( "You can't pick up a liquid!" ) );
    }
    if( weight_is_okay && g->u.weight_carried() > g->u.weight_capacity() ) {
        add_msg( m_bad, _( "You're overburdened!" ) );
    }
    if( volume_is_okay && g->u.volume_carried() > g->u.volume_capacity() ) {
        add_msg( m_bad, _( "You struggle to carry such a large volume!" ) );
    }

    return !problem;
}
Esempio n. 17
0
void processTree() {
    TriSet::iterator tit;
    ClassMap::iterator cit, cit2;
    int c, cOld;
    NTriangulation* t;

    for (NPacket* p = tree; p; p = p->nextTreePacket())
        if (p->type() == PACKET_TRIANGULATION) {
            // A triangulation to process.
            t = static_cast<NTriangulation*>(p);
            fprintf(stderr, "Processing %s ...\n", t->label().c_str());
            nTris++;

            nonMin = false;
            orig = static_cast<NTriangulation*>(p);
            equivs.clear();
            equivs.insert(orig);

            tryMovesUp(orig, argUp);

            if (nonMin) {
                allNonMin.push_back(orig);
                nNonMin++;
                continue;
            }

            // In equivs we now have a list of all triangulations
            // equivalent to orig.

            // Is this an equivalence class we're already seen?
            for (tit = equivs.begin(); tit != equivs.end(); tit++) {
                cit = eClass.find(*tit);
                if (cit != eClass.end())
                    break;
            }
            if (tit != equivs.end()) {
                // We found an equivalence class.  Insert everything we
                // haven't seen yet, and merge the classes of everything
                // we have.
                c = cit->second;
                for (tit = equivs.begin(); tit != equivs.end(); tit++) {
                    cit = eClass.find(*tit);
                    if (cit == eClass.end())
                        eClass.insert(std::make_pair(*tit, c));
                    else if (cit->second != c) {
                        // Merge the two equivalence classes.
                        cOld = cit->second;
                        for (cit = eClass.begin(); cit != eClass.end(); cit++)
                            if (cit->second == cOld)
                                cit->second = c;
                        nClasses--;
                    }
                }
            } else {
                // No such equivalence class.  Insert everything.
                c = nextClass++;
                for (tit = equivs.begin(); tit != equivs.end(); tit++)
                    eClass.insert(std::make_pair(*tit, c));
                nClasses++;
            }
        }

    // Finished progress reporting.
    fprintf(stderr, "\n");

    // Write the summary of results.
    if (! allNonMin.empty()) {
        printf("NON-MINIMAL TRIANGULATIONS:\n\n");
        for (std::list<NTriangulation*>::const_iterator it = allNonMin.begin();
                it != allNonMin.end(); it++)
            printf("    %s\n", (*it)->label().c_str());
        printf("\n");
    }

    if (nClasses) {
        printf("EQUIVALENCE CLASSES:\n\n");

        if (outFile) {
            newTree = new NContainer();
            newTree->setLabel("Equivalence Classes");
        }

        int classNum = 1;
        std::string className;
        NContainer* classCnt = 0;

        for (cit = eClass.begin(); cit != eClass.end(); cit++)
            if (cit->second >= 0) {
                // The first triangulation of a new equivalence class.
                c = cit->second;

                std::ostringstream s;
                s << "Class " << classNum << " : " <<
                  cit->first->homology().str();
                className = s.str();
                classNum++;

                printf("%s\n\n", className.c_str());
                if (outFile) {
                    classCnt = new NContainer();
                    classCnt->setLabel(className);
                    newTree->insertChildLast(classCnt);
                }

                // Find the triangulations in this class, and erase the
                // class as we go.
                for (cit2 = cit; cit2 != eClass.end(); cit2++)
                    if (cit2->second == c) {
                        printf("    %s\n",
                               cit2->first->label().c_str());
                        if (outFile) {
                            t = new NTriangulation(*(cit2->first));
                            t->setLabel(cit2->first->label());
                            classCnt->insertChildLast(t);
                        }

                        cit2->second = -1;
                    }

                printf("\n");
            }
    }

    printf("Final statistics:\n");
    printf("    Triangulations read:        %ld\n", nTris);
    printf("    Equivalence classes:        %ld\n", nClasses);
    printf("    New triangulations:         %ld\n", nNew);
    printf("    Non-minimal triangulations: %ld\n", nNonMin);
}
	bool isEmpty()
	{
		return graphNodesList.empty();
	}
Esempio n. 19
0
CharBitmap *
TextRendererPrivate::createCharacter(QChar c)
{
#ifdef NATRON_TEXT_RENDERER_USE_CACHE

    ushort unic = c.unicode();
    //c is already in the cache
    BitmapCache::iterator it = _bitmapsCache.find(unic);
    if ( it != _bitmapsCache.end() ) {
        return it.value();
    }
#endif

    if ( _usedTextures.empty() ) {
        newTransparentTexture();
    }

    GLuint texture = _usedTextures.back();
    GLsizei width = _fontMetrics.width(c);
    GLsizei height = _fontMetrics.height();

    //render into a new transparant pixmap using QPainter
    QImage image(width, height, QImage::Format_ARGB32_Premultiplied);
    image.fill(Qt::transparent);
    QPainter painter;
    painter.begin(&image);
    painter.setRenderHints(QPainter::HighQualityAntialiasing
                           | QPainter::TextAntialiasing);
    painter.setFont(_font);
    painter.setPen(Qt::white);

    painter.drawText(0, _fontMetrics.ascent(), c);
    painter.end();


    //fill the texture with the QImage
    image = QGLWidget::convertToGLFormat(image);
    glCheckError();

    GLuint savedTexture;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&savedTexture);
    glBindTexture(GL_TEXTURE_2D, texture);
    assert( glIsTexture(texture) );
    glTexSubImage2D( GL_TEXTURE_2D, 0, _xOffset, _yOffset, width, height, GL_RGBA,
                     GL_UNSIGNED_BYTE, image.bits() );
    glCheckError();
    glBindTexture(GL_TEXTURE_2D, savedTexture);


    CharBitmap *character = new CharBitmap;
    character->texID = texture;

    character->w = width;
    character->h = height;

    character->xTexCoords[0] = (GLfloat)_xOffset / TEXTURE_SIZE;
    character->xTexCoords[1] = (GLfloat)(_xOffset + width) / TEXTURE_SIZE;

    character->yTexCoords[0] = (GLfloat)_yOffset / TEXTURE_SIZE;
    character->yTexCoords[1] = (GLfloat)(_yOffset + height) / TEXTURE_SIZE;

#ifdef NATRON_TEXT_RENDERER_USE_CACHE
    BitmapCache::iterator retIt = _bitmapsCache.insert(unic, character); // insert a new charactr
    assert( retIt != _bitmapsCache.end() );
#endif

    _xOffset += width;
    if (_xOffset + width >= TEXTURE_SIZE) {
        _xOffset = 1;
        _yOffset += height;
    }
    if (_yOffset + height >= TEXTURE_SIZE) {
        newTransparentTexture();
        _yOffset = 1;
    }

#ifdef NATRON_TEXT_RENDERER_USE_CACHE

    return retIt.value();
#else

    return character;
#endif
} // createCharacter
Esempio n. 20
0
void ExecutionPath::checkScope(const Token *tok, std::list<ExecutionPath *> &checks)
{
    if (!tok || tok->str() == "}" || checks.empty())
        return;

    const std::auto_ptr<ExecutionPath> check(checks.front()->copy());

    for (; tok; tok = tok->next()) {
        // might be a noreturn function..
        if (Token::simpleMatch(tok->tokAt(-2), ") ; }") &&
            Token::Match(tok->linkAt(-2)->tokAt(-2), "[;{}] %var% (") &&
            tok->linkAt(-2)->previous()->varId() == 0) {
            ExecutionPath::bailOut(checks);
            return;
        }

        if (tok->str() == "}")
            return;

        if (tok->str() == "break") {
            ExecutionPath::bailOut(checks);
            return;
        }

        if (Token::simpleMatch(tok, "while (")) {
            // parse condition
            if (checks.size() > 10 || check->parseCondition(*tok->tokAt(2), checks)) {
                ExecutionPath::bailOut(checks);
                return;
            }

            // skip "while (fgets()!=NULL)"
            if (Token::simpleMatch(tok, "while ( fgets (")) {
                const Token *tok2 = tok->linkAt(3);
                if (Token::simpleMatch(tok2, ") ) {")) {
                    tok = tok2->linkAt(2);
                    if (!tok)
                        break;
                    continue;
                }
            }
        }

        // goto/setjmp/longjmp => bailout
        else if (Token::Match(tok, "goto|setjmp|longjmp")) {
            ExecutionPath::bailOut(checks);
            return;
        }

        // ?: => bailout
        if (tok->str() == "?") {
            for (const Token *tok2 = tok; tok2 && tok2->str() != ";"; tok2 = tok2->next()) {
                if (tok2->varId() > 0)
                    ExecutionPath::bailOutVar(checks, tok2->varId());
            }
        }

        // for/while/switch/do .. bail out
        else if (Token::Match(tok, "for|while|switch|do")) {
            // goto {
            const Token *tok2 = tok->next();
            if (tok2 && tok2->str() == "(")
                tok2 = tok2->link();
            if (tok2 && tok2->str() == ")")
                tok2 = tok2->next();
            if (!tok2 || tok2->str() != "{") {
                ExecutionPath::bailOut(checks);
                return;
            }

            if (tok->str() == "switch") {
                // parse condition
                if (checks.size() > 10 || check->parseCondition(*tok->next(), checks)) {
                    ExecutionPath::bailOut(checks);
                    return;
                }

                // what variable ids should the if be counted for?
                std::set<unsigned int> countif;

                std::list<ExecutionPath *> newchecks;

                for (const Token* tok3 = tok2->next(); tok3; tok3 = tok3->next()) {
                    if (tok3->str() == "{")
                        tok3 = tok3->link();
                    else if (tok3->str() == "}")
                        break;
                    else if (tok3->str() == "case" &&
                             !Token::Match(tok3, "case %num% : ; case")) {
                        parseIfSwitchBody(tok3, checks, newchecks, countif);
                    }
                }

                // Add newchecks to checks..
                std::copy(newchecks.begin(), newchecks.end(), std::back_inserter(checks));

                // Increase numberOfIf
                std::list<ExecutionPath *>::iterator it;
                for (it = checks.begin(); it != checks.end(); ++it) {
                    if (countif.find((*it)->varId) != countif.end())
                        (*it)->numberOfIf++;
                }
            }
            // no switch
            else {
                for (const Token *tok3 = tok; tok3 && tok3 != tok2; tok3 = tok3->next()) {
                    if (tok3->varId())
                        ExecutionPath::bailOutVar(checks, tok3->varId());
                }

                // it is not certain that a for/while will be executed:
                for (std::list<ExecutionPath *>::iterator it = checks.begin(); it != checks.end();) {
                    if ((*it)->numberOfIf > 0)
                        checks.erase(it++);
                    else
                        ++it;
                }

                // #2231 - loop body only contains a conditional initialization..
                if (Token::simpleMatch(tok2->next(), "if (")) {
                    // Start { for the if block
                    const Token *tok3 = tok2->linkAt(2);
                    if (Token::simpleMatch(tok3,") {")) {
                        tok3 = tok3->next();

                        // End } for the if block
                        const Token *tok4 = tok3->link();
                        if (Token::Match(tok3, "{ %var% =") &&
                            Token::simpleMatch(tok4, "} }") &&
                            Token::simpleMatch(tok4->tokAt(-2), "break ;")) {
                            // Is there a assignment and then a break?
                            const Token *t = Token::findsimplematch(tok3, ";");
                            if (t && t->tokAt(3) == tok4) {
                                for (std::list<ExecutionPath *>::iterator it = checks.begin(); it != checks.end(); ++it) {
                                    if ((*it)->varId == tok3->next()->varId()) {
                                        (*it)->numberOfIf++;
                                        break;
                                    }
                                }
                                tok = tok2->link();
                                continue;
                            }
                        }
                    }
                }

                // parse loop bodies
                check->parseLoopBody(tok2->next(), checks);
            }

            // skip { .. }
            tok2 = tok2->link();

            // if "do { .. } while ( .." , goto end of while..
            if (Token::simpleMatch(tok, "do {") && Token::simpleMatch(tok2, "} while ("))
                tok2 = tok2->linkAt(2);

            // bail out all variables if the scope contains a "return"
            // bail out all variables used in this for/while/switch/do
            for (; tok && tok != tok2; tok = tok->next()) {
                if (tok->str() == "return")
                    ExecutionPath::bailOut(checks);
                if (tok->varId())
                    ExecutionPath::bailOutVar(checks, tok->varId());
            }

            continue;
        }

        // bailout used variables in '; FOREACH ( .. ) { .. }'
        else if (tok->str() != "if" && Token::Match(tok->previous(), "[;{}] %var% (")) {
            // goto {
            const Token *tok2 = tok->next()->link()->next();
            if (tok2 && tok2->str() == "{") {
                // goto "}"
                tok2 = tok2->link();

                // bail out all variables used in "{ .. }"
                for (; tok && tok != tok2; tok = tok->next()) {
                    if (tok->varId())
                        ExecutionPath::bailOutVar(checks, tok->varId());
                }
            }
        }

        // .. ) { ... }  => bail out
        if (tok->str() == ")" && tok->next() && tok->next()->str() == "{") {
            ExecutionPath::bailOut(checks);
            return;
        }

        if ((tok->str() == "abort" || tok->str() == "exit") &&
            tok->next() && tok->next()->str() == "(") {
            ExecutionPath::bailOut(checks);
            return;
        }

        // don't parse into "struct type { .."
        if (Token::Match(tok, "struct|union|class %type% {|:")) {
            while (tok && tok->str() != "{" && tok->str() != ";")
                tok = tok->next();
            tok = tok ? tok->link() : 0;
            if (!tok) {
                ExecutionPath::bailOut(checks);
                return;
            }
        }

        if (Token::simpleMatch(tok, "= {")) {
            // GCC struct initialization.. bail out
            if (Token::Match(tok->tokAt(2), ". %var% =")) {
                ExecutionPath::bailOut(checks);
                return;
            }

            tok = tok->next()->link();
            if (!tok) {
                ExecutionPath::bailOut(checks);
                return;
            }
            continue;
        }

        // ; { ... }
        if (Token::Match(tok->previous(), "[;{}:] {")) {
            ExecutionPath::checkScope(tok->next(), checks);
            tok = tok->link();
            continue;
        }

        if (tok->str() == "if" && tok->next() && tok->next()->str() == "(") {
            // what variable ids should the numberOfIf be counted for?
            std::set<unsigned int> countif;

            std::list<ExecutionPath *> newchecks;
            while (tok->str() == "if" && tok->next() && tok->next()->str() == "(") {
                // goto "("
                tok = tok->next();

                // parse condition
                if (checks.size() > 10 || check->parseCondition(*tok->next(), checks)) {
                    ExecutionPath::bailOut(checks);
                    ExecutionPath::bailOut(newchecks);
                    return;
                }

                // goto ")"
                tok = tok->link();

                // goto "{"
                tok = tok->next();

                if (!tok || tok->str() != "{") {
                    ExecutionPath::bailOut(checks);
                    ExecutionPath::bailOut(newchecks);
                    return;
                }

                // Recursively check into the if ..
                parseIfSwitchBody(tok->next(), checks, newchecks, countif);

                // goto "}"
                tok = tok->link();

                // there is no else => break out
                if (!tok->next() || tok->next()->str() != "else")
                    break;

                // parse next "if"..
                tok = tok->tokAt(2);
                if (tok && tok->str() == "if")
                    continue;

                if (!tok) {
                    ExecutionPath::bailOut(newchecks);
                    return;
                }

                // there is no "if"..
                ExecutionPath::checkScope(tok->next(), checks);
                tok = tok->link();
                if (!tok) {
                    ExecutionPath::bailOut(newchecks);
                    return;
                }
            }

            // Add newchecks to checks..
            std::copy(newchecks.begin(), newchecks.end(), std::back_inserter(checks));

            // Increase numberOfIf
            std::list<ExecutionPath *>::iterator it;
            for (it = checks.begin(); it != checks.end(); ++it) {
                if (countif.find((*it)->varId) != countif.end())
                    (*it)->numberOfIf++;
            }

            // Delete checks that have numberOfIf >= 2
            for (it = checks.begin(); it != checks.end();) {
                if ((*it)->varId > 0 && (*it)->numberOfIf >= 2) {
                    delete *it;
                    checks.erase(it++);
                } else {
                    ++it;
                }
            }
        }


        {
            tok = check->parse(*tok, checks);
            if (checks.empty())
                return;
        }

        if (!tok)
            break;

        // return/throw ends all execution paths
        if (tok->str() == "return" ||
            tok->str() == "throw" ||
            tok->str() == "continue" ||
            tok->str() == "break") {
            ExecutionPath::bailOut(checks);
        }
    }
}
Esempio n. 21
0
void Vimpc::Run(std::string hostname, uint16_t port)
{
   int input = ERR;

   // Keyboard input event handler
   Vimpc::EventHandler(Event::Input, [&input] (EventData const & Data)
   {
      input = Data.input;
   });

   // Refresh the mode after a status update
   Vimpc::EventHandler(Event::StatusUpdate, [this] (EventData const & Data)
   {
      if (screen_.PagerIsVisible() == false)
      {
         Ui::Mode & mode = assert_reference(modeTable_[currentMode_]);
         mode.Refresh();
      }
   });

   // Set up the display
   {
      Ui::Mode & mode = assert_reference(modeTable_[currentMode_]);
      mode.Initialise(0);
   }

   SetSkipConfigConnects((hostname != "") || (port != 0));

   // Parse the config file
   commandMode_.SetQueueCommands(true);
   bool const configExecutionResult = Config::ExecuteConfigCommands(commandMode_);

   SetSkipConfigConnects(false);

   screen_.Start();

   if (configExecutionResult == true)
   {
      // If we didn't connect to a host from the config file, just connect to the default
      if (commandMode_.ConnectionAttempt() == false)
      {
         client_.Connect(hostname, port);
      }

      screen_.Update();
      commandMode_.SetQueueCommands(false);

      // The main loop
      while (Running == true)
      {
         screen_.UpdateErrorDisplay();

         {
            UniqueLock<Mutex> Lock(QueueMutex);

            if ((Queue.empty() == false) ||
               (ConditionWait(Condition, Lock, 100) != false))
            {
               if (Queue.empty() == false)
               {
                  EventPair const Event = Queue.front();
                  Queue.pop_front();
                  Lock.unlock();

                  if ((userEvents_ == false) &&
                     (Event.second.user == true))
                  {
                     Debug("Discarding user event");
                     continue;
                  }

                  for (auto func : Handler[Event.first])
                  {
                     func(Event.second);
                  }

                  EventMutex.lock();

                  for (auto cond : WaitConditions[Event.first])
                  {
                     cond->notify_all();
                  }

                  EventMutex.unlock();
               }
            }
         }

         if (input != ERR)
         {
            screen_.ClearErrorDisplay();

            if ((screen_.PagerIsVisible() == true)
#ifdef HAVE_MOUSE_SUPPORT
               && (input != KEY_MOUSE)
#endif
            )
            {
               if (screen_.PagerIsFinished() == true)
               {
                  screen_.HidePagerWindow();
               }
               else
               {
                  screen_.PagerWindowNext();
               }
            }
            else
            {
               Handle(input);
            }
         }

         bool const Resize = screen_.Resize();

         QueueMutex.lock();

         if (((input != ERR) || (Resize == true)) || (requireRepaint_ == true))
         {
            QueueMutex.unlock();
            Repaint();
         }
         else
         {
            QueueMutex.unlock();
         }

         input = ERR;
      }
   }
}
Esempio n. 22
0
 bool HasChildren() const {
   return !pChild.empty() || !text.empty();
 }
Esempio n. 23
0
void
OSGLContext_win::getGPUInfos(std::list<OpenGLRendererInfo>& renderers)
{

    const OSGLContext_wgl_data* wglInfo = appPTR->getWGLData();
    assert(wglInfo);
    if (!wglInfo) {
        return;
    }
    bool defaultFallback = false;
    if (wglInfo->NV_gpu_affinity) {
        // https://www.opengl.org/registry/specs/NV/gpu_affinity.txt
        std::vector<HGPUNV> gpuHandles;
        int gpuIndex = 0;
        HGPUNV gpuHandle;
        bool gotGPU = true;
        do {
            gotGPU = wglInfo->EnumGpusNV(gpuIndex, &gpuHandle);
            if (gotGPU) {
                gpuHandles.push_back(gpuHandle);
            }
            ++gpuIndex;
        } while (gotGPU);

        if (gpuHandles.empty()) {
            defaultFallback = true;
        }
        for (std::size_t i = 0; i < gpuHandles.size(); ++i) {
            OpenGLRendererInfo info;
            info.rendererID.rendererHandle = (void*)gpuHandles[i];

            boost::scoped_ptr<OSGLContext_win> context;
            try {

                GLRendererID gid;
                gid.rendererHandle = info.rendererID.rendererHandle;
                context.reset( new OSGLContext_win(FramebufferConfig(), appPTR->getOpenGLVersionMajor(), appPTR->getOpenGLVersionMinor(), false, gid, 0) );
            } catch (const std::exception& e) {
                continue;
            }

            if ( !makeContextCurrent( context.get() ) ) {
                continue;
            }

            try {
                OSGLContext::checkOpenGLVersion(true);
            } catch (const std::exception& e) {
                std::cerr << e.what() << std::endl;
                continue;
            }

            info.vendorName = std::string( (const char *) GL_GPU::GetString(GL_VENDOR) );
            info.rendererName = std::string( (const char *) GL_GPU::GetString(GL_RENDERER) );
            info.glVersionString = std::string( (const char *) GL_GPU::GetString(GL_VERSION) );
            info.glslVersionString = std::string( (const char*) GL_GPU::GetString(GL_SHADING_LANGUAGE_VERSION) );
            info.maxMemBytes = nvx_get_GPU_mem_info();
            GL_GPU::GetIntegerv(GL_MAX_TEXTURE_SIZE, &info.maxTextureSize);
            renderers.push_back(info);

            makeContextCurrent(0);
        }
    } else if (wglInfo->AMD_gpu_association && !isApplication32Bits()) {
        //https://www.opengl.org/registry/specs/AMD/wgl_gpu_association.txt
        UINT getGpuIDMaxCount = wglInfo->GetGpuIDAMD(0, 0);
        UINT maxCount = getGpuIDMaxCount;
        std::vector<UINT> gpuIDs(maxCount);
        if (maxCount == 0) {
            defaultFallback = true;
        } else {
            UINT gpuCount = wglInfo->GetGpuIDAMD(maxCount, &gpuIDs[0]);
            if (gpuCount > maxCount) {
                gpuIDs.resize(gpuCount);
            }
            for (UINT index = 0; index < gpuCount; ++index) {
                assert(index < gpuIDs.size());
                UINT gpuID = gpuIDs[index];

                OpenGLRendererInfo info;
                info.rendererName = GetGPUInfoAMDInternal_string(wglInfo, gpuID, WGL_GPU_RENDERER_STRING_AMD);
                if (info.rendererName.empty()) {
                    continue;
                }

                info.vendorName = GetGPUInfoAMDInternal_string(wglInfo, gpuID, WGL_GPU_VENDOR_AMD);
                if (info.vendorName.empty()) {
                    continue;
                }


                info.glVersionString = GetGPUInfoAMDInternal_string(wglInfo, gpuID, WGL_GPU_OPENGL_VERSION_STRING_AMD);
                if (info.glVersionString.empty()) {
                    continue;
                }

                // note: cannot retrieve GL_SHADING_LANGUAGE_VERSION

                info.maxMemBytes = 0;
                if (!isApplication32Bits()) {
                    int ramMB = 0;
                    // AMD drivers are f*** up in 32 bits, they read a wrong buffer size.
                    // It works fine in 64 bits mode
                    if (!GetGPUInfoAMDInternal_int(wglInfo, gpuID, WGL_GPU_RAM_AMD, &ramMB)) {
                        continue;
                    }
                    info.maxMemBytes = ramMB * 1e6;
                }

                info.rendererID.renderID = gpuID;
                
                boost::scoped_ptr<OSGLContext_win> context;

                GLRendererID gid;
                gid.renderID = info.rendererID.renderID;
                try {
                    context.reset( new OSGLContext_win(FramebufferConfig(), appPTR->getOpenGLVersionMajor(), appPTR->getOpenGLVersionMinor(), false, gid, 0) );
                } catch (const std::exception& e) {
                    continue;
                }

                if ( !makeContextCurrent( context.get() ) ) {
                    continue;
                }

                try {
                    OSGLContext::checkOpenGLVersion(true);
                } catch (const std::exception& e) {
                    std::cerr << e.what() << std::endl;
                    continue;
                }

                GL_GPU::GetIntegerv(GL_MAX_TEXTURE_SIZE, &info.maxTextureSize);
                renderers.push_back(info);
                
                makeContextCurrent(0);
            }
        }
    }

    if (renderers.empty()) {
        defaultFallback = true;
    }
    if (defaultFallback) {
        // No extension, use default
        boost::scoped_ptr<OSGLContext_win> context;
        try {
            context.reset( new OSGLContext_win(FramebufferConfig(), appPTR->getOpenGLVersionMajor(), appPTR->getOpenGLVersionMinor(), false, GLRendererID(), 0) );
        } catch (const std::exception& e) {
            std::cerr << e.what() << std::endl;

            return;
        }

        if ( !makeContextCurrent( context.get() ) ) {
            return;
        }

        try {
            OSGLContext::checkOpenGLVersion(true);
        } catch (const std::exception& e) {
            std::cerr << e.what() << std::endl;

            return;
        }

        OpenGLRendererInfo info;
        info.vendorName = std::string( (const char *) GL_GPU::GetString(GL_VENDOR) );
        info.rendererName = std::string( (const char *) GL_GPU::GetString(GL_RENDERER) );
        info.glVersionString = std::string( (const char *) GL_GPU::GetString(GL_VERSION) );
        info.glslVersionString = std::string( (const char *) GL_GPU::GetString(GL_SHADING_LANGUAGE_VERSION) );
        GL_GPU::GetIntegerv(GL_MAX_TEXTURE_SIZE, &info.maxTextureSize);
        // We don't have any way to get memory size, set it to 0
        info.maxMemBytes = nvx_get_GPU_mem_info();
        renderers.push_back(info);

        makeContextCurrent(0);
    }
} // OSGLContext_win::getGPUInfos
Esempio n. 24
0
/*Search by combination of tags and evalue */
int SearchRPSDBByTagsAndEvalue(std::list<RpsDBRecord*>& return_list)
{
	int gi=0;
	string domid;
	int alignlen=0;
	int numdom=0;
	double evalue=0.0;
	Str4large dom_id;
	Relate4set relation;

	/* check for empty list */
	if(return_list.empty())
	{
		ERR_POST(Error<<"[SearchRPSDB] parameter list is empty");
		return -1;
	}
	list<RpsDBRecord*>::iterator i=return_list.begin();
	RpsDBRecord* record=(*i);
	gi=record->GetGi();
	domid=record->GetDomId();
	alignlen=record->GetAlignLen();
	numdom=record->GetNumDom();
	evalue=record->GetEvalue();
	string express;
	CNcbiStrstream string_buf;
	/*remove dummy record from list-*/
	return_list.erase(return_list.begin());

	if(gi==0 && domid.empty() && alignlen==0 && numdom==0 ){
		ERR_POST("[SearchRPSDB]: no tags to search for");
	}

	/*if gi is set check other tags*/
	if(gi>0)
	{
		express="GI = " + NStr::IntToString(gi);
		express+= ".AND. ";
		if(!domid.empty()){
			express=express+"DOMID = '"+domid+ "' .AND. ";
		}else if(numdom>0){
			express=express+"NUMDOM ="+NStr::IntToString(numdom);
			express+=" .AND. ";
		}else if(alignlen>0){
			express=express+"ALIGN_LEN ="+NStr::IntToString(alignlen);
			express+= ".AND. ";
		}
	}
	/*id Domid is set check for numdom and alignlen */
	else if(!domid.empty()){
		express="DOMID= '"+domid+"' .AND. ";
		if(numdom>0){
			express=express+"NUMDOM ="+NStr::IntToString(numdom);
			express+= ".AND. ";
		}else if(alignlen>0) {
			express=express+"ALIGN_LEN ="+NStr::IntToString(alignlen);
			express+=".AND. ";
		}
	}
	else if(numdom>0){
		express="NUMDOM =";
		express+=numdom;
		express+=".AND. ";
		if(alignlen>0){
			express=express+"ALIGN_LEN ="+NStr::IntToString(alignlen);
			express+=".AND. ";
		}
	}
	/*add evalue cut off to the query expression */
	express=express+"EVALUE<"+NStr::DoubleToString(evalue);

	/*create a single relation with one table*/
	relation.init(rpsdb);
	if(!relation.isValid()){
		ERR_POST("Cannot create relation");
		return -1;
	}
	/*set a query for the relation and find all records */
	relation.querySet(express.c_str());
	for(int rc=relation.top(); rc!=r4eof; rc=relation.skip())
	{
		/*Fill record and add to list */
		record->SetGi(int(pf4rpsgi));
		dom_id.assign(pf4rpsdomid);
		dom_id.trim();
		string temp(dom_id.str());
		record->SetDomId(temp);
		record->SetFrom(int(pf4rpsfrom));
		record->SetAlignLen(int(pf4rpsalignlen));
		record->SetEvalue(double(pf4rpsevalue));
		record->SetMissingN(int(pf4rpsmisN));
		record->SetMissingC(int(pf4rpsmisC));
		record->SetNumdom(int(pf4rpsnumdom));
		return_list.push_back(record);
		record =new RpsDBRecord();
	}
	delete record;
	codeBase.unlock();
	relation.free();
	return 1;
}
Esempio n. 25
0
 bool hasChildren() const { return !m_children.empty(); }
Esempio n. 26
0
int SearchDOMNAME(std::list<DomnameDBRecord*>& return_list)
{
	string accession;
	string name;
	string pdbid;
	int rc=-20;
	Str4large strfield;
	if(return_list.empty())
	{
		ERR_POST(Error<<"[SearchDOMNAME] no parameters passed");
		return -1;
	}
	list<DomnameDBRecord*>::iterator i=return_list.begin();
	DomnameDBRecord* record=(*i);
	/* collect data from record */
	accession=record->GetAccession();
	name=record->GetName();
	pdbid=record->GetPdbId();
	/*remove first dummy record */
	return_list.erase(return_list.begin());
	if(accession.empty() && name.empty() && pdbid.empty()){
		ERR_POST("[SearchDOMNAME]: no tags are set to search");
		return -1;
	}
	/*search by mmdbid */
	if(!pdbid.empty()){
		string stringkey=pdbid;
		domnamedb.select(tagdnpdbid);
		domnamedb.top();
		rc=domnamedb.seek(stringkey.c_str());
		if(rc!=r4success){
			delete record;
			ERR_POST(Info<<"[SearchDOMNAME]: no record found for pdbid "<<pdbid);
			return -1;
		}
		for (rc=domnamedb.seek(stringkey.c_str()); rc==r4success;
			rc=domnamedb.seekNext(stringkey.c_str()))
		{
			/*fill record */
			strfield.assign(pf4dnaccession);
			strfield.trim();
			string temp(strfield.str());
			record->SetAccession(temp);

			strfield.assign(pf4dnname);
			strfield.trim();
			temp=strfield.str();
			record->SetName(temp);

			strfield.assign(pf4dnpdbid);
			strfield.trim();
			temp=strfield.str();
			record->SetPdbId(temp);

			return_list.push_back(record);
                        record =new DomnameDBRecord();
		}
		delete record;
	}
	/*search by domain accession or domain's name */
	else {
		string stringkey;
		if(!accession.empty())
		{
			stringkey=accession;
			domnamedb.select(tagdnaccession);
		}
		if(!name.empty())
		{
			stringkey=name;
			domnamedb.select(tagdnname);
		}
		domnamedb.top();
		rc=domnamedb.seek(stringkey.c_str());
		if(rc!=r4success){
			delete record;
			ERR_POST(Info<<"[SearchDOMNAME]: no record found for "<<stringkey);
			return -1;
		}
		for (rc=domnamedb.seek(stringkey.c_str());
			rc==r4success;rc=domnamedb.seekNext(stringkey.c_str()))
		{
			/*fill record */
			strfield.assign(pf4dnaccession);
			strfield.trim();
			string temp(strfield.str());
			record->SetAccession(temp);

			strfield.assign(pf4dnname);
			strfield.trim();
			temp=strfield.str();
			record->SetName(temp);

			strfield.assign(pf4dnpdbid);
			strfield.trim();
			temp=strfield.str();
			record->SetPdbId(temp);

			return_list.push_back(record);
                        record =new DomnameDBRecord();
		}
		delete record;
	}
	return 1;
}
Esempio n. 27
0
/*-----------------------------------------------------------------*/
bool NOMAD::strings_to_direction_type ( const std::list<std::string> & ls ,
                                       NOMAD::direction_type        & dt   )
{
    
    dt = NOMAD::UNDEFINED_DIRECTION;
    
    if ( ls.empty() || ls.size() > 4 )
        return false;
    
    std::list<std::string>::const_iterator it = ls.begin() , end = ls.end();
    std::string                            s  = *it;
    NOMAD::toupper ( s );
    
    // no direction:
    if ( s == "NONE" )
    {
        dt = NOMAD::NO_DIRECTION;
        return true;
    }
    
    // Ortho-MADS with 1, 2, n+1 (plus QUAD or NEG), or 2n directions:
    if ( s == "ORTHO" )
    {
        ++it;
        if ( it == end )
        {
            dt = NOMAD::ORTHO_NP1_QUAD;  // Default for ORTHO
            return true;
        }
        if ( *it == "1" )
        {
            dt = NOMAD::ORTHO_1;
            return true;
        }
        if ( *it == "2" )
        {
            dt = NOMAD::ORTHO_2;
            return true;
        }
        s = *it;
        NOMAD::toupper ( s );
        if ( s == "2N" )
        {
            dt = NOMAD::ORTHO_2N;
            return true;
        }
        if ( s == "N+1" )
        {
            ++it;
            if (it==end)
            {
                dt = NOMAD::ORTHO_NP1_QUAD;   // Default for ORTHO N+1
                return true;
            }
            s = *it;
            NOMAD::toupper ( s );
            if ( s=="QUAD" )
            {
                dt= NOMAD::ORTHO_NP1_QUAD;
                return true;
            }
            if ( s=="NEG" )
            {
                dt=NOMAD::ORTHO_NP1_NEG;
                return true;
            }
            if ( s=="UNI" )
            {
                dt=NOMAD::ORTHO_NP1_UNI;
                return true;
            }
            
        }
        
        return false;
    }
    
    // LT-MADS with 1, 2 or 2n directions:
    if ( s == "LT" )
    {
        ++it;
        if ( it == end )
        {
            dt = NOMAD::LT_2N;
            return true;
        }
        if ( *it == "1" )
        {
            dt = NOMAD::LT_1;
            return true;
        }
        if ( *it == "2" )
        {
            dt = NOMAD::LT_2;
            return true;
        }
        s = *it;
        NOMAD::toupper ( s );
        if ( s == "N+1" )
        {
            dt = NOMAD::LT_NP1;
            return true;
        }
        if ( s == "2N" )
        {
            dt = NOMAD::LT_2N;
            return true;
        }
        return false;
    }
    
    // GPS:
    if ( s == "GPS" )
    {
        ++it;
        if ( it == end )
        {
            dt = NOMAD::GPS_2N_STATIC;
            return true;
        }
        s = *it;
        NOMAD::toupper ( s );
        
        // GPS for binary variables:
        if ( s == "BINARY" || s == "BIN" )
        {
            dt = NOMAD::GPS_BINARY;
            return true;
        }
        
        // GPS, n+1 directions:
        if ( s == "N+1" )
        {
            ++it;
            if ( it == end )
            {
                dt = NOMAD::GPS_NP1_STATIC;
                return true;
            }
            s = *it;
            NOMAD::toupper ( s );
            
            // GPS, n+1, static:
            if ( s == "STATIC" )
            {
                ++it;
                if ( it == end )
                {
                    dt = NOMAD::GPS_NP1_STATIC;
                    return true;
                }
                s = *it;
                NOMAD::toupper ( s );
                if ( s == "UNIFORM" )
                {
                    dt = NOMAD::GPS_NP1_STATIC_UNIFORM;
                    return true;
                }
                return false;
            }
            
            // GPS, n+1, random:
            if ( s == "RAND" || s == "RANDOM" )
            {
                ++it;
                if ( it == end )
                {
                    dt = NOMAD::GPS_NP1_RAND;
                    return true;
                }
                s = *it;
                NOMAD::toupper ( s );
                if ( s == "UNIFORM" )
                {
                    dt = NOMAD::GPS_NP1_RAND_UNIFORM;
                    return true;
                }
                return false;
            }
            return false;
        }
        
        // 2n directions:
        if ( s == "2N" )
        {
            ++it;
            if ( it == end )
            {
                dt = NOMAD::GPS_2N_STATIC;
                return true;
            }
            s = *it;
            NOMAD::toupper ( s );
            if ( s == "STATIC" )
            {
                dt = NOMAD::GPS_2N_STATIC;
                return true;
            }
            if ( s == "RAND" || s == "RANDOM" )
            {
                dt = NOMAD::GPS_2N_RAND;
                return true;
            }
            return false;
        }
        return false;
    }
    return false;
}
Esempio n. 28
0
	inline bool has_pending() const
	{
		return !pending.empty();
	}
        void UpdateAI(uint32 diff) override
        {
            if (!UpdateVictim())
                return;

            if (TreeForm_Timer <= diff)
            {
                Talk(SAY_TREE);

                if (me->IsNonMeleeSpellCast(false))
                    me->InterruptNonMeleeSpells(true);

                me->RemoveAllAuras();

                DoCast(me, SPELL_SUMMON_FRAYER, true);
                DoCast(me, SPELL_TRANQUILITY, true);
                DoCast(me, SPELL_TREE_FORM, true);

                me->GetMotionMaster()->MoveIdle();
                MoveFree = false;

                TreeForm_Timer = 75000;
            }
            else
                TreeForm_Timer -= diff;

            if (!MoveFree)
            {
                if (MoveCheck_Timer <= diff)
                {
                    if (!Adds_List.empty())
                    {
                        for (std::list<uint64>::iterator itr = Adds_List.begin(); itr != Adds_List.end(); ++itr)
                        {
                            if (Unit* temp = Unit::GetUnit(*me, *itr))
                            {
                                if (!temp->IsAlive())
                                {
                                    Adds_List.erase(itr);
                                    ++DeadAddsCount;
                                    break;
                                }
                            }
                        }
                    }

                    if (DeadAddsCount < 3 && TreeForm_Timer-30000 <= diff)
                        DeadAddsCount = 3;

                    if (DeadAddsCount >= 3)
                    {
                        Adds_List.clear();
                        DeadAddsCount = 0;

                        me->InterruptNonMeleeSpells(true);
                        me->RemoveAllAuras();
                        me->GetMotionMaster()->MoveChase(me->GetVictim());
                        MoveFree = true;
                    }
                    MoveCheck_Timer = 500;
                }
                else
                    MoveCheck_Timer -= diff;

                return;
            }

            /*if (me->HasAura(SPELL_TREE_FORM, 0) || me->HasAura(SPELL_TRANQUILITY, 0))
                return;*/

            //one random seedling every 5 secs, but not in tree form
            if (SummonSeedling_Timer <= diff)
            {
                DoSummonSeedling();
                SummonSeedling_Timer = 6000;
            }
            else
                SummonSeedling_Timer -= diff;

            DoMeleeAttackIfReady();
        }
Esempio n. 30
0
static void buildKdTreeNode(
    KDTreeNode* Node, std::list<SCollisionFace*> &Triangles, s32 ForkLevel, const EKDTreeBuildingConcepts Concept)
{
    if (!Node || Triangles.empty())
        return;
    
    /* Check if tree node is a leaf */
    if (ForkLevel <= 0)
    {
        /* Create triangle reference list */
        std::vector<SCollisionFace*>* RefList = new std::vector<SCollisionFace*>(Triangles.size());
        
        u32 i = 0;
        foreach (SCollisionFace* Face, Triangles)
            (*RefList)[i++] = Face;
        
        /* Setup user data for tree node */
        Node->setDestructorCallback(KdTreeNodeDestructorProc);
        Node->setUserData(RefList);
        
        return;
    }
    
    const dim::aabbox3df BoundBox(Node->getBox());
    
    /* Compute average vertex position */
    dim::vector3df AvgVertPos;
    
    switch (Concept)
    {
        case KDTREECONCEPT_CENTER:
        {
            AvgVertPos = BoundBox.getCenter();
        }
        break;
        
        case KDTREECONCEPT_AVERAGE:
        {
            foreach (SCollisionFace* Face, Triangles)
                AvgVertPos += Face->Triangle.getCenter();
            
            AvgVertPos /= dim::vector3df(static_cast<f32>(Triangles.size()));
        }
        break;
    }
    
    /* Fill potentially sub triangle lists */
    std::list<SCollisionFace*> PotSubTrianglesNear[3], PotSubTrianglesFar[3];
    
    foreach (SCollisionFace* Face, Triangles)
    {
        for (s32 i = 0; i < 3; ++i)
        {
            #if 1
            
            if (Face->Triangle.PointA[i] < AvgVertPos[i] ||
                Face->Triangle.PointB[i] < AvgVertPos[i] ||
                Face->Triangle.PointC[i] < AvgVertPos[i])
            {
                PotSubTrianglesNear[i].push_back(Face);
            }
            if (Face->Triangle.PointA[i] >= AvgVertPos[i] ||
                Face->Triangle.PointB[i] >= AvgVertPos[i] ||
                Face->Triangle.PointC[i] >= AvgVertPos[i])
            {
                PotSubTrianglesFar[i].push_back(Face);
            }
            
            #else
            
            dim::aabbox3df NearBox(BoundBox);
            NearBox.Max[i] = AvgVertPos[i];
            
            dim::aabbox3df FarBox(BoundBox);
            NearBox.Min[i] = AvgVertPos[i];
            
            if (math::CollisionLibrary::checkTriangleBoxOverlap(Face->Triangle, NearBox))
                PotSubTrianglesNear[i].push_back(Face);
            if (math::CollisionLibrary::checkTriangleBoxOverlap(Face->Triangle, FarBox))
                PotSubTrianglesFar[i].push_back(Face);
            
            #endif
        }
    }
    
    /* Search for optimal tree partitioning */
    EKDTreeAxles Axis = KDTREE_XAXIS;
    
    switch (Concept)
    {
        case KDTREECONCEPT_CENTER:
        {
            const dim::vector3df BoxSize(BoundBox.getSize());
            
            if (BoxSize.X >= BoxSize.Y && BoxSize.X >= BoxSize.Z)
                Axis = KDTREE_XAXIS;
            else if (BoxSize.Y >= BoxSize.X && BoxSize.Y >= BoxSize.Z)
                Axis = KDTREE_YAXIS;
            else
                Axis = KDTREE_ZAXIS;
        }
        break;
        
        case KDTREECONCEPT_AVERAGE:
        {
            const u32 ListSize[3] =
            {
                PotSubTrianglesNear[0].size() + PotSubTrianglesFar[0].size(),
                PotSubTrianglesNear[1].size() + PotSubTrianglesFar[1].size(),
                PotSubTrianglesNear[2].size() + PotSubTrianglesFar[2].size()
            };
            
            if (ListSize[0] == ListSize[1] && ListSize[0] == ListSize[2])
            {
                const dim::vector3df BoxSize(BoundBox.getSize());
                
                if (BoxSize.X >= BoxSize.Y && BoxSize.X >= BoxSize.Z)
                    Axis = KDTREE_XAXIS;
                else if (BoxSize.Y >= BoxSize.X && BoxSize.Y >= BoxSize.Z)
                    Axis = KDTREE_YAXIS;
                else
                    Axis = KDTREE_ZAXIS;
            }
            else if (ListSize[0] <= ListSize[1] && ListSize[0] <= ListSize[2])
                Axis = KDTREE_XAXIS;
            else if (ListSize[1] <= ListSize[0] && ListSize[1] <= ListSize[2])
                Axis = KDTREE_YAXIS;
            else
                Axis = KDTREE_ZAXIS;
        }
        break;
    }
    
    /* Check if further sub-division is pointless */
    if (PotSubTrianglesNear[Axis].size() == Triangles.size() && PotSubTrianglesFar[Axis].size() == Triangles.size())
        ForkLevel = 0;
    
    #if 0
    /* Check if further sub-division is pointless */
    if (PotSubTrianglesNear[Axis].size() <= 1 && PotSubTrianglesFar[Axis].size() <= 1)
        io::Log::message("DEB: Only one triangle");
    #endif
    
    /* Create children tree nodes */
    Node->setAxis(Axis);
    Node->setDistance(AvgVertPos[Axis]);
    
    Node->addChildren();
    
    KDTreeNode* TreeNodeNear = static_cast<KDTreeNode*>(Node->getChildNear());
    KDTreeNode* TreeNodeFar = static_cast<KDTreeNode*>(Node->getChildFar());
    
    /* Build next fork level */
    buildKdTreeNode(TreeNodeNear, PotSubTrianglesNear[Axis], ForkLevel - 1, Concept);
    buildKdTreeNode(TreeNodeFar, PotSubTrianglesFar[Axis], ForkLevel - 1, Concept);
}