Ejemplo n.º 1
0
iteration_t* Trace::compressLoopLCS(iteration_t* iteration){
  Event *iter;
  int max, count, iteration_length;
  iteration_t *current, *rtn;
  vector<matching_pair_t *> *pairs = NULL;
  vector<iteration_t *> iterations;
  vector<iteration_t *>::iterator iteration_it;

  /* delete the current iteration from pendingIterations so that it won't be
   * evaluated repeatedly */
  pendingIterations.deleteIteration(iteration);

  /* check if there is pending iteration inside the target iteration */
  for(iter = iteration->target_head; iter != iteration->target_tail->next && iter != NULL; iter = iter->next){
    if(iter->checkLoc(LEADER)){
      /* loops are either completely disjoint or perfectly embedded: if there is
       * a LEADER event (merge_head) in an iteration, the corresponding merge_tail,
       * target_head, target_tail must also be in the same iteration. Therefore, when
       * we merge target_head ... target_tail into the previous iteration and remove
       * them, we only have to handle the case where target_tail is also the last event
       * of a larger iteration that directly or indirectly contains the two iterations
       * merge_head ... merge_tail target_head ... target_tail.
       */
      iterations = pendingIterations.getIterationsByMergeHead(iter);
      max = INT_MIN;
      current = NULL;
      for(iteration_it = iterations.begin(); iteration_it != iterations.end(); ++iteration_it){
        if((*iteration_it)->merge_length > max){
          current = *iteration_it;
          max = (*iteration_it)->merge_length;
        }
      }
      if(current){
        if(iteration->target_tail == current->target_tail){
          rtn = compressLoopLCS(current);
          iteration->target_tail = rtn->merge_tail;
        } else {
          rtn = compressLoopLCS(current);
        }
        if(rtn)
          delete rtn;
      }
    }
  }

  /* check if there is pending iteration inside the merge iteration */
  for(iter = iteration->merge_head; iter != iteration->merge_tail->next && iter != NULL; iter = iter->next){
    if(iter->checkLoc(LEADER)){
      iterations = pendingIterations.getIterationsByMergeHead(iter);
      max = INT_MIN;
      current = NULL;
      for(iteration_it = iterations.begin(); iteration_it != iterations.end(); ++iteration_it){
        if((*iteration_it)->merge_length > max){
          current = *iteration_it;
          max = (*iteration_it)->merge_length;
        }
      }
      if(current){
        if(iteration->merge_tail == current->target_tail){
          rtn = compressLoopLCS(current);
          iteration->merge_tail = rtn->merge_tail;
        } else {
          rtn = compressLoopLCS(current);
        }
        if(rtn)
          delete rtn;
      }
    }
  }

  for(iter = iteration->target_head, count = 1; iter != iteration->target_tail; iter = iter->next, count++);
  iteration->target_length = count;
  for(iter = iteration->merge_head, count = 1; iter != iteration->merge_tail; iter = iter->next, count++);
  iteration->merge_length = count;

  pairs = matchLoopLCS(iteration->merge_head, iteration->merge_tail, iteration->merge_length,
      iteration->target_head, iteration->target_tail, iteration->target_length );
  if(!pairs){
    assert(0);
  } else {
    iteration_length = updateLoopLCS(iteration->merge_head, iteration->merge_tail,
        iteration->merge_length, iteration->target_head, iteration->target_tail, pairs);
    mergeLoopEvents(iteration->merge_head, iteration->merge_tail,
        iteration->target_head, iteration->target_tail);
    updateLoopInfo(iteration->merge_head, iteration->merge_tail, iteration->target_head,
        iteration->target_tail, iteration_length);
    deleteIteration(iteration->target_head, iteration->target_tail);
  }

  for(unsigned i=0; i<pairs->size(); i++)
    delete pairs->at(i);
  delete pairs;

  iteration->target_head = NULL;
  iteration->target_tail = NULL;
  iteration->target_length = 0;
  iteration->merge_length = iteration_length;
  return iteration;
}
Ejemplo n.º 2
0
void probProcessor::change_request(Event& event){

  cafe::Config config(name());
  
  
  
  if (!MCREQID) throw runtime_error("ERROR:  processor MCReqID is not initialized.") ;
  
  // verify if request id is stay the same. In that case do nothing.
  
  if ( MCREQID->reqid() == _reqid ) return ;
  _reqid = MCREQID->reqid() ;
  
  // verify data epochs associated to this MC
  const vector<string>* epochs =  MCREQID->current_data_epochs();

  // Actually we could do better than just checking if the reqid changed,
  // if the current_data_epochs did not change we can also stop.
  // This is a little work, but much faster than rereading all trigger map
  bool same_epochs=true;
  if(_previous_epochs.size() == epochs->size()){
    for(int i=0; i<epochs->size(); i++){
      if(_previous_epochs[i] != epochs->at(i)){
	same_epochs=false;
	break;
      }
    }
  }else{
    same_epochs=false;
  }
  if(same_epochs) return;
  else{
    _previous_epochs.clear();
    for(int i=0; i<epochs->size(); i++) _previous_epochs.push_back(epochs->at(i));
  }


  //Get new maps of trigger versions and lumis (provided by cafTriggerEfficiency)
  _mapVersionLumi.clear();
  _mapVersionLumi1.clear();
  _mapVersionLumi2.clear();
  event.get("passedVersionLumi", _mapVersionLumi);
  event.get("passedVersionLumi1", _mapVersionLumi1);
  event.get("passedVersionLumi2", _mapVersionLumi2);


  //// This is a quick solution, but really _trigger_version and _trigger_lumi should be
  //// completely removed and only _mapVersionLumi should be used
  _trigger_version.clear();
  _trigger_lumi.clear();
  for(map<string, float>::iterator it = _mapVersionLumi.begin(); it != _mapVersionLumi.end(); ++it) {
    _trigger_version.push_back((*it).first);
    _trigger_lumi.push_back((*it).second);
  }


  if(_debug){ 
    cout<<"trigger version now has "<< _trigger_version.size()<<" entries. "<<endl; 
    cout<<"triglists: ";
    for (int i=0; i < _trigger_version.size(); i++) cout<<_trigger_version[i]<<" ";
    cout<<endl;
  }

  //// Update the trigger map (must be defined in children classes)
  // change_triggermap();
  // Moved to the beginning of defineEffInfo() define in child classes
  
  map< string, EffInfo > effInfo ;
  
  defineEffInfo(effInfo) ;
  
  //Set up the sigma variables with the effInfo
  sigmaSet(effInfo);
  
  for (map< string, EffInfo >::iterator it = effInfo.begin();
       it != effInfo.end(); it++) {
    
    //      cout << "Adding " << it->first << " to the map." << endl;
    //With our objectProb mapping, we fill it with the constructed objects
    string path = DeterminePath(it->first);
      
//       cout << endl << endl;
//       cout << "Prob:" << endl;
//       cout << "  " << it->first << endl;
//       cout << endl;
    
    _objectProb[it->first] = objectProbabilities(it->second, path, 
						 _ignoreOverflow, _ignoreUnderflow);
    
  }
  
}
Ejemplo n.º 3
0
static Event parseVObject( VObject *obj )
{
    Event e;

    bool haveAlarm = FALSE;
    bool haveStart = FALSE;
    bool haveEnd = FALSE;
    QDateTime alarmTime;
    Event::SoundTypeChoice soundType = Event::Silent;

    VObjectIterator it;
    initPropIterator( &it, obj );
    while( moreIteration( &it ) ) {
        VObject *o = nextVObject( &it );
        QCString name = vObjectName( o );
        QCString value = vObjectStringZValue( o );
        if ( name == VCDTstartProp ) {
            e.setStart( TimeConversion::fromISO8601( value ) );
            haveStart = TRUE;
        }
        else if ( name == VCDTendProp ) {
            e.setEnd( TimeConversion::fromISO8601( value ) );
            haveEnd = TRUE;
        }
        else if ( name == "X-Qtopia-NOTES" ) {
            e.setNotes( value );
        }
        else if ( name == VCDescriptionProp ) {
            e.setDescription( value );
        }
        else if ( name == VCLocationProp ) {
            e.setLocation( value );
        }
        else if ( name == VCAudioContentProp ) {
            haveAlarm = TRUE;
            VObjectIterator nit;
            initPropIterator( &nit, o );
            while( moreIteration( &nit ) ) {
                VObject *o = nextVObject( &nit );
                QCString name = vObjectName( o );
                QCString value = vObjectStringZValue( o );
                if ( name == VCRunTimeProp )
                    alarmTime = TimeConversion::fromISO8601( value );
                else if ( name == VCAudioContentProp ) {
                    if ( value == "silent" )
                        soundType = Event::Silent;
                    else
                        soundType = Event::Loud;
                }
            }
        }
        else if ( name == "X-Qtopia-TIMEZONE") {
            e.setTimeZone( value );
        }
        else if ( name == "X-Qtopia-AllDay" ) {
            e.setType( Event::AllDay );
        }
#if 0
        else {
            printf("Name: %s, value=%s\n", name.data(), vObjectStringZValue( o ) );
            VObjectIterator nit;
            initPropIterator( &nit, o );
            while( moreIteration( &nit ) ) {
                VObject *o = nextVObject( &nit );
                QCString name = vObjectName( o );
                QString value = vObjectStringZValue( o );
                printf(" subprop: %s = %s\n", name.data(), value.latin1() );
            }
        }
#endif
    }

    if ( !haveStart && !haveEnd )
        e.setStart( QDateTime::currentDateTime() );

    if ( !haveEnd ) {
        e.setType( Event::AllDay );
        e.setEnd( e.start() );
    }

    if ( haveAlarm ) {
        int minutes = alarmTime.secsTo( e.start() ) / 60;
        e.setAlarm( TRUE, minutes, soundType );
    }
    return e;
}
Ejemplo n.º 4
0
void
ClientProxy1_6::handleClipboardSendingEvent(const Event& event, void*)
{
	ClipboardChunk::send(getStream(), event.getData());
}
Ejemplo n.º 5
0
 MNote(const Event& _mc) : mc(_mc) {
       for (int i = 0; i < mc.notes().size(); ++i)
             ties.append(0);
       }
Ejemplo n.º 6
0
int main(int argc, char* argv[])
{
	int Argument;
	char Message[512];
	SimpleString ServiceName;
	int ConnectionString = -1;
	int ConnectionObjects = -1;

	if ( argc < 2 )
	{
		Usage( "Two few parameters" );
	}

	if ( argv[1][0] == '-' )
	{
		Usage( "The first parameter *must* be the service name" );
	}
	ServiceName = argv[1];

	// Check argument before launching any registering process
	for( Argument = 2; Argument < argc; Argument++ )
	{
		if ( strcmp( "-o", argv[Argument]) == 0 )
		{
			if ( Argument+1 >= argc || argv[Argument+1][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing output name at parameter %d\n", Argument+1 );
				Usage( (const char *)Message );
			}
			if ( Argument+2 >= argc || argv[Argument+2][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing description for output '%s' at parameter %d\n", argv[Argument+1], Argument+2 );
				Usage( (const char *)Message );
			}

			Argument += 2;
			continue;
		}

		if ( strcmp( "-i", argv[Argument]) == 0 )
		{
			if ( Argument+1 >= argc || argv[Argument+1][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing input name at parameter %d\n", Argument+1 );
				Usage( (const char *)Message );
			}
			if ( Argument+2 >= argc || argv[Argument+2][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing description for input '%s' at parameter %d\n", argv[Argument+1], Argument+2 );
				Usage( (const char *)Message );
			}
			Argument += 2;
			continue;
		}

		if ( strcmp( "-io", argv[Argument]) == 0 )
		{
			if ( Argument+1 >= argc || argv[Argument+1][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing inoutput name at parameter %d\n", Argument+1 );
				Usage( (const char *)Message );
			}
			if ( Argument+2 >= argc || argv[Argument+2][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing description for inoutput '%s' at parameter %d\n", argv[Argument+1], Argument+2 );
				Usage( (const char *)Message );
			}
			Argument += 2;
			continue;
		}

		if ( strcmp( "-v", argv[Argument]) == 0 )
		{
			if ( Argument+1 >= argc || argv[Argument+1][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing variable name at parameter %d\n", Argument+1 );
				Usage( (const char *)Message );
			}
			if ( Argument+2 >= argc || argv[Argument+2][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing description for variable '%s' at parameter %d\n", argv[Argument+1], Argument+2 );
				Usage( (const char *)Message );
			}
			if ( Argument+3 >= argc || argv[Argument+3][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing value for variable '%s' at parameter %d\n", argv[Argument+1], Argument+3 );
				Usage( (const char *)Message );
			}
			Argument += 3;
			continue;
		}

		if ( strcmp( "-ct", argv[Argument]) == 0 )
		{
			if ( Argument+1 >= argc || argv[Argument+1][0] == '-')
			{
				// We consider it as the name
				sprintf( Message, "Missing connection strint after parameter %d\n", Argument+1 );
				Usage( (const char *)Message );
			}

			ConnectionString = Argument+1;

			ConnectionObjects = ParseConnectionString( argv[ConnectionString], false );
			if ( ConnectionObjects <= 0 )
			{
				sprintf( Message, "Bad connection string in parameter %d\n", Argument+1 );
				Usage( (const char *)Message );
			}

			Argument += 1;
			continue;
		}

		if ( strcmp( "-d", argv[Argument]) == 0 )
		{
			if ( Debug )
			{
				fprintf( stderr, "Warning: debug mode already set\n" );
			}
			Debug = true;
			continue;
		}

		sprintf( Message, "invalid option in parameter %d ('%s')", Argument+1, argv[Argument] );
		Usage( (const char *)Message );
	}

#ifdef _DEBUG
		// MsgSocket::Debug = MsgSocket::DBG_LINKSYNC;
#endif

	// Ok, it seems that parameters looks ok...
	// start registering service
	if ( Debug ) { printf("Launching service '%s' ", ServiceName.GetStr() ); }

	Service * pServ = ServiceFactory.Create( ServiceName );
	if ( Debug ) { printf("with ServiceId %s\n", pServ->GetPeerIdAsString().GetStr() ); }

	// Check argument before launching any registering process
	for( Argument = 2; Argument < argc; Argument++ )
	{
		if ( strcmp( "-o", argv[Argument]) == 0 )
		{
			pServ->AddConnector( argv[Argument+1], argv[Argument+2], AnOutput );

			Argument += 2;
			continue;
		}

		if ( strcmp( "-i", argv[Argument]) == 0 )
		{
			pServ->AddConnector( argv[Argument+1], argv[Argument+2], AnInput );

			Argument += 2;
			continue;
		}

		if ( strcmp( "-io", argv[Argument]) == 0 )
		{
			pServ->AddConnector( argv[Argument+1], argv[Argument+2], AnInOutput );

			Argument += 2;
			continue;
		}

		if ( strcmp( "-v", argv[Argument]) == 0 )
		{
			if ( Debug ) { printf( "Adding variable '%s' ('%s') with value '%s'...", argv[Argument+1], argv[Argument+2], argv[Argument+3] ); }

			if ( pServ->AddVariable( argv[Argument+1], SimpleString::EmptyString, argv[Argument+2], ReadWriteAccess ) == true )
			{
				pServ->SetVariableValue( argv[Argument+1], argv[Argument+3] );
				if ( Debug ) { printf( "done.\n" ); }
			}
			else
			{
				if ( Debug ) { printf( "failed.\n" ); }
			}

			Argument += 3;
			continue;
		}

		if ( strcmp( "-ct", argv[Argument]) == 0 )
		{
			// Already processed
			Argument += 1;
			 continue;
		}

		if ( strcmp( "-d", argv[Argument]) == 0 )
		{
			// Debug option already processed int the validity checking mode
			 continue;
		}

		sprintf( Message, "invalid option in parameter %d ('%s')", Argument+1, argv[Argument] );
		Usage( (const char *)Message );
	}

	pServ->Start();

	printf( "Waiting...\n" );
	// Lock Mylself
	Event ForEver;
	ForEver.Wait();

	return 0;
}
Ejemplo n.º 7
0
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
bool Comment::detachFrom(PublicObject* object) {
	if ( object == NULL ) return false;

	// check all possible parents
	MomentTensor* momentTensor = MomentTensor::Cast(object);
	if ( momentTensor != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return momentTensor->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = momentTensor->comment(index());
			if ( child != NULL )
				return momentTensor->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(MomentTensor): comment has not been found");
				return false;
			}
		}
	}
	FocalMechanism* focalMechanism = FocalMechanism::Cast(object);
	if ( focalMechanism != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return focalMechanism->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = focalMechanism->comment(index());
			if ( child != NULL )
				return focalMechanism->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(FocalMechanism): comment has not been found");
				return false;
			}
		}
	}
	Amplitude* amplitude = Amplitude::Cast(object);
	if ( amplitude != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return amplitude->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = amplitude->comment(index());
			if ( child != NULL )
				return amplitude->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(Amplitude): comment has not been found");
				return false;
			}
		}
	}
	Magnitude* magnitude = Magnitude::Cast(object);
	if ( magnitude != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return magnitude->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = magnitude->comment(index());
			if ( child != NULL )
				return magnitude->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(Magnitude): comment has not been found");
				return false;
			}
		}
	}
	StationMagnitude* stationMagnitude = StationMagnitude::Cast(object);
	if ( stationMagnitude != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return stationMagnitude->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = stationMagnitude->comment(index());
			if ( child != NULL )
				return stationMagnitude->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(StationMagnitude): comment has not been found");
				return false;
			}
		}
	}
	Pick* pick = Pick::Cast(object);
	if ( pick != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return pick->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = pick->comment(index());
			if ( child != NULL )
				return pick->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(Pick): comment has not been found");
				return false;
			}
		}
	}
	Event* event = Event::Cast(object);
	if ( event != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return event->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = event->comment(index());
			if ( child != NULL )
				return event->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(Event): comment has not been found");
				return false;
			}
		}
	}
	Origin* origin = Origin::Cast(object);
	if ( origin != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return origin->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = origin->comment(index());
			if ( child != NULL )
				return origin->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(Origin): comment has not been found");
				return false;
			}
		}
	}
	Parameter* parameter = Parameter::Cast(object);
	if ( parameter != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return parameter->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = parameter->comment(index());
			if ( child != NULL )
				return parameter->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(Parameter): comment has not been found");
				return false;
			}
		}
	}
	ParameterSet* parameterSet = ParameterSet::Cast(object);
	if ( parameterSet != NULL ) {
		// If the object has been added already to the parent locally
		// just remove it by pointer
		if ( object == parent() )
			return parameterSet->remove(this);
		// The object has not been added locally so it must be looked up
		else {
			Comment* child = parameterSet->comment(index());
			if ( child != NULL )
				return parameterSet->remove(child);
			else {
				SEISCOMP_DEBUG("Comment::detachFrom(ParameterSet): comment has not been found");
				return false;
			}
		}
	}

	SEISCOMP_ERROR("Comment::detachFrom(%s) -> wrong class type", object->className());
	return false;
}
Ejemplo n.º 8
0
void *EmergeThread::run()
{
	DSTACK(FUNCTION_NAME);
	BEGIN_DEBUG_EXCEPTION_HANDLER

	v3s16 pos;

	m_map    = (ServerMap *)&(m_server->m_env->getMap());
	m_emerge = m_server->m_emerge;
	m_mapgen = m_emerge->m_mapgens[id];
	enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info;

	reg("EmergeThread" + itos(id), 5);

	while (!stopRequested()) {
	try {
		std::map<v3s16, MapBlock *> modified_blocks;
		BlockEmergeData bedata;
		BlockMakeData bmdata;
		EmergeAction action;
		MapBlock *block;

		if (!popBlockEmerge(&pos, &bedata)) {
			m_queue_event.wait();
			continue;
		}

		if (blockpos_over_limit(pos))
			continue;

		bool allow_gen = bedata.flags & BLOCK_EMERGE_ALLOW_GEN;
		EMERGE_DBG_OUT("pos=" PP(pos) " allow_gen=" << allow_gen);

		action = getBlockOrStartGen(pos, allow_gen, &block, &bmdata);
		if (action == EMERGE_GENERATED) {
			{
				ScopeProfiler sp(g_profiler,
					"EmergeThread: Mapgen::makeChunk", SPT_AVG);
				TimeTaker t("mapgen::make_block()");

				m_mapgen->makeChunk(&bmdata);

				if (enable_mapgen_debug_info == false)
					t.stop(true); // Hide output
			}

			block = finishGen(pos, &bmdata, &modified_blocks);
		}

		runCompletionCallbacks(pos, action, bedata.callbacks);

		if (block) {
			//modified_blocks[pos] = block;
		} else if (allow_gen)
			verbosestream<<"nothing generated at "<<pos<< " emerge action="<< action <<std::endl;

		if (modified_blocks.size() > 0)
			m_server->SetBlocksNotSent(/*modified_blocks*/);

		if (m_mapgen->heat_cache.size() > 1000) {
			m_mapgen->heat_cache.clear();
			m_mapgen->humidity_cache.clear();
		}
	} catch (VersionMismatchException &e) {
		std::ostringstream err;
		err << "World data version mismatch in MapBlock " << PP(pos) << std::endl
			<< "----" << std::endl
			<< "\"" << e.what() << "\"" << std::endl
			<< "See debug.txt." << std::endl
			<< "World probably saved by a newer version of " PROJECT_NAME_C "."
			<< std::endl;
		debug_stacks_print();
		m_server->setAsyncFatalError(err.str());
	} catch (SerializationError &e) {
		std::ostringstream err;
		err << "Invalid data in MapBlock " << PP(pos) << std::endl
			<< "----" << std::endl
			<< "\"" << e.what() << "\"" << std::endl
			<< "See debug.txt." << std::endl
			<< "You can ignore this using [ignore_world_load_errors = true]."
			<< std::endl;
		debug_stacks_print();
		m_server->setAsyncFatalError(err.str());
	} catch (std::exception &e) {
		errorstream << "emerge: exception at " << pos << " : " << e.what() << std::endl;
	}
	}

	END_DEBUG_EXCEPTION_HANDLER
	return NULL;
}
Ejemplo n.º 9
0
void
StreamFilter::filterEvent(const Event& event)
{
	m_events->dispatchEvent(Event(event.getType(),
						getEventTarget(), event.getData()));
}
Ejemplo n.º 10
0
void V8Event::valueAccessorSetter(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::AccessorInfo& info)
{
    Event* event = V8Event::toNative(info.Holder());
    event->setDefaultPrevented(!value->BooleanValue());
}
Ejemplo n.º 11
0
void EmergeThread::signal()
{
	m_queue_event.signal();
}
Ejemplo n.º 12
0
void testtex::run(void)
{
	pe.wait();
	puts("In thread");
}
Ejemplo n.º 13
0
/**
 * A particular event has been triggered.
 * Process all of this events components.
 *
 * @param The triggered event
 * @return Returns true if the event shall not be run again.
 */
bool EventManager::executeEvent(Event &ev) {
    if(&ev == NULL) return false;

    // skip executing events that are on cooldown
    if (ev.cooldown_ticks > 0) return false;

    // set cooldown
    ev.cooldown_ticks = ev.cooldown;

    Event_Component *ec;

    for (unsigned i = 0; i < ev.components.size(); ++i) {
        ec = &ev.components[i];

        if (ec->type == "set_status") {
            camp->setStatus(ec->s);
        }
        else if (ec->type == "unset_status") {
            camp->unsetStatus(ec->s);
        }
        else if (ec->type == "intermap") {

            if (fileExists(mods->locate(ec->s))) {
                mapr->teleportation = true;
                mapr->teleport_mapname = ec->s;
                mapr->teleport_destination.x = static_cast<float>(ec->x) + 0.5f;
                mapr->teleport_destination.y = static_cast<float>(ec->y) + 0.5f;
            }
            else {
                ev.keep_after_trigger = false;
                mapr->log_msg = msg->get("Unknown destination");
            }
        }
        else if (ec->type == "intramap") {
            mapr->teleportation = true;
            mapr->teleport_mapname = "";
            mapr->teleport_destination.x = static_cast<float>(ec->x) + 0.5f;
            mapr->teleport_destination.y = static_cast<float>(ec->y) + 0.5f;
        }
        else if (ec->type == "mapmod") {
            if (ec->s == "collision") {
                if (ec->x >= 0 && ec->x < mapr->w && ec->y >= 0 && ec->y < mapr->h) {
                    mapr->collider.colmap[ec->x][ec->y] = static_cast<unsigned short>(ec->z);
                    mapr->map_change = true;
                }
                else
                    logError("EventManager: Mapmod at position (%d, %d) is out of bounds 0-255.", ec->x, ec->y);
            }
            else {
                int index = distance(mapr->layernames.begin(), find(mapr->layernames.begin(), mapr->layernames.end(), ec->s));
                if (!mapr->isValidTile(ec->z))
                    logError("EventManager: Mapmod at position (%d, %d) contains invalid tile id (%d).", ec->x, ec->y, ec->z);
                else if (ec->x >= 0 && ec->x < mapr->w && ec->y >= 0 && ec->y < mapr->h)
                    mapr->layers[index][ec->x][ec->y] = static_cast<unsigned short>(ec->z);
                else
                    logError("EventManager: Mapmod at position (%d, %d) is out of bounds 0-255.", ec->x, ec->y);
            }
        }
        else if (ec->type == "soundfx") {
            FPoint pos(0,0);
            bool loop = false;

            if (ec->x != -1 && ec->y != -1) {
                if (ec->x != 0 && ec->y != 0) {
                    pos.x = static_cast<float>(ec->x) + 0.5f;
                    pos.y = static_cast<float>(ec->y) + 0.5f;
                }
            }
            else if (ev.location.x != 0 && ev.location.y != 0) {
                pos.x = static_cast<float>(ev.location.x) + 0.5f;
                pos.y = static_cast<float>(ev.location.y) + 0.5f;
            }

            if (ev.type == "on_load")
                loop = true;

            SoundManager::SoundID sid = snd->load(ec->s, "MapRenderer background soundfx");

            snd->play(sid, GLOBAL_VIRTUAL_CHANNEL, pos, loop);
            mapr->sids.push_back(sid);
        }
        else if (ec->type == "loot") {
            ec->x = ev.hotspot.x;
            ec->y = ev.hotspot.y;
            mapr->loot.push_back(*ec);
        }
        else if (ec->type == "msg") {
            mapr->log_msg = ec->s;
        }
        else if (ec->type == "shakycam") {
            mapr->shaky_cam_ticks = ec->x;
        }
        else if (ec->type == "remove_currency") {
            camp->removeCurrency(ec->x);
        }
        else if (ec->type == "remove_item") {
            camp->removeItem(ec->x);
        }
        else if (ec->type == "reward_xp") {
            camp->rewardXP(ec->x, true);
        }
        else if (ec->type == "reward_currency") {
            camp->rewardCurrency(ec->x);
        }
        else if (ec->type == "reward_item") {
            ItemStack istack;
            istack.item = ec->x;
            istack.quantity = ec->y;
            camp->rewardItem(istack);
        }
        else if (ec->type == "restore") {
            camp->restoreHPMP(ec->s);
        }
        else if (ec->type == "spawn") {
            Point spawn_pos;
            spawn_pos.x = ec->x;
            spawn_pos.y = ec->y;
            powers->spawn(ec->s, spawn_pos);
        }
        else if (ec->type == "power") {
            Event_Component *ec_path = ev.getComponent("power_path");
            FPoint target;

            if (ec_path) {
                // targets hero option
                if (ec_path->s == "hero") {
                    target.x = mapr->cam.x;
                    target.y = mapr->cam.y;
                }
                // targets fixed path option
                else {
                    target.x = static_cast<float>(ec_path->a) + 0.5f;
                    target.y = static_cast<float>(ec_path->b) + 0.5f;
                }
            }
            // no path specified, targets self location
            else {
                target.x = static_cast<float>(ev.location.x) + 0.5f;
                target.y = static_cast<float>(ev.location.y) + 0.5f;
            }

            // ec->x is power id
            // ec->y is statblock index
            mapr->activatePower(ec->x, ec->y, target);
        }
        else if (ec->type == "stash") {
            mapr->stash = toBool(ec->s);
            if (mapr->stash) {
                mapr->stash_pos.x = static_cast<float>(ev.location.x) + 0.5f;
                mapr->stash_pos.y = static_cast<float>(ev.location.y) + 0.5f;
            }
        }
        else if (ec->type == "npc") {
            mapr->event_npc = ec->s;
        }
        else if (ec->type == "music") {
            mapr->music_filename = ec->s;
            mapr->loadMusic();
        }
        else if (ec->type == "cutscene") {
            mapr->cutscene = true;
            mapr->cutscene_file = ec->s;
        }
        else if (ec->type == "repeat") {
            ev.keep_after_trigger = toBool(ec->s);
        }
        else if (ec->type == "save_game") {
            mapr->save_game = toBool(ec->s);
        }
        else if (ec->type == "npc_id") {
            mapr->npc_id = ec->x;
        }
    }
    return !ev.keep_after_trigger;
}
Ejemplo n.º 14
0
void ElevatorLogic::HandleOpened(Environment &env, const Event &e) {

	Elevator *ele = static_cast<Elevator*>(e.GetSender());

	env.SendEvent("Elevator::Close", 4, this, ele);
}
Ejemplo n.º 15
0
 EventView(Event const &base) : m_base(base), m_particle(base.coordinate(0))
 {
 }
Ejemplo n.º 16
0
//==============================================================================
Error EventManager::updateAllEvents(F32 prevUpdateTime, F32 crntTime)
{
	Error err = ErrorCode::NONE;
	m_prevUpdateTime = prevUpdateTime;
	m_crntTime = crntTime;

	auto it = m_events.getBegin();
	auto end = m_events.getEnd();
	for(; it != end && !err; ++it)
	{
		Event* event = *it;

		// If event or the node's event is marked for deletion then dont 
		// do anything else for that event
		if(event->getMarkedForDeletion())
		{
			continue;
		}

		if(event->getSceneNode() != nullptr 
			&& event->getSceneNode()->getMarkedForDeletion())
		{
			event->setMarkedForDeletion();
			continue;
		}

		// Audjust starting time
		if(event->m_startTime < 0.0)
		{
			event->m_startTime = crntTime;
		}

		// Check if dead
		if(!event->isDead(crntTime))
		{
			// If not dead update it

			if(event->getStartTime() <= crntTime)
			{
				err = event->update(prevUpdateTime, crntTime);
			}
		}
		else
		{
			// Dead

			if(event->getReanimate())
			{
				event->m_startTime = prevUpdateTime;
				err = event->update(prevUpdateTime, crntTime);
			}
			else
			{
				Bool kill;
				err = event->onKilled(prevUpdateTime, crntTime, kill);
				if(!err && kill)
				{
					event->setMarkedForDeletion();
				}
			}
		}
	}

	return err;
}
Ejemplo n.º 17
0
void Interactor::UnRead(Event& e) { e.unread(); }
Ejemplo n.º 18
0
bool Event::operator<(const Event& _E) const
{
  if (EventPtr->timeout >= _E.getTimeout())
    return (true);
  return (false);
}
Ejemplo n.º 19
0
//--------------------------------------------------------------------------
// Main Function
//
int main(int argc, char *argv[])
{
	if (argc > 2)
	{
		cout << "Usage: Start with ./cnw [filename] to load calendar "
				<< "or ./cnw to make new calendar." << endl;
	}

	// New Calendar is created.
	if (argc == 1)
	{
		tm* begin1 = new tm;
		begin1->tm_hour = 9;
		begin1->tm_min = 20;
		begin1->tm_mday = 10;
		begin1->tm_mon = 6 - 1;
		begin1->tm_year = 2015 - 1900;

		Event* event1 = new Event("Presentation", begin1, 30);

		list<Event*> calendar_queue;

		Calendar calendar(calendar_queue);

		calendar.addEvent(event1);
		calendar.setConnectionState(false);
		calendar.run();
		return SUCCESS;
	}

	if (strcmp("-s", argv[1]) == 0)
	{
		//Server mode
		cout << "You've entered server mode!" << endl;
		runServer();
		return SUCCESS;
	}

	// Else load calendar
	string filename = argv[1];
	ifstream file;
	file.open(filename.c_str(), std::ios::in | std::ios::binary);

	if (!file.is_open())
	{
		std::cout << "Error: file " << filename << " cannot be opened.\n";
		return ERROR;
	}

	char check_input[50];
	for (int i = 0; i < 50; i++)
		check_input[i] = 0;
	file.read(check_input, 4);

	if (!(strcmp(check_input, "CNW\0") == 0))
	{
		cout << "File corrupted!" << endl;
		return ERROR;
	}

	int num_events;
	file.read((char*) &num_events, sizeof(int));

	list<Event*> calendar_queue;
	string event_name;
	short duration;

	for (int i = 0; i < num_events; i++)
	{
		Event* event = new Event();
		tm* time = new tm();
		int tm_data;

		getline(file, event_name, '\0');
		event->setName(event_name);

		file.read((char*) &tm_data, sizeof(int));
		time->tm_mday = tm_data;
		file.read((char*) &tm_data, sizeof(int));
		time->tm_mon = tm_data;
		file.read((char*) &tm_data, sizeof(int));
		time->tm_year = tm_data;
		file.read((char*) &tm_data, sizeof(int));
		time->tm_hour = tm_data;
		file.read((char*) &tm_data, sizeof(int));
		time->tm_min = tm_data;
		file.read((char*) &tm_data, sizeof(int));
		time->tm_sec = tm_data;
		file.read((char*) &duration, sizeof(short));

		event->setStartTime(time);
		event->setDuration(duration);

		calendar_queue.push_back(event);
	}

	Calendar calendar(calendar_queue);
	calendar.setConnectionState(false);
	calendar.run();

	return SUCCESS;
}
Ejemplo n.º 20
0
bool isEventEqual::operator()(Event a, Event b) const
{
  if (a.getTimeout() == b.getTimeout())
    return (true);
  return (false);
}
Ejemplo n.º 21
0
void JSAbstractEventListener::handleEvent(Event* ele, bool isWindowEvent)
{
#ifdef KJS_DEBUGGER
    if (KJSDebugWin::instance() && KJSDebugWin::instance()->inSession())
        return;
#endif

    Event *event = ele;

    JSObject* listener = listenerObj();
    if (!listener)
        return;

    Window* window = windowObj();
    Frame *frame = window->frame();
    if (!frame)
        return;
    KJSProxy* proxy = frame->jScript();
    if (!proxy)
        return;

    JSLock lock;
  
    ScriptInterpreter* interpreter = proxy->interpreter();
    ExecState* exec = interpreter->globalExec();
  
    JSValue* handleEventFuncValue = listener->get(exec, "handleEvent");
    JSObject* handleEventFunc = 0;
    if (handleEventFuncValue->isObject()) {      
        handleEventFunc = static_cast<JSObject*>(handleEventFuncValue);
        if (!handleEventFunc->implementsCall())
            handleEventFunc = 0;
    }
  
    if (handleEventFunc || listener->implementsCall()) {
        ref();
      
        List args;
        args.append(toJS(exec, event));
      
        // Set the event we're handling in the Window object
        window->setCurrentEvent(event);
        // ... and in the interpreter
        interpreter->setCurrentEvent(event);
      
        JSValue* retval;
        if (handleEventFunc) {
            interpreter->startTimeoutCheck();
            retval = handleEventFunc->call(exec, listener, args);
        } else {
            JSObject* thisObj;
            if (isWindowEvent)
                thisObj = window;
            else
                thisObj = static_cast<JSObject*>(toJS(exec, event->currentTarget()));
            interpreter->startTimeoutCheck();
            retval = listener->call(exec, thisObj, args);
        }
        interpreter->stopTimeoutCheck();

        window->setCurrentEvent(0);
        interpreter->setCurrentEvent(0);

        if (exec->hadException()) {
            JSObject* exception = exec->exception()->toObject(exec);
            String message = exception->get(exec, messagePropertyName)->toString(exec);
            int lineNumber = exception->get(exec, "line")->toInt32(exec);
            String sourceURL = exception->get(exec, "sourceURL")->toString(exec);
            if (Interpreter::shouldPrintExceptions())
                printf("(event handler):%s\n", message.deprecatedString().utf8().data());
            frame->addMessageToConsole(message, lineNumber, sourceURL);
            exec->clearException();
        } else {
            if (!retval->isUndefinedOrNull() && event->storesResultAsString())
                event->storeResult(retval->toString(exec));
            if (html) {
                bool retvalbool;
                if (retval->getBoolean(retvalbool) && !retvalbool)
                    event->preventDefault();
            }
        }

        Document::updateDocumentsRendering();
        deref();
    }
}
Ejemplo n.º 22
0
bool isEventLess::operator()(Event a, Event b) const
{
  if (a.getTimeout() > b.getTimeout())
    return (true);
  return (false);
}
Ejemplo n.º 23
0
void Slider::handleEvent(const Event& evt)
{
	Widget::handleEvent(evt);
	if(isPointerInteractionEnabled())
	{
		Vector2f point = Vector2f(evt.getPosition().x(), evt.getPosition().y());
	
		point = transformPoint(point);

		Vector2f sliderPos = getSliderPosition();
		Vector2f sliderSize = getSliderSize();

		if(evt.getType() == Event::Up)
		{
			myPressed = false;
			if(myValueChanged)
			{
				Event e;
				e.reset(Event::ChangeValue, Service::Ui, getId());
				dispatchUIEvent(e);
			}
		}

		if(simpleHitTest(point, sliderPos, sliderSize))
		{
			if(evt.getType() == Event::Down)
			{
				myPressed = true;
				myPressPos = evt.getPosition().x();
			}
			evt.setProcessed();
		}
		if(simpleHitTest(point))
		{
			if(myPressed && evt.getType() == Event::Move)
			{
				int newValue = (point[0] + sliderSize[0] / 2) * myTicks / mySize[0]; 
				if(newValue < 0) newValue = 0;
				if(newValue > (myTicks - 1)) newValue = myTicks - 1;

				if(newValue != myValue)
				{
					myValue = newValue;
					if(!myDeferUpdate)
					{
						Event e;
						e.reset(Event::ChangeValue, Service::Ui, getId());
						dispatchUIEvent(e);
					}
					else
					{
						myValueChanged = true;
					}
				}
			}
			evt.setProcessed();
		}
	}
	if(isGamepadInteractionEnabled())
	{
		if(evt.isButtonDown(Event::ButtonLeft))
		{
			evt.setProcessed();
			myIncrement = -1;
			// Full slider change takes 2 seonds
			myIncrementTimeStep = 2.0 / myTicks;
			// Force an immediate change
			myIncrementTimer = myIncrementTimeStep;
		}
		else if(evt.isButtonDown(Event::ButtonRight))
		{
			evt.setProcessed();
			myIncrement = 1;
			// Full slider change takes 2 seonds
			myIncrementTimeStep = 2.0 / myTicks;
			// Force an immediate change
			myIncrementTimer = myIncrementTimeStep;
		}
		else if(evt.getType() == Event::Up)
		{
			myIncrement = 0;
		}
	}
}
Ejemplo n.º 24
0
int main(void)
{
	Queue bankQueue; //represents the line of customers in the bank/bank line
	PQueue eventListPQueue; //priority queue eventListPQueue for the event list

	bool tellerAvailable = true;
	loadIntoPriorityQueue(eventListPQueue); //load data into Priority Queue from file/Create and add arrival events to event list

	//waitTime = SUM(time of departure) - SUM(processing time) - SUM(time of arrival)/COUNT(EVENTS)
	unsigned int sumDepartureTime = 0;
	unsigned int sumProcessingTime = 0;
	unsigned int sumArrivalTime = 0;
	unsigned int eventCount = 0; //track how many customers came in
	float waitTime; //Calculated at the end

	cout << "Simulation Begins" << endl;

	while(!eventListPQueue.isEmpty()) //run while eventListPQueue is not empty
	{
		Event newEvent = eventListPQueue.peek();
		// Get current time
		unsigned int currentTime = newEvent.getTime(); // get time of newEvent
		if (newEvent.getType() == 'A') //check if newEvent is an arrival event
		{
			// Processes an arrival event.
			//processArrival(newEvent, eventListPQueue, bankQueue, tellerAvailable, currentTime);

			eventListPQueue.dequeue(); //Remove this event from the event list
			Event customer = newEvent; //customer referenced in arrivalEvent
			if (bankQueue.isEmpty() && tellerAvailable)
			{
				unsigned int departureTime = currentTime + customer.getLength();//currentTime + transaction time in arrivalEvent
				Event newDepartureEvent('D', departureTime, 0); //a new departure event with departureTime
				eventListPQueue.enqueue(newDepartureEvent);
				tellerAvailable = false;
			}
			else
			{
				bankQueue.enqueue(customer);
			}

			cout << "Processing an arrival event at time:\t" << customer.getTime() << endl;
			eventCount++; //count how many customers arrived
			sumArrivalTime += customer.getTime();
			sumProcessingTime += customer.getLength();
		}
		else
		{
			// Processes a departure event.
//			processDeparture(newEvent, eventListPQueue, bankQueue, tellerAvailable, currentTime);
			eventListPQueue.dequeue(); // Remove this event from the event list

			if(!bankQueue.isEmpty())
			{
				// Customer at front of line begins transaction
				Event customer = bankQueue.peek();
				bankQueue.dequeue();
				unsigned int departureTime = currentTime + customer.getLength(); //currentTime + transaction time in customer
				Event newDepartureEvent('D', departureTime, 0); //a new departure event with departureTime
				eventListPQueue.enqueue(newDepartureEvent);
			}
			else
			{
				tellerAvailable = true;
			}

			cout << "Processing a departure event at time:\t" << currentTime << endl; //temp
			sumDepartureTime += currentTime;
		}

	}

	waitTime = (float)(sumDepartureTime - sumProcessingTime - sumArrivalTime)/eventCount; //do the average wait time calculation

	cout << "Simulation Ends\n\n";
	cout << "Final Statistics:" << endl;
	cout << "\tTotal number of people processed: " << eventCount << endl;
	cout << "\tAverage amount of time spent waiting: " << waitTime << endl;

//	cout << "Bank Queue Contents:" << endl;
//	bankQueue.print();
//	cout << "Priority Queue Contents:" << endl;
//	eventListPQueue.print();
//	resultPrinterQueue(bankQueue); //print out the results
	return 0;
}
Ejemplo n.º 25
0
bool probProcessor::processEvent(Event &event)
{
    //Run2b switch
    evtno = event.getGlobal()->evtno();
    runno = event.getGlobal()->runno();
    isRun2b = event.isRun2b();  // needed because some jet eta def changed between Run2a and Run2b, fine.

    change_request(event);
    if(_debug){
      cout<<"trigger version now has "<< _trigger_version.size()<<" entries."<<endl;
      cout<<"triglists: ";
      for (int i=0; i < _trigger_version.size(); i++) cout<<_trigger_version[i]<<" ";
      cout<<endl;
    }
    //First we use a created a map to grab the possibly empty information from
    //the previous processor, and grab this information
    mEvtw.clear();
    event.get("passedEvtw", mEvtw);

    _corrfactors.clear();
    _derivatives.clear();

    //Get the passed TObject information
    event.get("passedEM", EM);
    event.get("passedMU", MU);
    event.get("passedJET", JET);
    event.get("passedMET", MET);
    event.get("passedTAU", TAU);

    event.get("passedNEM", NEM);
    event.get("passedNMU", NMU);
    event.get("passedNJET", NJET);
    event.get("passedNTAU", NTAU);
    event.get("passedINSTLUM",INSTLUM);

    // decide whether to weight the periods, or simply pick one
    _triggerPeriod = "none";
    event.get("TriggerPeriod", _triggerPeriod);

    //We grab the stats pointer from the event
    //event.get("StatPointer", _stat);

    //Now we run through the map of the triggerlist version and luminousity
    //and calculate the probabilities.
    //This calls calcProb(version) which acts as the heart of the calculations.
    //Note: mEvtw[_channel] is set internally in this method.
    eventWeight(mEvtw);
    

    //If the user wishes outputs using the sigma variations in the event,
    //this will call calcProb(version) with the appropriate sigma variations.
    //Note: mEvtw[_channel sigma] is set internally in this method.
    if(_sigma != "false") {

        eventWeightSigma(mEvtw);
    }

    //Now we put these values into the event.
    event.put("passedEvtw", mEvtw);

    //Pass full object weight information to event
    //(needed for evaluation of efficiency uncertainties)
    vector<string> weightnames,derivnames;
    for (map<string, vector<EffVal> >::iterator it = _corrfactors.begin();
	 it!=_corrfactors.end(); it++) {
      if (it->second.size()>0) {
	event.put(name()+":weight_vector_"+it->first,it->second);
	weightnames.push_back(name()+":weight_vector_"+it->first);
	derivnames.push_back(name()+":derivative_vector_"+it->first);
      }
    }
    for (map<string, vector<double> >::iterator it = _derivatives.begin();
	 it!=_derivatives.end(); it++) {
      if (it->second.size()>0) {
	event.put(name()+":derivative_vector_"+it->first,it->second);
      }
    }

    // add list of weight and derivative vectors provided by this processor
    // to list of weight and derivative vectors already stored by other
    // caf_trigger processors (if any)
    vector<string> existing_weightnames,existing_derivnames;
    if (event.get("caf_trigger_weight_vectors",existing_weightnames)) {
      weightnames.insert(weightnames.end(),existing_weightnames.begin(),
			 existing_weightnames.end());
    }
    if (event.get("caf_trigger_derivative_vectors",existing_derivnames)) {
      derivnames.insert(derivnames.end(),existing_derivnames.begin(),
			existing_derivnames.end());
    }
    event.put("caf_trigger_weight_vectors",weightnames);
    event.put("caf_trigger_derivative_vectors",derivnames);

    return true;
}
Ejemplo n.º 26
0
int addTestEvent(EventModel &model,
                 Event::EventType type,
                 Event::EventDirection direction,
                 const QString &account,
                 int groupId,
                 const QString &text,
                 bool isDraft,
                 bool isMissedCall,
                 const QDateTime &when,
                 const QString &remoteUid,
                 bool toModelOnly,
                 const QString messageToken)
{
    Event event;
    event.setType(type);
    event.setDirection(direction);
    event.setGroupId(groupId);
    event.setStartTime(when);
    if (type == Event::CallEvent)
        event.setEndTime(when.addSecs(100));
    else
        event.setEndTime(event.startTime());
    event.setLocalUid(account);
    if (remoteUid.isEmpty()) {
        event.setRemoteUid(type == Event::SMSEvent ? "555123456" : "td@localhost");
    } else {
        event.setRemoteUid(remoteUid);
    }
    event.setFreeText(text);
    event.setIsDraft( isDraft );
    event.setIsMissedCall( isMissedCall );
    event.setMessageToken(messageToken);
    if (model.addEvent(event, toModelOnly)) {
        addedEventIds.insert(event.id());
        return event.id();
    }
    return -1;
}
Ejemplo n.º 27
0
void EventHandler::tick()
{
    switch(m_emSrvType)
    {
    case Srv_UnDefine:
        break;
    case Srv_Game:
    {
        if(m_ltUpdateTime > 0)
        {
            if(reversion_ - m_lLastCheckTime > m_ltUpdateTime)
            {
                m_lLastCheckTime = reversion_;
                Event* e = eq_->allocateEvent();
                e->set_cmd(EVENT_TIMER);
                e->set_state(Status_Normal_Game);
                e->set_time(0);
                eq_->safePushEvent(e);

                /*m_nTimerTick ++;
                if(m_nTimerTick >= 5*60)
                {
                	Event* e = eq_->allocateEvent();
                	e->set_cmd(EVENT_TIMER_5_TICK);
                	e->set_state(Status_Normal_Game);
                	e->set_time(0);
                	eq_->safePushEvent(e);
                	m_nTimerTick = 0;
                }

                m_nTimerTickLuckyNum++;
                if(m_nTimerTickLuckyNum >= 60)
                {
                	Event* e = eq_->allocateEvent();
                	e->set_cmd(EVENT_LUCKY_NUM);
                	e->set_state(Status_Normal_Game);
                	e->mutable_luckynummsg()->set_type( 1 );//·¢ËÍÊý¾Ý
                	e->set_time(0);
                	eq_->safePushEvent(e);
                	m_nTimerTickLuckyNum = 0;
                }*/
            }
        }
        /*if (m_IsSendOnceMsg)
        {
        	m_IsSendOnceMsg = false;

        	Event* e = eq_->allocateEvent();
        	if (e)
        	{
        		e->set_cmd(EVENT_USER_HOURMETER_BRAODCAST_START);
        		e->set_state(Status_Normal_Game);
        		e->set_time(0);
        		eq_->safePushEvent(e);
        	}

        	e = eq_->allocateEvent();
        	if (e)
        	{
        		e->set_cmd(EVENT_UPDATE_BROADCAST_ROBOT);
        		e->set_state(Status_Normal_Game);
        		e->set_time(0);
        		e->mutable_updatebroadcastrobot()->set_nype(BROADCAST_ROBOT_MSG_UPDATE);
        		eq_->safePushEvent(e);
        	}

        	e = eq_->allocateEvent();
        	e->set_cmd(EVENT_TIMER_5_TICK);
        	e->set_state(Status_Normal_Game);
        	e->set_time(0);
        	eq_->safePushEvent(e);
        }*/
    }
    break;
    case Srv_Country:
    {
        if(m_ltUpdateTime > 0)
        {
            if(reversion_ - m_lLastCheckTime > m_ltUpdateTime)
            {
                m_lLastCheckTime = reversion_;
                Event* e = eq_->allocateEvent();
                e->set_cmd(EVENT_COUNTRY_TIMER);
                e->set_state(Status_Normal_Game);
                e->set_time(0);
                eq_->safePushEvent(e);
            }
        }
    }
    break;
    /*case Srv_Region:
    	{
    		if(m_ltUpdateTime > 0)
    		{
    			if(reversion_ - m_lLastCheckTime > m_ltUpdateTime)
    			{
    				m_lLastCheckTime = reversion_;
    				Event* e = eq_->allocateEvent();
    				e->set_cmd(EVENT_REGION_TIMER);
    				e->set_state(Status_Normal_Game);
    				e->set_time(0);
    				eq_->safePushEvent(e);

    				e = eq_->allocateEvent();
    				e->set_cmd(EVENT_REGIONCOUNTRY_TIMER);
    				e->set_state(Status_Normal_Game);
    				e->set_time(0);
    				eq_->safePushEvent(e);
    			}
    		}
    	}
    	break;
    case Srv_Fight:
    	{
    		if(m_ltUpdateTime > 0)
    		{
    			if(reversion_ - m_lLastCheckTime > m_ltUpdateTime)
    			{
    				m_lLastCheckTime = reversion_;
    				Event* e = eq_->allocateEvent();
    				e->set_cmd(EVENT_FIGHT_TIMER);
    				e->set_state(Status_Normal_Game);
    				e->set_time(0);
    				eq_->safePushEvent(e);

    			}
    		}
    	}
    	break;
    case Srv_Rank:
    	{
    		if(m_ltUpdateTime > 0)
    		{
    			if(reversion_ - m_lLastCheckTime > m_ltUpdateTime)
    			{
    				m_lLastCheckTime = reversion_;
    				Event* e = eq_->allocateEvent();
    				e->set_cmd(EVENT_RANK_TIMER);
    				e->set_state(Status_Normal_Game);
    				e->set_time(0);
    				eq_->safePushEvent(e);

    			}
    		}
    	}
    	break;*/
    default:
        break;
    }

    if(dh_ != NULL)
    {
        dh_->tick();
    }
}
Ejemplo n.º 28
0
bool FtlImpl_Bast::random_merge(LogPageBlock *logBlock, long lba, Event &event)
{
	/* Do merge (n reads, n writes and 2 erases (gc'ed))
	 * 1. Write page to new data block
	 * 1a Promote new log block.
	 * 2. Create BLOCK_SIZE reads
	 * 3. Create BLOCK_SIZE writes
	 * 4. Invalidate data block
	 * 5. promote new block as data block
	 * 6. put data and log block into the invalidate list.
	 */

	Address eventAddress = Address(event.get_logical_address(), PAGE);
	Address newDataBlock = Block_manager::instance()->get_free_block(DATA, event);

	int t=0;
	for (uint i=0;i<BLOCK_SIZE;i++)
	{
		// Lookup page table and see if page exist in log page
		Address readAddress;
		if (logBlock->pages[i] != -1)
			readAddress.set_linear_address(logBlock->address.get_linear_address() + logBlock->pages[i], PAGE);
		else if (data_list[lba] != -1)
			readAddress.set_linear_address(data_list[lba] + i, PAGE);
		else
			continue; // Empty page

		if (controller.get_state(readAddress) == EMPTY)
			continue;

		if (controller.get_state(readAddress) == INVALID) // A page might be invalidated by trim
			continue;

		Event readEvent = Event(READ, event.get_logical_address(), 1, event.get_start_time());
		readEvent.set_address(readAddress);
		controller.issue(readEvent);

		Event writeEvent = Event(WRITE, event.get_logical_address(), 1, event.get_start_time()+readEvent.get_time_taken());
		writeEvent.set_address(Address(newDataBlock.get_linear_address() + i, PAGE));
		writeEvent.set_payload((char*)page_data + readAddress.get_linear_address() * PAGE_SIZE);
		writeEvent.set_replace_address(readAddress);
		controller.issue(writeEvent);

		//event.consolidate_metaevent(writeEvent);
		event.incr_time_taken(writeEvent.get_time_taken() + readEvent.get_time_taken());
		// Statistics
		controller.stats.numFTLRead++;
		controller.stats.numFTLWrite++;
		controller.stats.numWLRead++;
		controller.stats.numWLWrite++;
		t++;
	}

//	printf("t %i\n",t);

	// Invalidate inactive pages (LOG and DATA

	Block_manager::instance()->erase_and_invalidate(event, logBlock->address, LOG);

	if (data_list[lba] != -1)
	{
		Address a = Address(data_list[lba], PAGE);
		Block_manager::instance()->erase_and_invalidate(event, a, DATA);
	}

	// Update mapping
	data_list[lba] = newDataBlock.get_linear_address();
	update_map_block(event);

	dispose_logblock(logBlock, lba);

	controller.stats.numLogMergeFull++;
	return true;
}
Ejemplo n.º 29
0
void mainanalyze(TTree *particletree, const float beam_momentum, const TString output_filename="Extracted_distributions.root")
{
	cout << "Beta calculated for nucleon mass: " << nucleon_mass << " GeV/c^2 and beam momentum: " << beam_momentum << endl;

	float angle,
		  p1, p2,
		  pt1, pt2,
		  pz_cms1, pz_cms2,
		  E1, E2,
		  E_prot,
		  inv_mass,
		  gbE1, gbE2,
		  theta1, theta2,
		  y1, y2,
		  y_prot_cms,
		  eta1, eta2,
		  angle_j,
		  angle_diff,
		  y_diff,
		  eta_diff;

	bool	positive,
			positive_j;

	int	n[3];
	unsigned int all_particles=0;
	UInt_t	i,j;

	TLorentzVector v1, v2, v;

	unsigned correlations = 0, pos_correlations = 0, neg_correlations = 0, all_correlations = 0, unlike_correlations = 0;

	Event *event = new Event();
	Particle *particleA, *particleB;
	particletree->SetBranchAddress("event",&event);
	Long64_t treeNentries = particletree->GetEntries();
	cout << "Number of events: " << treeNentries << endl;
	Long64_t ev;

	Particles particles;
	Histos histos;
	TFile *root_output_file;

	histos.init();
	particles.init(&histos, beam_momentum);
	particles.newEvent(true);
	root_output_file = new TFile(output_filename,"recreate");

	cout << "Writing events" << endl;

	for(ev=0; ev<treeNentries; ++ev)
	{
		particletree->GetEntry(ev);

		n[Neg] = n[All] = n[Pos] = 0;

		for(i=0; i<event->GetNpa(); ++i)
		{
			particleA = event->GetParticle(i);

			pt1 = TMath::Sqrt(TMath::Power(particleA->GetPx(),2)+TMath::Power(particleA->GetPy(),2));
			p1 = TMath::Sqrt(TMath::Power(particleA->GetPx(),2)+TMath::Power(particleA->GetPy(),2)+TMath::Power(particleA->GetPz(),2));
			E1 = TMath::Sqrt(pion_mass*pion_mass+p1*p1);
			E_prot = TMath::Sqrt(proton_mass*proton_mass+p1*p1);
			y_prot_cms = 0.5*TMath::Log((E_prot+particleA->GetPz())/(E_prot-particleA->GetPz())) - particles.y_cms;
			v1.SetPxPyPzE(particleA->GetPx(),particleA->GetPy(),particleA->GetPz(),E1);

			//Minimal pT cut
//			if(pt1 < 0.2)
//				continue;

			y1 = 0.5*TMath::Log((E1+particleA->GetPz())/(E1-particleA->GetPz())) - particles.y_cms;
			angle = TMath::ATan2(particleA->GetPy(), particleA->GetPx());

			particles.analyze(particleA,beam_momentum);

			positive = particleA->isPositive();

			if(event->GetNpa() > 1)
			{
				for(j=i+1; j<event->GetNpa(); ++j)
				{
					particleB = event->GetParticle(j);

					pt2 = TMath::Sqrt(TMath::Power(particleB->GetPx(),2)+TMath::Power(particleB->GetPy(),2));
					p2 = TMath::Sqrt(TMath::Power(particleB->GetPx(),2)+TMath::Power(particleB->GetPy(),2)+TMath::Power(particleB->GetPz(),2));

					//cout << "p1 = " << p1 << " | p2 = " << p2 << endl;

					E2 = TMath::Sqrt(pion_mass*pion_mass+p2*p2);
					E_prot = TMath::Sqrt(proton_mass*proton_mass+p2*p2);
					y_prot_cms = 0.5*TMath::Log((E_prot+particleB->GetPz())/(E_prot-particleB->GetPz())) - particles.y_cms;
					v2.SetPxPyPzE(particleB->GetPx(),particleB->GetPy(),particleB->GetPz(),E2);

					v = v1 + v2;
					inv_mass = v.M();

//					if(inv_mass < 0.285) //GeV dipion (280 MeV) + Coulomb interactions (5 MeV)
//						continue;

					histos.histInvMass->Fill(inv_mass);

					//cout << "E1 = " << E1 << " | E2 = " << E2 << endl;

					gbE1 = particles.calc_gbE(E1);
					gbE2 = particles.calc_gbE(E2);

					//cout << "Beta factor: " << particles.beta << endl;
					//cout << "Gamma factor: " << particles.gamma << endl;
					//cout << "gamma*beta*E1: " << gbE1 << " | gamma*beta*E2: " << gbE2 << endl;

					pz_cms1 = particles.gamma*particleA->GetPz() - gbE1;
					pz_cms2 = particles.gamma*particleB->GetPz() - gbE2;

					//cout << "pz_cms1 = " << pz_cms1 << " | pz_cms2 = " << pz_cms2 << endl;

					y2 = 0.5*TMath::Log((E2+particleB->GetPz())/(E2-particleB->GetPz())) - particles.y_cms;
					
					//Minimal pT cut
//					if(pt2 < 0.2)
//						continue;

					angle_j = TMath::ATan2(particleB->GetPy(), particleB->GetPx());

					//cout << "y1 = " << y1 << " | y2 = " << y2 << endl;

					theta1 = TMath::Abs(TMath::ATan2(pt1,pz_cms1));
					theta2 = TMath::Abs(TMath::ATan2(pt2,pz_cms2));

					//cout << "theta1 = " << theta1 << " | theta2 = " << theta2 << endl;

					eta1 = -TMath::Log(TMath::Tan(0.5*theta1));
					eta2 = -TMath::Log(TMath::Tan(0.5*theta2));

					//cout << "eta1 = " << eta1 << " | eta2 = " << eta2 << endl;
					//cout << "angle1 = " << angle << " | angle2 = " << angle_j << endl;

					positive_j = particleB->isPositive();
					if((angle_diff = TMath::Abs(angle-angle_j)) > TMath::Pi())
						angle_diff = 2*TMath::Pi()-angle_diff;
					y_diff = TMath::Abs(y1-y2);
					eta_diff = TMath::Abs(eta1-eta2);

					histos.histDyDphiAll->Fill(angle_diff, y_diff);
					histos.histDetaDphiAll->Fill(angle_diff, eta_diff);

					++all_correlations;

					if((positive_j == true) && (positive == true))
					{
						++correlations;
						++pos_correlations;

						histos.histDyDphiPos->Fill(angle_diff, y_diff);
						histos.histDetaDphiPos->Fill(angle_diff, eta_diff);
					}
					else if((positive_j == false) && (positive == false))
					{
						++correlations;
						++neg_correlations;
						histos.histDyDphiNeg->Fill(angle_diff, y_diff);
						histos.histDetaDphiNeg->Fill(angle_diff, eta_diff);
					}
					else
					{
						++unlike_correlations;
						histos.histDyDphiUnlike->Fill(angle_diff, y_diff);
						histos.histDetaDphiUnlike->Fill(angle_diff, eta_diff);
					}
				}
			}

			all_particles++;
			n[All]++;

			if(positive)
				n[Pos]++;
			else
				n[Neg]++;

		}

		//cout << "\rEvent " << ev;
		if(!(ev%10))
			cout << "Event " << ev << " / " << treeNentries << endl;

		particles.newEvent();

	}

	//event--;

	cout << endl << "Filling with zeros" << endl;

	cout << "All correlations: " << all_correlations << endl;
	cout << "Like-sign correlations: " << correlations << endl;
	cout << "Positive correlations: " << pos_correlations << endl;
	cout << "Negative correlations: " << neg_correlations << endl;
	cout << "=======================" << endl << "All particles: " << all_particles << ", all events: " << ev << endl;
	cout << "Mean multiplicity: " << (((double)all_particles)/ev) << endl;

	//histos.histCharged->AddBinContent(1,zeros);
	//histos.histChargedNeg->AddBinContent(1,zeros);
	//histos.histChargedPos->AddBinContent(1,zeros);
	//	histos.histCharged->ResetStats();
	//	histos.histChargedNeg->ResetStats();
	//	histos.histChargedPos->ResetStats();
	root_output_file->cd();
	histos.write();
	histos.clear();
	root_output_file->Close();
}
Ejemplo n.º 30
0
void Trace::slowCompressLoop(int window){
  static int warned_once = 0;
  int distance;
  Event *iter;
  iteration_t *rtn;
  iteration_t *iteration;
  vector<iteration_t *> iterations;
  vector<iteration_t *>::iterator iteration_it;
  int i;

  int head_flag;      /* Whether target head has been found. */
  int match_flag;     /* Whether a node matching target head has been found. */
  int found_flag;     /* */

  int target_length=1, merge_length=1;
  int target_real_length, merge_real_length;
  double ratio;

  Event *target_tail = NULL;
  Event *target_head = NULL;
  Event *merge_tail = NULL;
  Event *merge_head = NULL;

#if defined FEATURE_SIG_DIFF && FEATURE_SIG_DIFF > 0
  Event* search;
  StackSig* target_sig;
  StackSig* merge_sig;
#endif

  distance = 0;
  head_flag = 0;
  found_flag = 1;

  do {
    target_tail = tail;

    if(found_flag || !head_flag) {
      /* if the found flag is set - start a new search */
      target_head = target_tail;
      distance = 0;
      target_length = merge_length = 1;
    } else {
      /* otherwise continue a previous search */
      target_head = target_head->prev;
      target_length++;
      merge_length = 1;
    }

    head_flag = 0;
    match_flag = 0;
    found_flag = 0;


    /* Search backwards in the queue until we find a match with the target tail.
     * After this loop is done, either head_flag will be false (and nothing found)
     * or the head will be just after the matching tail. */
    while(target_head->prev != NULL && (window == -1 || window > distance)) {
      if( !target_head->checkLoc(MEMBER)
          && !target_head->checkLoc(PENDING_MEMBER)
          && !target_head->checkLoc(PENDING_LEADER)
          && !target_head->checkLoc(PENDING_TAIL)
          && target_tail->sigMatch(target_head->prev)
          && target_tail->opMatch(target_head->prev)){
        head_flag = 1;
        break;
      }
      target_head = target_head->prev;
      target_length++;
      distance++;
    }

    /* didn't find head: can skip the rest. */
    if (!head_flag) {
      /* Warn if the window was exceeded, but only warn once. */
      if(!warned_once && window != -1 && window <= distance) {
        cerr<<"warning: window exceeded - possible compression missed (window: "<<window<<"   distance: "<<distance<<")"<<endl;
        warned_once = 1;
      }
      break;
    }

    /* If the head flag is true, we've got the target_tail, the target_head, and
     * the merge_tail (just before target_head). Now we can try to find a match
     * for the target_head somewhere before the merge tail.  This will be merge_head.*/
    merge_head = target_head->prev;
    merge_tail = target_head->prev;

    while(merge_head != NULL) {
      if( !merge_head->checkLoc(MEMBER)
          && merge_head->sigMatch(target_head)
          && merge_head->opMatch(target_head)){

        target_real_length = realLength(target_head, target_tail);
        merge_real_length = realLength(merge_head, merge_tail);
        assert(target_real_length > 0 && merge_real_length > 0);
        if(target_real_length > merge_real_length){
          ratio = (double)merge_real_length / (double)target_real_length;
        } else {
          ratio = (double)target_real_length / (double)merge_real_length;
        }
        if(1 - ratio < MAX_LENGTH_DIFF){
#if defined FEATURE_SIG_DIFF && FEATURE_SIG_DIFF > 0
          /* heuristic that helps to identify the best match */
          if( (target_tail->sigEquals(merge_tail) && target_head->sigEquals(merge_head))
              || (merge_length == target_length && merge_length == 1 )  )
#endif
            if(merge_head->checkLoc(PENDING_MEMBER) || merge_head->checkLoc(PENDING_LEADER)
                || merge_head->checkLoc(PENDING_TAIL)){
              for(iter = merge_head, i = 0; iter; iter = iter->prev, i++){
                iterations = pendingIterations.getIterationsByTargetHead(iter);
                if(iterations.size() == 1){
                  if(iterations[0]->target_tail->getId() >= merge_head->getId()){
                    break;
                  }
                }else{
                  /* only one pending iteration can have iter as the
                   * target_head, because it's impossible to choose a
                   * PENDING_LEADER event as the target_head */
                  assert(iterations.size()==0);
                }
                iterations.clear();
              }
              if(iterations.size() == 1 && (merge_tail == iterations[0]->target_tail)){
                match_flag = 1;
                break;
              }
            } else {
              match_flag = 1;
              break;
            }
        }
      }
      merge_head = merge_head->prev;
      merge_length++;
    }

    /* If we didn't find the merge head, we continue to the next iteration to try to
     * find a longer iteration. */
    if(!match_flag)
      continue;
    found_flag = 1;

    /* mark the loop iteration */
    /* 1. check if the current iteration is a trailing iteration, if
     * it is a trailing iteration, only the case where merge_tail equals
     * to the tail of the pervious iteration is allowed */
    if(merge_head->checkLoc(PENDING_MEMBER) || merge_head->checkLoc(PENDING_LEADER)
        || merge_head->checkLoc(PENDING_TAIL)){
      for(iter = merge_head, i = 0; iter; iter = iter->prev, i++){
        iterations = pendingIterations.getIterationsByTargetHead(iter);
        if(iterations.size() == 1){
          //if(iterations[0]->target_length - i > 0){
          if(iterations[0]->target_tail->getId() >= merge_head->getId()){
            break;
          }
        }else{
          /* only one pending iteration can have iter as the
           * target_head, because it's impossible to choose a
           * PENDING_LEADER event as the target_head */
          assert(iterations.size()==0);
        }
        iterations.clear();
      }

      if(iterations.size() == 1 && (merge_tail == iterations[0]->target_tail)){
        iterations = pendingIterations.getIterationsByTargetTail(merge_tail);
        for(iteration_it = iterations.begin();
            iteration_it != iterations.end(); iteration_it++)
          for(iter = (*iteration_it)->target_tail;
              iter != (*iteration_it)->target_head; iter = iter->prev)
            if(iter == merge_head){
              (*iteration_it)->target_tail->unsetLoc(PENDING_TAIL);
              (*iteration_it)->target_tail->setLoc(PENDING_MEMBER);
              pendingIterations.updateIterationTargetTail((*iteration_it), target_tail);
              (*iteration_it)->target_length += target_length;
              break;
            }

      } else {
        found_flag = 0;
        continue;
      }
    }


#if defined FEATURE_SIG_DIFF && FEATURE_SIG_DIFF > 0
    if(!target_tail->sigEquals(merge_tail)){
      target_sig = target_tail->getSignature();
      merge_sig = merge_tail->getSignature();
      search = target_tail;
      while(search != merge_tail){
        search->updateStatsSig(target_sig, merge_sig);
        search = search->prev;
      }
      target_tail->setSignature(*merge_sig);
    }
    if(target_tail != target_head && !target_head->sigEquals(merge_head)){
      target_sig = target_head->getSignature();
      merge_sig = merge_head->getSignature();
      search = target_tail;
      while(search != merge_tail){
        search->updateStatsSig(target_sig, merge_sig);
        search = search->prev;
      }
      target_head->setSignature(*merge_sig);
    }
#endif


    /* 2. if merge_head ... merge_tail is a pending iteration, merge it */
    iterations = pendingIterations.getIterationsByTargetHead(merge_head);
    rtn = NULL;
    for(iteration_it = iterations.begin(); iteration_it != iterations.end(); iteration_it++){
      if((*iteration_it)->target_head == merge_head && (*iteration_it)->target_tail == merge_tail){
        iteration = *iteration_it;
        rtn = compressLoopLCS(iteration);
        updateIds(rtn->merge_head);
        break;
      }
    }

    /* 3. mark the current iteration as pending */
    if(rtn){
      pendingIterations.create(rtn->merge_head, rtn->merge_tail, rtn->merge_length,
          target_head, target_tail, target_length);
      delete rtn;
    } else {
      pendingIterations.create(merge_head, merge_tail, merge_length, target_head, target_tail, target_length);
      for(iter = merge_tail; iter != merge_head && iter != NULL; iter=iter->prev)
        iter->setLoc(MEMBER);
      assert(iter);
      iter->setLoc(LEADER);
    }
    /* mark the events in the target iteration as PENDING */
    target_tail->setLoc(PENDING_TAIL);
    if(target_tail != target_head){
      for(iter = target_tail->prev; iter != target_head && iter != NULL; iter = iter->prev)
        iter->setLoc(PENDING_MEMBER);
    }
    target_head->setLoc(PENDING_LEADER);

  } while(head_flag && !found_flag);

} /* slowCompressLoop */