Exemplo n.º 1
0
 void close() {
     AutoLock hold(lock);
     closed = true;
     queue.clear();
     JS_NOTIFY_ALL_CONDVAR(condvar);
 }
int HuffmanCode::zip(char* inputFile, char* outputFile) {

	CStopWatch time;
	time.startTimer();

	cout<<"Zipping.."<<endl;

	// Declare variable
	Reader *reader = new Reader(inputFile);		// Readfile object
	Writer *writer = new Writer(outputFile);	// Writefile object
	HCZHeader header;							// Header object


	Queue priQueue;							// Creat a Queue
	Node* huffmantree = NULL;				// root of Huffman tree

	char **codemap;// Map of chareacter code
	char *code;						// temp of code

	int bodysize = 0;				// Sum of bit in body
	int totalcharater = 0;			// Sum of character in text
	int usedcharacter = 0;			// Number of character used in txt
	int totalbit = 0;				// Total bit of coding map

	// Initialize the table of character code
	codemap = new char*[256];
	for(int i = 0; i < 256; i++){
    	codemap[i] = new char[16];
    	memset(codemap[i],'\0',strlen(codemap[i]));
    }

	// Initialize the temp variable to save encode
    code = new char[16];
    memset(code,'\0',strlen(code));
    code[0]='0';

	//	Count character and add to the Queue
	while(reader->isHasNext()){
		priQueue.freq(reader->readChar());
	}
	delete reader;

    // Get number of used character
    usedcharacter = priQueue.getCount();

    // Sort the Queue
	priQueue.sort();

	// Get the huffman tree
	huffmantree = priQueue.creatHuffmanTree();

	// Conver huffman tree to code map and get nessessary information
    convertHuffmanToMap(codemap,huffmantree,code,bodysize,totalcharater,totalbit);

    // Set important info to Header
    header.setBodySize(bodysize);
    header.setTotal(usedcharacter,totalbit);

    // Set codelist to header
    for(int i = 0 ; i < 256 ; i++){
    	if(codemap[i][0] != '\0'){
    		header.set(i,strlen(codemap[i]),codemap[i]);
    	}
    }

    // Writer header to file
    header.write(writer);

    // Encode file
    reader = new Reader(inputFile);
    char k;
    int limit;
    while(reader->isHasNext()){

    	k = reader->readChar();
    	limit = strlen(codemap[char2Int(k)]);

    	for(char j = 0 ; j < limit ; j++){
    		writer->writeBit(codemap[char2Int(k)][char2Int(j)] - '0');
    	}
    }

    delete reader;
    delete writer;
    cout<< "Total character encoded: "<<totalcharater<<endl;
    cout<<"Done!..."<<endl;
    time.stopTimer();
    cout<<"Excution time: "<<time.getElapsedTime()<<"s"<<endl;
    return SUCCESS;
}
Exemplo n.º 3
0
Mylist<double>* BCAlg:: computeBC(Mylist<BCUser*> &userList)//Bc method
{
	for (int i=0; i<userList.size(); i++){
		userList.at(i)->bc=0;//sets all of the bc scores of the users to 0.
	}	
	
	for(int i=0; i<userList.size(); i++){
		for (int j=0; j<userList.size(); j++){
			userList.at(j)->clearPred();//clears the predecessor array of the user
			userList.at(j)->numsp=0;//sets the num of shortest paths from user i to user j to 0
			userList.at(j)->dist=-1;//sets the distance from user i to user j to 0
			userList.at(j)->delta=0.0;//sets the change value to 0
		}
		userList.at(i)->numsp=1;//sets the # of shortest paths for user i to 1
		userList.at(i)->dist=0;// sets the distance for user 1 to 0
		Stack<BCUser*> st;//creates a stack of BCuser*'s
		Queue<BCUser*> q;//creates a queue of BCuser*'s
		q.push_back(userList.at(i));//adds specified user to the queue
		
		while (!q.empty()){//first in first out, while queue isn't empty
			BCUser* v;//creates a bcuser*
			
			v = q.front();//sets temp v to first value of the queue
			q.pop_front();//remove top of the queue 
			st.push(v);//push the temp bcuser to the stack
			for(int w =0; w< v->getFriendsSize(); w++){
			int u= v->getFriendAt(w);
				if (userList.at(u)->dist == -1){//if user v's friend at w, has a dist of -1
					q.push_back(userList.at(u));//push back user v's friend at w onto the queue
					userList.at(u)->dist=v->dist+1;//set user v's friend at w distance equal to one more than user v's distance
				}
				if (userList.at(u)->dist == v->dist+1){//if user v's friend at w distance is equal to one more than user v's distance
					userList.at(u)->numsp = userList.at(u)->numsp  + v->numsp;//user v's friend at w number of shortest paths is itself plus v's number of shortest paths
					userList.at(u)->preds.push_back(v->getId());//push back v onto predecessor of user v's friend at w
					}
			}
		}
		while (!st.empty()){//last in first out
			BCUser* w = st.top(); //creates a temp bcuser
			st.pop(); //removes w from the stack
			for(int v=0; v < w->preds.size(); v++){//loops through preds of w
			int u= w->preds.at(v);//sets u to the pred of w at v
				//sets the delta of the  userList at u
				userList.at(u)->delta =userList.at(u)->delta + ((userList.at(u)->numsp)/(w->numsp))*(1+(w->delta));
			}
			w->bc = w->bc + w->delta;//makes bc at w equal to itself plus the change (delta)
			}
		   }		  
		
		Mylist<double>*scores= new Mylist<double>();//dynamically allocates scores Mylist<double>
		for (int i=0; i<userList.size(); i++){
			(*scores).push_back(userList.at(i)->bc);//pushes back all of the userList bc values to the scores Mylist
		}
		double min, max;
		min = userList.at(0)->bc;//sets min to first value
		max = userList.at(0)->bc;//sets max to first value
		for(int x=0; x<userList.size(); x++){
			if (userList.at(x)->bc >=max){
				max= userList.at(x)->bc;//goes through userlist, if bc value at x is greater than max, sets max to that userlist bc
			}
			if (userList.at(x)->bc <=min){
				min = userList.at(x)->bc;//goes through userlist, if bc value at x is less than min, sets min to that userlist bc
			}	
		}
		for (int y=0; y<userList.size(); y++){
			(*scores)[(userList.at(y)->getId())]= (((*scores).at(y))-min)/(max-min);//sets scores at userlist of the id 	
		}
		for (int i=0; i<userList.size(); i++){
			userList.at(i)->bc= (*scores).at(i);//sets the bc values of userlist to the normalized bc scores
		}
		
	return scores;	
	return 0;
}
Exemplo n.º 4
0
void ComTdbUdr::displayContents(Space *space, ULng32 flag)
{
  ComTdb::displayContents(space, flag & 0xFFFFFFFE);

  if (flag & 0x00000008)
  {
    const size_t sz = sizeof(short);
    char buf[512];

    str_sprintf(buf, "\nFor ComTdbUdr :");
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    Lng32 lowFlags = (Lng32) (flags_ % 65536);
    Lng32 highFlags = (Lng32) ((flags_ - lowFlags) / 65536);
    str_sprintf(buf, "flags = %b%b", highFlags, lowFlags);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    if (sqlName_)
    {
      char *s = sqlName_;
      str_sprintf(buf, "routineName = %s", s);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    }

    if (routineName_)
    {
      char *s = routineName_;
      str_sprintf(buf, "externalName = %s", s);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    }

    if (containerName_)
    {
      char *s = containerName_;
      str_sprintf(buf, "externalFile = %s", s);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    }

    if (externalPath_)
    {
      char *s = externalPath_;
      str_sprintf(buf, "externalPath = %s", s);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    }

    if (librarySqlName_)
    {
      char *s = librarySqlName_;
      str_sprintf(buf, "librarySqlName = %s", s);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    }

    // Some strings come from the user and there is no limit on the
    // maximum length. For these strings we will print two lines, the
    // first a header line and the second the actual string. For
    // example, the Java signature will look like this in the SHOWPLAN
    // output:
    //
    // signature =
    // (Ljava/lang/Float;[Ljava/lang/Float;)V
    //
    const char *s1;
    const char *s2;

    if (routineSignature_)
    {
      s1 = "\nsignature = ";
      s2 = routineSignature_;
      space->allocateAndCopyToAlignedSpace(s1, str_len(s1), sz);
      space->allocateAndCopyToAlignedSpace(s2, str_len(s2), sz);
    }

    if (runtimeOptions_)
    {
      s1 = "\nruntimeOptions = ";
      s2 = runtimeOptions_;
      space->allocateAndCopyToAlignedSpace(s1, str_len(s1), sz);
      space->allocateAndCopyToAlignedSpace(s2, str_len(s2), sz);
    }

    if (runtimeOptionDelimiters_)
    {
      s1 = "\noptionDelimiters = ";
      s2 = runtimeOptionDelimiters_;
      space->allocateAndCopyToAlignedSpace(s1, str_len(s1), sz);
      space->allocateAndCopyToAlignedSpace(s2, str_len(s2), sz);
    }

    str_sprintf(buf, "\nnumParameters = %d, maxResultSets = %d",
                numParams_, maxResultSets_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    
    str_sprintf(buf, "numInputValues = %d, numOutputValues = %d",
                numInputValues_, numOutputValues_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    
    str_sprintf(buf, "requestBufferSize = %d, replyBufferSize = %d",
                requestSqlBufferSize_, replySqlBufferSize_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    
    str_sprintf(buf, "requestRowLength = %d, replyRowLength = %d",
                requestRowLen_, replyRowLen_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    
    str_sprintf(buf, "outputRowLen = %d, stateAreaSize = %d",
                outputRowLen_, stateAreaSize_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    
    str_sprintf(buf, "requestTuppIndex = %d, replyTuppIndex = %d",
                (Int32) requestTuppIndex_, (Int32) replyTuppIndex_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    str_sprintf(buf, "udrType = %d, languageType = %d",
                (Int32) udrType_, (Int32) languageType_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    str_sprintf(buf, "parameterStyle = %d, sqlAccessMode = %d",
                (Int32) paramStyle_, (Int32) sqlAccessMode_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    str_sprintf(buf, "transactionAttributes = %d", (Int32) transactionAttrs_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    str_sprintf(buf, "externalSecurity = %d, routineOwnerId = %d",
                (Int32) externalSecurity_, (Int32) routineOwnerId_);
    space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

    UInt32 i;
    for (i = 0; i < numParams_; i++)
    {
      const UdrFormalParamInfo *p = paramInfo_[i];

      str_sprintf(buf, "\nParameter %d", (Int32) i);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

      str_sprintf(buf, "  name [%s]", p->getParamName());
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

      str_sprintf(buf, "  flags %b, type %d", p->getFlags(),
                  (Int32) p->getType());
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

      str_sprintf(buf, "  precision %d, scale %d, charset %d, collation %d",
                  (Int32) p->getPrecision(), (Int32) p->getScale(),
                  (Int32) p->getEncodingCharSet(), (Int32) p->getCollation());
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    }

    Queue *optData = getOptionalData();
    if (optData)
    {
      UInt32 dataElems = optData->numEntries();
      str_sprintf(buf, "\nNumber of optional data elements: %d",
                  (Int32) dataElems);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

      const char *s = NULL;
      i = 0;

      optData->position();
      while ((s = (const char *) optData->getNext()) != NULL)
      {
        // Each data element is prefixed by a 4-byte length field
        UInt32 len = 0;
        str_cpy_all((char *)&len, s, 4);

        str_sprintf(buf, "\nOptional data %d (length %d):",
                    (Int32) i++, (Int32) len);
        space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);

        if (len > 0)
        {
          // Create a buffer containing at most 200 bytes of data
          if (len > 200)
            len = 200;
          char truncatedBuf[201];
          str_cpy_all(truncatedBuf, s + 4, len);
          truncatedBuf[len] = 0;

          // Change NULL bytes and non-ASCII characters to '.' for
          // display purposes
          for (UInt32 j = 0; j < len; j++)
          {
            if (truncatedBuf[j] == 0 || !isascii(truncatedBuf[j]))
              truncatedBuf[j] = '.';
          }
          
          space->allocateAndCopyToAlignedSpace(truncatedBuf, len, sz);
        }
      }
    }
    if (javaDebugPort_ > 0)
    {
      str_sprintf(buf, "\njavaDebugPort = %d, javaDebugTimeout = %d",
                  javaDebugPort_, javaDebugTimeout_);
      space->allocateAndCopyToAlignedSpace(buf, str_len(buf), sz);
    }

  } // if (flag & 0x00000008)

  if (flag & 0x00000001)
  {
    displayExpression(space,flag);
    displayChildren(space,flag);
  }
}
Exemplo n.º 5
0
int main(int argc, char **argv) {
    EventList eventlist;
    eventlist.setEndtime(timeFromSec(5000));
    Clock c(timeFromSec(50/100.), eventlist);
    int algo = UNCOUPLED;
    double epsilon = 1;
    int crt = 2;

    if (argc>1) {
        if (!strcmp(argv[1],"UNCOUPLED"))
            algo = UNCOUPLED;
        else if (!strcmp(argv[1],"COUPLED_INC"))
            algo = COUPLED_INC;
        else if (!strcmp(argv[1],"FULLY_COUPLED"))
            algo = FULLY_COUPLED;
        else if (!strcmp(argv[1],"COUPLED_TCP"))
            algo = COUPLED_TCP;
        else if (!strcmp(argv[1],"COUPLED_EPSILON")) {
            algo = COUPLED_EPSILON;
            if (argc>2) {
                epsilon = atof(argv[2]);
                crt++;
                printf("Using epsilon %f\n",epsilon);
            }
        }
        else
            exit_error(argv[0]);
    }
    linkspeed_bps SERVICE1 = speedFromPktps(400);
    linkspeed_bps SERVICE2;
    if (argc>crt)
        SERVICE2 = speedFromPktps(atoi(argv[crt++]));
    else
        SERVICE2 = speedFromPktps(400);

    simtime_picosec RTT1=timeFromMs(100);
    simtime_picosec RTT2;
    if (argc>crt)
        RTT2 = timeFromMs(atoi(argv[crt]));
    else
        RTT2 = timeFromMs(100);

    mem_b BUFFER1=memFromPkt(RANDOM_BUFFER+timeAsSec(RTT1)*speedAsPktps(SERVICE1));//NUMFLOWS * targetwnd);
    mem_b BUFFER2=memFromPkt(RANDOM_BUFFER+timeAsSec(RTT2)*speedAsPktps(SERVICE2));//NUMFLOWS * targetwnd);

    srand(time(NULL));

    // prepare the loggers
    stringstream filename(ios_base::out);
    filename << "../data/logout." << speedAsPktps(SERVICE2) << "pktps." <<timeAsMs(RTT2) << "ms."<< rand();
    cout << "Outputting to " << filename.str() << endl;
    Logfile logfile(filename.str(),eventlist);

    logfile.setStartTime(timeFromSec(0.5));
    QueueLoggerSimple logQueue = QueueLoggerSimple();
    logfile.addLogger(logQueue);
    //	QueueLoggerSimple logPQueue1 = QueueLoggerSimple(); logfile.addLogger(logPQueue1);
    //QueueLoggerSimple logPQueue3 = QueueLoggerSimple(); logfile.addLogger(logPQueue3);
    QueueLoggerSimple logPQueue = QueueLoggerSimple();
    logfile.addLogger(logPQueue);
    MultipathTcpLoggerSimple mlogger = MultipathTcpLoggerSimple();
    logfile.addLogger(mlogger);

    //TrafficLoggerSimple logger;
    //logfile.addLogger(logger);
    SinkLoggerSampling sinkLogger = SinkLoggerSampling(timeFromMs(1000),eventlist);

    logfile.addLogger(sinkLogger);


    QueueLoggerSampling qs1 = QueueLoggerSampling(timeFromMs(1000),eventlist);
    logfile.addLogger(qs1);
    QueueLoggerSampling qs2 = QueueLoggerSampling(timeFromMs(1000),eventlist);
    logfile.addLogger(qs2);

    TcpLoggerSimple* logTcp = NULL;

    logTcp = new TcpLoggerSimple();
    logfile.addLogger(*logTcp);

    // Build the network
    Pipe pipe1(RTT1, eventlist);
    pipe1.setName("pipe1");
    logfile.writeName(pipe1);
    Pipe pipe2(RTT2, eventlist);
    pipe2.setName("pipe2");
    logfile.writeName(pipe2);
    Pipe pipe_back(timeFromMs(.1), eventlist);
    pipe_back.setName("pipe_back");
    logfile.writeName(pipe_back);

    RandomQueue queue1(SERVICE1, BUFFER1, eventlist,&qs1,memFromPkt(RANDOM_BUFFER));
    queue1.setName("Queue1");
    logfile.writeName(queue1);

    RandomQueue queue2(SERVICE2, BUFFER2, eventlist,&qs2,memFromPkt(RANDOM_BUFFER));
    queue2.setName("Queue2");
    logfile.writeName(queue2);
    Queue pqueue2(SERVICE2*2, memFromPkt(FEEDER_BUFFER), eventlist,NULL);
    pqueue2.setName("PQueue2");
    logfile.writeName(pqueue2);
    Queue pqueue3(SERVICE1*2, memFromPkt(FEEDER_BUFFER), eventlist,NULL);
    pqueue3.setName("PQueue3");
    logfile.writeName(pqueue3);
    Queue pqueue4(SERVICE2*2, memFromPkt(FEEDER_BUFFER), eventlist,NULL);
    pqueue4.setName("PQueue4");
    logfile.writeName(pqueue4);

    Queue* pqueue;

    Queue queue_back(max(SERVICE1,SERVICE2)*4, memFromPkt(1000), eventlist,NULL);
    queue_back.setName("queue_back");
    logfile.writeName(queue_back);

    TcpRtxTimerScanner tcpRtxScanner(timeFromMs(10), eventlist);

    //TCP flows on path 1
    TcpSrc* tcpSrc;
    TcpSink* tcpSnk;
    route_t* routeout;
    route_t* routein;
    double extrastarttime;

    for (int i=0; i<TCP_1; i++) {
        tcpSrc = new TcpSrc(NULL,NULL,eventlist);
        tcpSrc->setName("Tcp1");
        logfile.writeName(*tcpSrc);
        tcpSnk = new TcpSink();
        tcpSnk->setName("Tcp1");
        logfile.writeName(*tcpSnk);

        tcpRtxScanner.registerTcp(*tcpSrc);

        // tell it the route
        pqueue = new Queue(SERVICE1*2, memFromPkt(FEEDER_BUFFER), eventlist,NULL);
        pqueue->setName("PQueue1_"+ntoa(i));
        logfile.writeName(*pqueue);

        routeout = new route_t();
        routeout->push_back(pqueue);
        routeout->push_back(&queue1);
        routeout->push_back(&pipe1);
        routeout->push_back(tcpSnk);

        routein  = new route_t();
        routein->push_back(tcpSrc);

        extrastarttime = drand()*50;
        tcpSrc->connect(*routeout,*routein,*tcpSnk,timeFromMs(extrastarttime));
        sinkLogger.monitorSink(tcpSnk);
    }

    //TCP flow on path 2
    for (int i=0; i<TCP_2; i++) {
        tcpSrc = new TcpSrc(NULL,NULL,eventlist);
        tcpSrc->setName("Tcp2");
        logfile.writeName(*tcpSrc);
        tcpSnk = new TcpSink();
        tcpSnk->setName("Tcp2");
        logfile.writeName(*tcpSnk);

        tcpRtxScanner.registerTcp(*tcpSrc);

        pqueue = new Queue(SERVICE2*2, memFromPkt(FEEDER_BUFFER), eventlist,NULL);
        pqueue->setName("PQueue2_"+ntoa(i));
        logfile.writeName(*pqueue);

        // tell it the route
        routeout = new route_t();
        routeout->push_back(pqueue);
        routeout->push_back(&queue2);
        routeout->push_back(&pipe2);
        routeout->push_back(tcpSnk);

        routein  = new route_t(); //routein->push_back(&queue_back); routein->push_back(&pipe_back);
        routein->push_back(tcpSrc);
        extrastarttime = 50*drand();
        tcpSrc->connect(*routeout,*routein,*tcpSnk,timeFromMs(extrastarttime));
        sinkLogger.monitorSink(tcpSnk);
    }

    MultipathTcpSrc* mtcp;
    if (algo==COUPLED_EPSILON)
        mtcp = new MultipathTcpSrc(algo,eventlist,&mlogger,epsilon);
    else
        mtcp = new MultipathTcpSrc(algo,eventlist,&mlogger);

    //MTCP flow 1
    tcpSrc = new TcpSrc(NULL,NULL,eventlist);
    tcpSrc->setName("Subflow1");
    logfile.writeName(*tcpSrc);
    tcpSnk = new TcpSink();
    tcpSnk->setName("Subflow1");
    logfile.writeName(*tcpSnk);

    tcpRtxScanner.registerTcp(*tcpSrc);

    // tell it the route
    routeout = new route_t();
    routeout->push_back(&pqueue3);
    routeout->push_back(&queue1);
    routeout->push_back(&pipe1);
    routeout->push_back(tcpSnk);

    routein  = new route_t();
    //routein->push_back(&queue_back); routein->push_back(&pipe_back);
    routein->push_back(tcpSrc);
    extrastarttime = 50*drand();

    //join multipath connection
    mtcp->addSubflow(tcpSrc);

    tcpSrc->connect(*routeout,*routein,*tcpSnk,timeFromMs(extrastarttime));
    sinkLogger.monitorSink(tcpSnk);

    //MTCP flow 2
    tcpSrc = new TcpSrc(NULL,NULL,eventlist);
    tcpSrc->setName("Subflow2");
    logfile.writeName(*tcpSrc);
    tcpSnk = new TcpSink();
    tcpSnk->setName("Subflow2");
    logfile.writeName(*tcpSnk);
    tcpRtxScanner.registerTcp(*tcpSrc);

    // tell it the route
    routeout = new route_t();
    routeout->push_back(&pqueue4);
    routeout->push_back(&queue2);
    routeout->push_back(&pipe2);
    routeout->push_back(tcpSnk);

    routein  = new route_t();
    //routein->push_back(&queue_back); routein->push_back(&pipe_back);
    routein->push_back(tcpSrc);
    extrastarttime = 50*drand();

    //join multipath connection
    mtcp->addSubflow(tcpSrc);

    tcpSrc->connect(*routeout,*routein,*tcpSnk,timeFromMs(extrastarttime));
    sinkLogger.monitorSink(tcpSnk);

    // Record the setup
    int pktsize = TcpPacket::DEFAULTDATASIZE;
    logfile.write("# pktsize="+ntoa(pktsize)+" bytes");
    logfile.write("# bottleneckrate1="+ntoa(speedAsPktps(SERVICE1))+" pkt/sec");
    logfile.write("# bottleneckrate2="+ntoa(speedAsPktps(SERVICE2))+" pkt/sec");
    logfile.write("# buffer1="+ntoa((double)(queue1._maxsize)/((double)pktsize))+" pkt");
    logfile.write("# buffer2="+ntoa((double)(queue2._maxsize)/((double)pktsize))+" pkt");
    double rtt = timeAsSec(RTT1);
    logfile.write("# rtt="+ntoa(rtt));
    rtt = timeAsSec(RTT2);
    logfile.write("# rtt="+ntoa(rtt));
    logfile.write("# numflows="+ntoa(NUMFLOWS));
    logfile.write("# targetwnd="+ntoa(targetwnd));

    // GO!
    while (eventlist.doNextEvent()) {}
}
Exemplo n.º 6
0
ExWorkProcRetcode ExHbaseAccessDDLTcb::work()
{
  short retcode = 0;
  short rc = 0;

  // if no parent request, return
  if (qparent_.down->isEmpty())
    return WORK_OK;

  while (1)
    {
      switch (step_)
	{
	case NOT_STARTED:
	  {
	    matches_ = 0;
	    if (hbaseAccessTdb().accessType_ == ComTdbHbaseAccess::CREATE_)
	      step_ = CREATE_TABLE;
	   else if (hbaseAccessTdb().accessType_ == ComTdbHbaseAccess::DROP_)
	      step_ = DROP_TABLE;
	   else
	     step_ = HANDLE_ERROR;
	  }
	  break;

	case CREATE_TABLE:
	  {
	    table_.val = hbaseAccessTdb().getTableName();
	    table_.len = strlen(hbaseAccessTdb().getTableName());

	    Queue * cfnl = hbaseAccessTdb().getColFamNameList();
	    cfnl->position();
	    HBASE_NAMELIST colFamList;
	    HbaseStr colFam;
	    while(NOT cfnl->atEnd())
	      {
		char * cfName = (char*)cfnl->getCurr();
		colFam.val = cfName;
		colFam.len = strlen(cfName);

		colFamList.insert(colFam);
		cfnl->advance();
	      }

	    step_ = DONE;
	  }
	  break;

	case DROP_TABLE:
	  {
	    step_ = DONE;
	  }
	  break;

	case HANDLE_ERROR:
	  {
	    if (handleError(rc))
	      return rc;
	    
	    step_ = DONE;
	  }
	  break;

	case DONE:
	  {
	    if (handleDone(rc))
	      return rc;

	    step_ = NOT_STARTED;

	    return WORK_OK;
	  }
	  break;

	}// switch

    } // while
}
Exemplo n.º 7
0
#include <future>
#include <iostream>

using namespace std;

template<typename T>

class MessageQueue
{
private:
		using Queue = vector<T>;
		using QueueIterator = typename Queue::iterator;
		Queue m_A;
		Queue m_B;

		Queue* m_Producer{ &m_A };
		Queue* m_Consumer{ &m_B };

		QueueIterator m_ConsumerIterator{ m_B.end() };
		condition_variable& m_MessageCondition;
		condition_variable m_ConsumptionFInished;

		mutex m_MutexProducer;
		mutex m_MutexConsumer;

		unsigned int m_SwapCount{ 0 };
public:
		MessageQueue(condition_variable& messageCondition)
				:m_MessageCondition{ messageCondition }
		{
		
Exemplo n.º 8
0
/*
 * PFabric topology with 144 hosts (16, 9, 4)
 */
PFabricTopology::PFabricTopology(
        uint32_t num_hosts, 
        uint32_t num_agg_switches,
        uint32_t num_core_switches, 
        double bandwidth,
        uint32_t queue_type
        ) : Topology () {
    uint32_t hosts_per_agg_switch = num_hosts / num_agg_switches;

    this->num_hosts = num_hosts;
    this->num_agg_switches = num_agg_switches;
    this->num_core_switches = num_core_switches;

    //Capacities
    double c1 = bandwidth;
    double c2 = hosts_per_agg_switch * bandwidth / num_core_switches;

    // Create Hosts
    for (uint32_t i = 0; i < num_hosts; i++) {
        hosts.push_back(Factory::get_host(i, c1, queue_type, params.host_type)); 
    }

    // Create Switches
    for (uint32_t i = 0; i < num_agg_switches; i++) {
        AggSwitch* sw = new AggSwitch(i, hosts_per_agg_switch, c1, num_core_switches, c2, queue_type);
        agg_switches.push_back(sw); // TODO make generic
        switches.push_back(sw);
    }
    for (uint32_t i = 0; i < num_core_switches; i++) {
        CoreSwitch* sw = new CoreSwitch(i + num_agg_switches, num_agg_switches, c2, queue_type);
        core_switches.push_back(sw);
        switches.push_back(sw);
    }

    //Connect host queues
    for (uint32_t i = 0; i < num_hosts; i++) {
        hosts[i]->queue->set_src_dst(hosts[i], agg_switches[i/16]);
        //std::cout << "Linking Host " << i << " to Agg " << i/16 << "\n";
    }

    // For agg switches -- REMAINING
    for (uint32_t i = 0; i < num_agg_switches; i++) {
        // Queues to Hosts
        for (uint32_t j = 0; j < hosts_per_agg_switch; j++) { // TODO make generic
            Queue *q = agg_switches[i]->queues[j];
            q->set_src_dst(agg_switches[i], hosts[i * 16 + j]);
            //std::cout << "Linking Agg " << i << " to Host" << i * 16 + j << "\n";
        }
        // Queues to Core
        for (uint32_t j = 0; j < num_core_switches; j++) {
            Queue *q = agg_switches[i]->queues[j + 16];
            q->set_src_dst(agg_switches[i], core_switches[j]);
            //std::cout << "Linking Agg " << i << " to Core" << j << "\n";
        }
    }

    //For core switches -- PERFECT
    for (uint32_t i = 0; i < num_core_switches; i++) {
        for (uint32_t j = 0; j < num_agg_switches; j++) {
            Queue *q = core_switches[i]->queues[j];
            q->set_src_dst(core_switches[i], agg_switches[j]);
            //std::cout << "Linking Core " << i << " to Agg" << j << "\n";
        }
    }
}
Exemplo n.º 9
0
int main() {
   
    pc.baud(115200);

    float temp;

    pc.printf("Hello!");
    
    //implement XBee communication
    send.attach(&sendPackage,0.7);
    //implement EMG signal processing
    adc_aqr.attach(&adc_acquire,0.05);
    adc_aqr_temp.attach(&adc_acquire_temp,0.05);
    get_position.attach(&position_decide,0.05);
    get_position_temp.attach(&position_decide_temp,0.05);

    xbee.baud(57600);
    rst = 0;
    led1 = 0;
    wait_ms(1);
    rst = 1;
    wait_ms(1);
    led1 = 1;
    
    led2 = 0;
    // xbee send data 
    msg.id = 0;
    msg.mode_send = 1;
    msgIface.sendPacket( MsgTypeModeSend, (uint8_t*)&msg, sizeof(MsgModeSend) );        
    while ( !msgIface.sendComplete() ) {
        msgIface.sendNow();
    }
    wait_ms(250);
    led2 = 1;
    
    wait_ms(250);
    led2 = 0;
    msg.id = 0;
    msg.mode_send = 1;
    msgIface.sendPacket( MsgTypeModeSend, (uint8_t*)&msg, sizeof(MsgModeSend) );        
    while ( !msgIface.sendComplete() ) {
        msgIface.sendNow();
    }
    wait_ms(250);
    led2 = 1;
    
    
    wait_ms(250);
    led2 = 0;
    msg.id = 0; 
    msg.mode_send = 1;
    msgIface.sendPacket( MsgTypeModeSend, (uint8_t*)&msg, sizeof(MsgModeSend) ); 
    //Implement IMU function
    imu_mpu6050.setAcceleroRange(MPU6050_ACCELERO_RANGE_2G);    // set the scale of the accelerometer
    imu_mpu6050.setGyroRange(MPU6050_GYRO_RANGE_250);           // set the scale of the gyro
    float angle_x;
    float angle_y;      // store the angle of x-axis and angle of y-axis
    bool success_flag;  // indicate the iic connection
    
    success_flag = imu_hand.testCommunication();    // if successful, return 1
    //train and get the train sample
    init();
    while(!success_flag)        // wait until connection
    {
        myled = 1;
    }  
 // while loop  

    t.start();
    while(1) {
        imu_hand.getAngleXY(&angle_x, &angle_y);    // get angle_x and angle_y      
        myQueue.Put(&adc);
        myQueue_temp.Put(&adc_temp);
        //pc.printf("y:  %f",angle_y);
        if(pos==2&&pos==2&& angle_y>65)
        {
            
            if(mode_enable==1)
            {
              t.reset();
              mode_enable=0;
              pc.printf("SHOOT\r\n");
              msg.id = 0;
              msg.mode_send = SHOOT;
              
            }
              
        }
       // pc.printf("time : %f\r\n", t.read());
       // pc.printf("mode_enable : %d\r\n", mode_enable);
        if(t.read()>3)
        {
           t.reset();
           mode_enable=1;
        }
        
        if(pos==0&&pos_temp==0)
        {
           pc.printf("IDLE\r\n");
           msg.id = 0;
           msg.mode_send = 0;         
        }

        else
        {
          
               if(adc-adc_temp>120)
               {
                  if(abs(angle_x)<30)
                  {
                    pc.printf("CANNON_UP\r\n");
                      msg.id = 0;  
                      msg.mode_send = CANNON_UP;
                  }
                  if(angle_x>60 && angle_x<90)
                  {
                     pc.printf("CANNON_LEFT\r\n");
                     msg.id = 0;
                      msg.mode_send = CANNON_LEFT;
                  }
                  if(angle_x<-60 && angle_x>-90)
                  {
                     pc.printf("SHOOT\r\n");
                     msg.id = 0;
                      msg.mode_send = SHOOT;
                  }

               }
               else if(adc_temp-adc>-100)
               {
               
                  if(abs(angle_x)<30)
                  {
                    pc.printf("CANNON_DOWN\r\n");
                    msg.id = 0;
                      msg.mode_send = CANNON_DOWN;
                  }
                  if(angle_x>60 && angle_x<90)
                  {
                     pc.printf("CANNON_RIGHT\r\n");
                     msg.id = 0;
                      msg.mode_send = CANNON_RIGHT;
                  }

               }
            
            
        }
       // pc.printf("pos: %d\r\n",pos_temp);
        if(myQueue.GetNumberOfItems( )==sample_num)
        {
           myQueue.Get(&temp);
        }
        if(myQueue_temp.GetNumberOfItems( )==sample_num)
        {
           myQueue_temp.Get(&temp);
        }
        msgIface.sendNow();       
    }
    
}
Exemplo n.º 10
0
void display() {
  cout << iq.front() << " " << iq.size() << " ";
  cout << lfq.front() << " " << lfq.size() << endl;
}
Exemplo n.º 11
0
int main (void) {
	try {
		Queue queue (5);
		queue.push (10);
		queue.push (20);
		queue.push (30);
		queue.push (40);
		queue.push (50);
//		queue.push (60);
		cout << queue.pop () << endl; // 10
		queue.push (60);
		cout << queue.pop () << endl; // 20
		cout << queue.pop () << endl; // 30
		queue.push (70);
		queue.push (80);
		cout << queue.pop () << endl; // 40
		cout << queue.pop () << endl; // 50
		cout << queue.pop () << endl; // 60
		cout << queue.pop () << endl; // 70
		cout << queue.pop () << endl; // 80
//		queue.pop ();
	}
	catch (exception& ex) {
		cout << ex.what () << endl;
		return -1;
	}
	return 0;
}
Exemplo n.º 12
0
int main() {
  int a;
  cin >> a;
  for (int i = 0; i < a; ++i) {
    lfq.push(cnum+0.1205);
    iq.push(cnum++);
  }
  display();
  for (int i = 0; i < 500; ++i) {
    lfq.push(cnum+0.1205);
    iq.push(cnum++);
  }
  display();
  for (int i = 0; i < a; ++i) {
    lfq.pop();
    iq.pop();
  }
  display();
  cin >> a;
  for (int i = 0; i < a; ++i) {
    lfq.pop();
    iq.pop();
  }
  display();
  iq.clear();
  lfq.clear();
  cin >> a;
  for (int i = 0; i < a; ++i) {
    lfq.push(cnum+0.1205);
    iq.push(cnum++);
  }
  for (int i = 0; i < a/2; ++i) {
    lfq.pop();
    iq.pop();
  }
  display();
  return 0;
}
Exemplo n.º 13
0
 void trace(JSTracer *trc) {
     AutoLock hold(lock);
     for (T *p = busy.begin(); p != busy.end(); p++)
         (*p)->trace(trc);
     queue.trace(trc);
 }
Exemplo n.º 14
0
 bool lockedIsIdle() { return busy.empty() && queue.empty(); }
Exemplo n.º 15
0
bool mlt_still_working()
{
    assert(mlt_inited);

    return thread_running || !async_responses.empty();
}
Exemplo n.º 16
0
int main() {
  try {
    Queue<int> q;
    q.add(1); q.add(2); q.add(3); 
    q.remove(); q.remove(); q.remove();
    for (int i=10; i<=28; i++)
      q.add(i);
    Queue<int> r = q;
    while (!q.empty()) {
        cout << q.front() << ' ';
        q.remove();
    }
    cout << endl;
    while (!r.empty()) {
        cout << r.front() << ' ';
        r.remove();
    }
    cout << endl;
  }
  catch (const char* s) {
    cout << "chyba: " << s << endl;
  }
  //system("PAUSE");
  return 0;
}
Exemplo n.º 17
0
void mlt_process_callbacks()
{
    assert(mlt_inited);

    while (!async_responses.empty())
    {
        async_req_t response = async_responses.pop();
        /*printf("master: got response\n");
        printf("master: got response: %s.\n", (response.type == ANIM) ? "anim" :
                            (response.type == LAND_ART) ? "land art" :
                            (response.type == STATIC_ART) ? "static art" :
                            (response.type == LAND_BLOCK) ? "land block" :
                            (response.type == STATICS_BLOCK) ? "statics block" :
                            "<unknown>");*/
        if (response.type == ANIM)
        {
            int body_id   = response.anim.body_id;
            int action    = response.anim.action;
            int direction = response.anim.direction;
            ml_anim *res  = response.anim.res;
            response.anim.callback(body_id, action, direction, res);
        }
        else if (response.type == LAND_ART)
        {
            int land_id = response.land_art.land_id;
            ml_art *res = response.land_art.res;
            response.land_art.callback(land_id, res);
        }
        else if (response.type == STATIC_ART)
        {
            int item_id = response.static_art.item_id;
            ml_art *res = response.static_art.res;
            response.static_art.callback(item_id, res);
        }
        else if (response.type == GUMP)
        {
            int gump_id  = response.gump.gump_id;
            ml_gump *res = response.gump.res;
            response.gump.callback(gump_id, res);
        }
        else if (response.type == LAND_BLOCK)
        {
            int map            = response.land_block.map;
            int block_x        = response.land_block.block_x;
            int block_y        = response.land_block.block_y;
            ml_land_block *res = response.land_block.res;
            response.land_block.callback(map, block_x, block_y, res);
        }
        else if (response.type == STATICS_BLOCK)
        {
            int map               = response.statics_block.map;
            int block_x           = response.statics_block.block_x;
            int block_y           = response.statics_block.block_y;
            ml_statics_block *res = response.statics_block.res;
            response.statics_block.callback(map, block_x, block_y, res);
        }
        else
        {
            assert(0 && "unknown response type");
        }
    }
}
Exemplo n.º 18
0
int main(){
    Queue a = Queue();
    a.add("a");
    cout << a.getUsed() << endl;
    a.add("b");
    a.add("c");
    a.add("d");
    cout << a.remove() << endl;
    cout << a.remove() << endl;
    cout << a.getUsed() << endl;
    a.add("e");
    a.add("f");
    a.add("break");
    cout << a.getUsed() << endl;
    cout << a.remove() << endl;
    cout << a.remove() << endl;
    cout << a.remove() << endl;
    a.add("fake");
    cout << a.getUsed() << endl;
    cout << a.remove() << endl;
    cout << a.remove() << endl;
    cout << a.remove() << endl;
    cout << a.getUsed() << endl;
    
    //system("pause");
    return 0;
} //main()
Exemplo n.º 19
0
/*
+-----------------+------------------------------------------------------------+
| FUNCION         | PriceOnLine::ProcessIt                                     |
+-----------------+------------------------------------------------------------+
| DESCRIPCION     | Proceso del objeto                                         |
|                 |                                                            | 
+-----------------+------------------------------------------------------------+
*/
int PriceOnLine::ProcessIt()
{
	str_sel_cadata	term_data;
	str_heap_data	heap_data;
	TrxData			trx_data;
	char			msg_str[2000];
	char			aux_str[64];
	char			szNroCta[64];
	int				cont;
	int				len;
	int				ret;
	int				limite=OK;
	int				channel_down;
	int				pos_ocup;
	int				TrxEnVuelo;
	str_upd_rev		StrDataRev;
	char 			CajDevol[6];
	char 			TrxDevol[5];
	char 			CajVenta[6];
	char 			TrxVenta[5];
	char			FecVenta[7];
	char			szCampo13[LON_CAMPO_13 + 1];
	char			szCuotas[32];
	/* Modificacion PINPAD */
	char			szPinPad[64];
	int				iHayPinPad;
	/* Pinpad 2*/
	long			lCodProc;
	long			lCodCuenta;
	char			szCodiProc[16];
	int				iTipoOperacion=0;
	char			NroTrxAux[9];
	char			szRowId[64];
	char			szFHtransm[32];
	char			szFHoperac[32];
	long			lImpoTran;
	long			lCashBack;
        char                    szCriptograma[1024] = {0};
        char                    szVersionEMV[20] = {0};
        char                    szEMVProductList[512] = {0};
	struct trxRtaTPV stRta;
	
	/* Blanquea estructura de respuesta */
	memset(&stRta, 0, sizeof(stRta));
	memset(stRta.szCodAut, ' ', sizeof(stRta.szCodAut)-1);
	memset(stRta.szComerc, ' ', sizeof(stRta.szComerc)-1);
	memset(stRta.szTermin, ' ', sizeof(stRta.szTermin)-1);
	memset(stRta.szNroLot, ' ', sizeof(stRta.szNroLot)-1);
	memset(stRta.szPlnIso, ' ', sizeof(stRta.szPlnIso)-1);
	memset(stRta.szProtoc, ' ', sizeof(stRta.szProtoc)-1);
	memset(stRta.szRespCA, ' ', sizeof(stRta.szRespCA)-1);
	memset(stRta.szFecOri, ' ', sizeof(stRta.szFecOri)-1);
	memset(stRta.szTicOri, ' ', sizeof(stRta.szTicOri)-1);
	memset(stRta.szPlanSF, ' ', sizeof(stRta.szPlanSF)-1);
        

	/* Track II en las IBM no viene el separador de campos '='. Se agrega */
	char TrackIIprice[40];
	char * indexTr;
	strcpy(TrackIIprice,mensaje_price->GetField(10));
	if ((indexTr=strchr(TrackIIprice,'D'))!=NULL)
	{
		*indexTr='='; 
		mensaje_price->PutField(10,TrackIIprice);
	}
	
	/* Se invierte la fecha de caducidad siempre */
	mensaje_price->InvertirFecha(); 
	
	/* Se loguean los datos de la terminal */
	LogAlarm.Put(0, "PriceOn: Emp:[%s] Suc:[%s] Ter:[%s] Trx:[%s] Tar:[%s] Plan:[%s]\n", 
						mensaje_price->GetEmpresa()     , 
						mensaje_price->GetSucursal()    ,
						mensaje_price->GetTerminal()    ,
						mensaje_price->GetTransaccion() ,
						mensaje_price->GetCodTar()      ,
						mensaje_price->ObtPlanSf());

	/* Se obtienen los datos de la terminal en base al mensaje price */
	strcpy(term_data.plan_sf, mensaje_price->ObtPlanSf());
	strcpy(term_data.cod_tar, mensaje_price->GetCodTar());
	strcpy(term_data.nro_suc, mensaje_price->GetEmpresa());
	strcpy(term_data.nro_caj, mensaje_price->GetTerminal());

	/* Obtiene el tipo de operacion ( 01:T_VENT - 02:T_DEVO - 08:T_PAGO - 09:T_DEVP ) */
	iTipoOperacion = atoi(mensaje_price->GetField(5));

	/* Se buscan los restantes datos de la terminal */
	ret=getDataByNT2(&term_data);
	if ( (ret!=OK) || (term_data.caj_bloq==1) )
	{
		/* Al dar error, loguea los datos de la terminal mal configurada */
		if (term_data.caj_bloq==1)
		{
			LogAlarm.Put (0, "PriceOn: ERROR Caja bloqueada por cierre anterior fallido\n");
		}
		else
		{
			LogAlarm.Put (0, "PriceOn: ERROR (%d) al obtener datos de la terminal\n", ret);
		}

		/* Escribe en el log de errores de terminal */
		LogErrTerminal.Put(0, "Fecha Hora %s", currentTimeLog() );
		LogErrTerminal.Put(0, "Caja: %s - Empresa: %s - Tarjeta: %s - Plan: %s - Evento: PriceOn\n\n", 
								mensaje_price->GetTerminal(),
								mensaje_price->GetEmpresa(),
								mensaje_price->GetCodTar(),
								mensaje_price->ObtPlanSf()); 
		
		/* Arma mensaje de respuesta y lo envia al TPV */
		sprintf(stRta.szRespCA, "102");
		if ( (iTipoOperacion==T_PAGO) || (iTipoOperacion==T_DEVP) )
		{
			Armar_y_Enviar_Respuesta("11", &stRta);
		}
		else
		{
			Armar_y_Enviar_Respuesta("08", &stRta);
		}
		return OK;
	}
	
	/* Se agrega en la cadena del heap el nro_tar original para devolverlo */
	strcpy(heap_data.nro_tar,mensaje_price->GetField(4));
	
	/* Se adapta el mensaje price a la forma de autorizacion */
	mensaje_price->ConvMsgPrice(atoi(term_data.tip_aut));

	/* Completa la estructura de Trace Number */
	TraceNumber.SetNroSuc(term_data.nro_suc);
	TraceNumber.SetNroCaj(term_data.nro_caj);
	TraceNumber.SetNroCA (term_data.nro_ca );
	TraceNumber.SetCodConCie(term_data.cod_con_cie);
	
	/* Si se esta haciendo un cierre de lote genera la respuesta y se la envia de vuelta al price */
	if (CACS.IsCierre(atoi(term_data.nro_ca)))
	{
		if ((CACS.GetSuc(atoi(term_data.nro_ca))==atoi(term_data.nro_suc)) &&
			(CACS.GetCaj(atoi(term_data.nro_ca))==atoi(term_data.nro_caj)))
		{
			/* Arma mensaje de respuesta y lo envia al TPV */
			LogAlarm.Put(0, "PriceOn: ERROR. Cierre de lote activo notificando a Price\n");
			sprintf(stRta.szRespCA, "104");
			if ( (iTipoOperacion==T_PAGO) || (iTipoOperacion==T_DEVP) )
			{
				Armar_y_Enviar_Respuesta("11", &stRta);
			}
			else
			{
				Armar_y_Enviar_Respuesta("07", &stRta);
			}
			return OK;
		}
	}
	
	/* Completar el mensaje con los datos generados por nosotros	*/
	if (!strcmp(term_data.uco_seg,"S"))
	{
		mensaje_price->SetCodSeg();
	}
	else
	{
		mensaje_price->SetNoCodSeg();
	}
	
	/* Setea el centro autorizador */
    mensaje_price->SetNroCAPrice(term_data.nro_ca);

	/* Convierte el mensaje a formato ISO */
	mensaje_iso=new Iso_Msg();
	mensaje_iso->SetNroCA8583(term_data.nro_ca);
	*mensaje_iso=*mensaje_price;

	sprintf(szFHtransm, currentTimestamp());
	mensaje_iso->PutField(7, szFHtransm);	
	strcpy(aux_str, TraceNumber);
	mensaje_iso->PutField(11, aux_str); 	
	mensaje_iso->PutField(24, term_data.cod_red);	
	mensaje_iso->PutField(41, term_data.nro_caj_ca);	
	mensaje_iso->PutField(49, term_data.cod_mon);	
	trx_data.NroLot(term_data.nro_lot);
	trx_data.CodMon(term_data.cod_mon);	
	sprintf(aux_str, "%-15s", term_data.nro_com);
	mensaje_iso->PutField(42, aux_str);

	/* Si hora operacion mayor a transmision se rechaza */
	/* Quitar si sincronizan hora los servidores        */
	switch (DBTipoProtocoloISO(term_data.nro_ca))
	{
	case PROT_ISO_AMEX: 
		memset(szFHoperac, 0, sizeof(szFHoperac));
		strcpy(szFHoperac, mensaje_iso->GetField(13));
		strcat(szFHoperac, mensaje_iso->GetField(12));
		if (strcmp(szFHoperac, szFHtransm)>0)
		{
			LogAlarm.Put(0, "PriceOn: ERROR fecha Suc[%s] Ter[%s] Operac[%s] Transm[%s]\n", 
							mensaje_price->GetSucursal(), mensaje_price->GetTerminal(),
							szFHoperac, szFHtransm);
			sprintf(stRta.szRespCA, "109");
			Armar_y_Enviar_Respuesta("02", &stRta);
			return OK;	
		}
		break;
	default:
		break;
	}

	/* Modificacion PINPAD */
	iHayPinPad = mensaje_price->UsePinPad();
	if (iHayPinPad)
	{
		/* Arma el codigo de procesamiento */
		lCodCuenta = atol(mensaje_price->GetField(31));
		if ( (lCodCuenta != PINPAD_CA_P) && (lCodCuenta != PINPAD_CC_P) &&
		     (lCodCuenta != PINPAD_CA_D) && (lCodCuenta != PINPAD_CC_D) )
		{
			lCodCuenta = PINPAD_CA_P;	/* Caja de ahorro en pesos por defecto */
		}
		lCodProc = atol(mensaje_iso->GetField(3)) + lCodCuenta * 1000;
		sprintf(szCodiProc, "%06d", lCodProc);
		mensaje_iso->PutField(3, szCodiProc);

		LogAlarm.Put(0, "PriceOn: Codigo de procesamiento PPAD: %s\n", szCodiProc);

		/* Agrega el pinpad al mensaje */
		memset(szPinPad, 0, sizeof(szPinPad));
		mensaje_price->GetPinPad(szPinPad);
		mensaje_iso->PutField(52, szPinPad);
	}
	/* Fin manejo PinPad */

	/* Obtiene montos de la operacion */
	lImpoTran = atol(mensaje_price->GetField( 6));
	lCashBack = atol(mensaje_price->GetField(32));
	
	/* CashBack Visa. Campo 4 = Compra + Retiro */
	if (lCashBack>0)
	{
		switch (term_data.prot_cash[0])
		{
		case CASHBACK_VISA: 
			sprintf(aux_str, "%012ld", lImpoTran+lCashBack);
			mensaje_iso->PutField(4, aux_str);
			break;
		case CASHBACK_POSN:
			sprintf(aux_str, "%012ld", lImpoTran);
			break;
		default:
			break;
		}
		LogAlarm.Put(0, "PriceOn: CashBack. Prot:%c Imp:%ld Ret:%ld Tot:%ld\n", 
					 term_data.prot_cash[0], lImpoTran, lCashBack, atol(aux_str));
	}
	
	/* Arma los datos de la transaccion para la BD */
	mensaje_price->GetDBData(trx_data);
	mensaje_iso->GetDBData(trx_data);
	sprintf(aux_str,"%02d",M_CEAU);
	trx_data.ModAut(aux_str);
	trx_data.CanRet("0000");
	trx_data.NroCA(term_data.nro_ca);
	trx_data.NroCajCa(term_data.nro_caj_ca);
	trx_data.NroCom(term_data.nro_com); 
	trx_data.NroCuo(mensaje_price->ObtCuotas());
	trx_data.PlanISO(term_data.plan_iso);
	trx_data.PlanSF(mensaje_price->ObtPlanSf()); 
	trx_data.NroRef("");

	/* Pago de resumen */
	iTipoOperacion = atoi(mensaje_price->GetField(5));
	switch (iTipoOperacion)
	{
	case T_PAGO:
		sprintf(aux_str, "%02d", T_PAGO);
		trx_data.CodTrx(aux_str);
		sprintf(szCodiProc, "%06d", OPCODE_VISA_PAGO_RESUMEN);
		trx_data.CodPro(szCodiProc);
		mensaje_iso->PutField(3, szCodiProc);
		break;
	case T_DEVP:
		sprintf(aux_str, "%02d", T_DEVP);
		trx_data.CodTrx(aux_str);
		sprintf(szCodiProc, "%06d", OPCODE_VISA_DEVO_RESUMEN);
		trx_data.CodPro(szCodiProc);
		mensaje_iso->PutField(3, szCodiProc);
		break;
	}

	/* Codigo de procesamiento */
	if ( (lCashBack>0) && (iTipoOperacion==1) )
	{
		lCodProc = 0;
		switch ( term_data.prot_cash[0] )
		{
		case CASHBACK_VISA: 
			lCodProc = OPCODE_VISA_VEN_CASHBACK;
			break;
		case CASHBACK_POSN:
			lCodProc = (((atol(mensaje_iso->GetField(3))/1000)%10)*1000) + OPCODE_POSN_VEN_CASHBACK;
			break;
		}
		if (lCodProc)
		{
			sprintf(szCodiProc, "%06d", lCodProc);
			mensaje_iso->PutField(3, szCodiProc);
			trx_data.CodPro(szCodiProc);
			LogAlarm.Put(0, "PriceOn: Codigo de procesamiento CASH: %s\n", szCodiProc);
		}
	}
	
	/* Numero de cuenta */
	memset(szNroCta, 0, sizeof(szNroCta));

	/* Agrega peticion de numero de cuenta */
	if (strcmp( mensaje_price->GetField(21) , "01") == 0) 
	{
		sprintf(aux_str, "%s", CAMPO_NRO_CUENTA);
		strcat(szNroCta, aux_str);
	}

	/* Agrega fecha de diferimento (Si no es devolucion) */
	if (term_data.dias_dif > 0)
	{
		char szFechaTrx[32];
		char szFechaDif[32];
		sprintf(szFechaTrx,"%04d%4.4s",ObtYear(),trx_data.FecLoc());
		if( (atoi(trx_data.CodTrx())!=T_DEVO) && (atoi(trx_data.CodTrx())!=T_DEVP) )
		{
			if (getFechaDif(szFechaTrx, term_data.dias_dif, szFechaDif)==0)
			{
				sprintf(aux_str, "%s%s", CAMPO_FECHA_DIFE, szFechaDif);
				strcat(szNroCta, aux_str);
			}
		}
	}

	/* Agrega campo 59 */
	if (strlen(szNroCta)>0)
	{
		sprintf(aux_str, "%03d%s", strlen(szNroCta), szNroCta);
		ret = mensaje_iso->PutField(59, aux_str);
		LogAlarm.Put(10, "PriceOn: Campo 59:[%s] Ret:[%d]\n", aux_str, ret);
	}

	strcpy(heap_data.anul_onl,  "0");
	strcpy(heap_data.plan_iso,  term_data.plan_iso);
	strcpy(heap_data.nro_com,   term_data.nro_com);
	strcpy(heap_data.trans_ori, "0000");
	strcpy(heap_data.fecha_ori, "000000");

	/* Arma el campo cuotas */
	strcpy(aux_str, mensaje_price->ObtCuotas());
	
	/* #37322 Cuotas articulos nacionales */
	if (term_data.plan_esp > 0) 
	{
		sprintf(aux_str, "%03d", term_data.plan_esp);
	}

	sprintf(szCuotas, "003%1.1s%2.2s",trx_data.PlanISO(), &aux_str[1]);
	
	/* Compras AMEX de contado no se envia campo 48 */
	switch (DBTipoProtocoloISO(term_data.nro_ca))
	{
	case PROT_ISO_AMEX: 
		if (strcmp(szCuotas, "003001")==0) 
		{
			memset(szCuotas, 0, sizeof(szCuotas));
		}
		break;
	default:
		break;
	}

	/*** Se verifica que sea una devolucion para convertirla en anulacion ***/
	/*** en caso que la transaccion original se encuentre en la base y    ***/
	/*** sea de la fecha en curso                                         ***/
	
	LogAlarm.Put(8, "PriceOn: Codigo de transaccion:[%s]\n", trx_data.CodTrx());
	if( (atoi(trx_data.CodTrx())==T_DEVO) || (atoi(trx_data.CodTrx())==T_DEVP) )
	{
		/* Obtiene la caja y transaccion  */
		strcpy(CajDevol,trx_data.NroCaj());
		strcpy(TrxDevol,trx_data.NroTrx());
		LogAlarm.Put(0, "PriceOn: Devolucion. CAut:[%s] TerOri:[%s] CajDevol:[%s]\n", term_data.nro_ca, CajDevol, TrxDevol);

		/* Agrega el monto a consulta de anulaciones */
		trx_data.Monto(mensaje_price->GetField(6));
		
		/* Reemplaza caja y transaccion por los de la operacion original */
		trx_data.NroCaj(mensaje_price->GetField(27));
		trx_data.NroTrx(mensaje_price->GetField(28));

		/* Obtiene los datos de la operacion */
		StrDataRev=*(trx_data.GetDataRev());
		
		/* Agrega el plan */
		strcpy(StrDataRev.plan_sf, trx_data.PlanSF());

		/* Actualiza el estado de la transaccion y trae los datos */
		ret=DBTrx.UpdAnulVenta(&StrDataRev);
		
		strcpy(CajVenta,trx_data.NroCaj());
		strcpy(TrxVenta,trx_data.NroTrx());

		LogAlarm.Put(0, "PriceOn: Actualizacion anulacion venta. Ret:[%d], Errno:[%d]\n",ret,DBTrx.GetErrno());
		LogAlarm.Put(0, "PriceOn: TerV:[%s], TrxV[%s] TerD:[%s], TrxD[%s]\n", CajVenta, TrxVenta, CajDevol, TrxDevol);
		
		/* Devolucion de pago de resumen */
		if (atoi(trx_data.CodTrx())==T_DEVP)
		{
			LogAlarm.Put(0, "PriceOn: Devolucion pago de resumen\n");
			if ( (ret==1403) || (ret==-1403) )
			{
				LogAlarm.Put(0, "PriceOn: No existe original\n");
				sprintf(stRta.szRespCA, "108");
				Armar_y_Enviar_Respuesta("02", &stRta);
				return OK;
			}
		}
		
		/* Error en la actualizacion */
		if (ret==NOOK)
		{
			LogAlarm.Put(0, "PriceOn: ERROR (%d) al actualizar BD en devolucion\n", DBTrx.GetErrno());
			if (atoi(trx_data.CodTrx())==T_DEVP)
			{
				sprintf(stRta.szRespCA, "107");
				Armar_y_Enviar_Respuesta("02", &stRta);
				return OK;
			}
		}

		/* La transaccion esta viajando (estado 01) */
		if (ret==NORTA)
		{
			/* Arma mensaje de respuesta y lo envia al TPV */
			LogAlarm.Put(0, "PriceOn: ERROR al esperar respuesta en devolucion\n");	
			sprintf(stRta.szRespCA, "101");
			Armar_y_Enviar_Respuesta("02", &stRta);
			return OK;
		} 
		
		/* La transaccion original esta pendiente de envio */
		if (ret==INSANULOFF)
		{
			LogAlarm.Put(0, "PriceOn: ANULACION de transaccion original no enviada\n");

			if ( atol(StrDataRev.retiro) > 0 )
			{
				LogAlarm.Put(0, "PriceOn: Anulacion offline con cashback no permitida");	
				sprintf(stRta.szRespCA, "110");
				Armar_y_Enviar_Respuesta("02", &stRta);
				return OK;
			}

			/* Se arma la transaccion */
			sprintf(aux_str, "%02d", T_OFLI);
			trx_data.ModEnv(aux_str);
			sprintf(aux_str, "%02d", M_CRED);
			trx_data.ModAut(aux_str);
			trx_data.NroTrc("-1");
			sprintf(aux_str, "%02d", E_NOAN);
			trx_data.CodEst(aux_str);
			trx_data.CodAut(getCodAutLocal(trx_data.CodTar()));
			sprintf(aux_str, "%04d%4.4s", ObtYear(), trx_data.FecLoc());
			trx_data.FecTrx(aux_str);
			trx_data.NroCaj(CajDevol);
			trx_data.NroTrx(TrxDevol);
			
			/* Fecha del dia */
			memset(FecVenta, 0, sizeof(FecVenta));
			memcpy(&FecVenta[0], &aux_str[6], 2);
			memcpy(&FecVenta[2], &aux_str[4], 2);
			memcpy(&FecVenta[4], &aux_str[2], 2);

			/* Se inserta como venta anulada para no enviar al CA */
			LogAlarm.Put(0, "PriceOn: Inserta venta anulada (NOEN)\n");
			ret= DBTrx.Insert(trx_data.GetInsVenData(), szRowId);
			LogAlarm.Put(0, "PriceOn: Resultado insercion: %d\n", ret);
			
			/* Arma mensaje de respuesta y lo envia al TPV */
			sprintf(stRta.szCodAut, trx_data.CodAut());
			sprintf(stRta.szTermin, term_data.nro_caj_ca);
			sprintf(stRta.szComerc, term_data.nro_com);
			sprintf(stRta.szPlnIso, term_data.plan_iso);
			sprintf(stRta.szNroLot, term_data.nro_lot);
			sprintf(stRta.szFecOri, FecVenta);
			sprintf(stRta.szTicOri, TrxVenta);
			sprintf(stRta.szPlanSF, term_data.plan_sf);
			sprintf(stRta.szRespCA, "000");
			switch (DBTipoProtocoloISO(term_data.nro_ca))
			{
			case PROT_ISO_AMEX: 
				sprintf(stRta.szProtoc, "A");
				break;
			default:
				sprintf(stRta.szProtoc, "B");
				break;
			}
			Armar_y_Enviar_Respuesta("00", &stRta);
			return OK;
			
		} /* end del if INSANULOFF */
		
		/**********************/
		/* ANULACIONES ONLINE */
		/**********************/

		if (ret==INSANUL)
		{
			LogAlarm.Put(0, "PriceOn: Se continua como ANULACION\n");

			/* Continua anulacion si monto cashback es coincidente */
			if ( atol(StrDataRev.retiro) != atol(trx_data.Retiro()) )
			{
				LogAlarm.Put(0, "PriceOn: Difiere monto cashback. VENTA:[%ld] ANULA:[%ld]\n", 
									atol(StrDataRev.retiro), atol(trx_data.Retiro()));
				sprintf(stRta.szRespCA, "110");
				Armar_y_Enviar_Respuesta("02", &stRta);
				return OK;	
			}

			/* INSERTA DEVOLUCION */
			
			/* Modo de envio "00" */
			sprintf(aux_str, "%02d", T_ONLI);
			trx_data.ModEnv(aux_str);
			
			/* Modo de autorizacion "10" */
			sprintf(aux_str, "%02d", M_CRED);
			trx_data.ModAut(aux_str);

			/* Numero de trace */
			trx_data.NroTrc("-1");

			/* Codigo de autorizacion */
			trx_data.CodAut("-1");

			/* Codigo de estado E_ANVE=28 */
			sprintf(aux_str, "%02d", E_ANVE);
			trx_data.CodEst(aux_str);

			/* Fecha de transaccion */
			sprintf(aux_str, "%04d%4.4s", ObtYear(), trx_data.FecLoc());
			trx_data.FecTrx(aux_str);
			
			/* Terminal */
			trx_data.NroCaj(CajDevol);
			
			/* Transaccion */
			trx_data.NroTrx(TrxDevol);
			
			/* Terminal original de venta */
			trx_data.NroCajOri(CajVenta);

			/* Transaccion original de venta */
			trx_data.NroTicOri(TrxVenta);

			/* Numero de lote (Caja venta para cerrar) */
			trx_data.NroLot(term_data.nro_lot);

			/* Codigo de seguridad */
			trx_data.CodSeg(" ");

			/* Track 1 */
			/*trx_data.Track1(" ");*/

			/* Track 2 */
			/*trx_data.Track2(" ");*/

			/* Borra intento de anulacion anterior */
			DBTrx.DeleteRech(trx_data.GetInsVenData(), E_RECH); /* Estado = '03' */
 			LogAlarm.Put(0, "PriceOn: DeleteRech '%02d' : %d\n", E_RECH, DBTrx.GetErrno());

			/* Se inserta devolucion para conciliar */
			if (DBTrx.Insert(trx_data.GetInsVenData(), szRowId))
			{
				LogAlarm.Put(0, "PriceOn: ERROR al insertar devolucion: %d\n", DBTrx.GetErrno());
				sprintf(stRta.szRespCA, "105");
				if ( (iTipoOperacion==T_PAGO) || (iTipoOperacion==T_DEVP) )
				{
					Armar_y_Enviar_Respuesta("11", &stRta);
				}
				else
				{
					Armar_y_Enviar_Respuesta("02", &stRta);
				}
				return OK;
			}
			strcpy(heap_data.rowid, szRowId);
			LogAlarm.Put(0, "PriceOn: Insert devolucion rowid [%s]: %d\n", szRowId, ret);

			/* TRANSFORMA DEVOLUCION EN ANULACION */

			/* Obtiene datos de la caja de venta */
			strcpy(term_data.nro_caj, CajVenta);
			ret=getDataByNT2(&term_data);

			/* Codigo de procesamiento */
			if ( (lCashBack>0) && (iTipoOperacion==2) )
			{
				lCodProc = 0;
				switch ( term_data.prot_cash[0] )
				{
				case CASHBACK_VISA: 
					lCodProc = OPCODE_VISA_ANU_CASHBACK;
					break;
				case CASHBACK_POSN:
					lCodProc = (((atol(mensaje_iso->GetField(3))/1000)%10)*1000) + OPCODE_POSN_ANU_CASHBACK;
					break;
				}
				if (lCodProc)
				{
					sprintf(szCodiProc, "%06d", lCodProc);
					mensaje_iso->PutField(3, szCodiProc);
					trx_data.CodPro(szCodiProc);
				}
			}
			else
			{
				lCodProc = 20000 + atol(mensaje_iso->GetField(3)) % 10000;
				sprintf(szCodiProc, "%06d", lCodProc);
				trx_data.CodPro(szCodiProc);
			}
			LogAlarm.Put(0, "PriceOn: Codigo de procesamiento ANUL: %s\n", szCodiProc);

			/* Cambia codigo de transaccion a 05 (Anulacion venta online) */
			sprintf(aux_str, "%02d", T_ANVE);
			trx_data.CodTrx(aux_str);
		
			/* Modo de envio */
			sprintf(aux_str, "%02d", T_ANUL);
			trx_data.ModEnv(aux_str);

			/* Modo de autorizacion */
			sprintf(aux_str, "%02d", M_CEAU);
			trx_data.ModAut(aux_str);

			/* Numero de terminal */
			trx_data.NroCaj(CajVenta);
		
			/* Numero de transaccion */
			trx_data.NroTrx(TrxVenta);
			
			/* Numero de lote */
			trx_data.NroLot(term_data.nro_lot);
			
			/* Numero de caja CA */
			trx_data.NroCajCa(term_data.nro_caj_ca);
			
			/* Numero de comercio */
			trx_data.NroCom(term_data.nro_com); 

			/* Fecha de la transaccion */
			trx_data.FecLoc(StrDataRev.fec_loc);

			/* Numero de trace */
			TraceNumber.SetNroSuc(term_data.nro_suc);
			TraceNumber.SetNroCaj(term_data.nro_caj);
			TraceNumber.SetNroCA (term_data.nro_ca );
			TraceNumber.SetCodConCie(term_data.cod_con_cie);
			strcpy(aux_str, TraceNumber);
			trx_data.NroTrc(aux_str);

			/* CONVIERTE MENSAJE ISO A ANULACION */
			
			/* Campo 3: Codigo de procesamiento */
			mensaje_iso->PutField(3, trx_data.CodPro());

			/* Campo 11: Numero de Trace */
			mensaje_iso->PutField(11, trx_data.NroTrc()); 	

        		/* Campo 12: Hora local (trx original) */
    			sprintf(aux_str, trx_data.FecLoc());
			//// mensaje_iso->PutField(12, &aux_str[4]);

			/* Campo 13: Fecha local (trx original) */
			sprintf(aux_str, "%4.4s", trx_data.FecLoc());
			//// mensaje_iso->PutField(13, aux_str);

			/* Campo 37: Numero referencia anulacion. Se agrega */
			mensaje_iso->PutField(37, StrDataRev.nro_ref);
			trx_data.NroRef(StrDataRev.nro_ref);

			/* Campo 38: Codigo de autorizacion */
			switch (DBTipoProtocoloISO(trx_data.NroCA()))
			{
			case PROT_ISO_AMEX:
				if (strlen(StrDataRev.cod_aut)>0)
				{
					mensaje_iso->PutField(38, StrDataRev.cod_aut);
					trx_data.CodAut(StrDataRev.cod_aut);
				}
				break;
			default:
				break;
			}

			/* Campo 41: Numero de caja CA */
			mensaje_iso->PutField(41, term_data.nro_caj_ca);	
			
			/* Campo 42: Numero de comercio CA */
			sprintf(aux_str, "%-15s", term_data.nro_com);
			mensaje_iso->PutField(42, aux_str);

			/* Campo 62: Numero de ticket */
			sprintf(aux_str, "004%04d", atoi(TrxVenta));
			mensaje_iso->PutField(62, aux_str);

			/* Almacena transaccion de venta */
			sprintf(NroTrxAux, "%s", TrxVenta);	
			
			/* Marca anulacion online SI */
			strcpy(heap_data.anul_onl, "1");		
		}
		else
		{
			LogAlarm.Put(0, "PriceOn: Se continua como DEVOLUCION\n");

			/* Continua devolucion solo si monto cashback es cero */
			if (lCashBack>0)
			{
				LogAlarm.Put(0, "PriceOn: Monto cashback no es cero [%ld]\n", lCashBack);
				sprintf(stRta.szRespCA, "110");
				Armar_y_Enviar_Respuesta("02", &stRta);
				return OK;	
			}
			
			/* Marca anulacion online NO */
			strcpy(heap_data.anul_onl, "0");

			/* Restaura caja y terminal del mensaje */
			trx_data.NroCaj(CajDevol);
			sprintf(NroTrxAux, "%s", trx_data.NroTrx());	
			trx_data.NroTrx(TrxDevol);
		}
		
		/* Arma el campo 48 de plan, transaccion y fecha originales */
		if(useCampCuot(trx_data.NroCA())==1)
		{
			trx_data.NroCajOri(CajVenta);
			trx_data.NroTicOri(NroTrxAux);
			DBTrx.SelTrxOrig(&StrDataRev);
			trx_data.FecOri(StrDataRev.fec_ori);
			
			LogAlarm.Put(0, "PriceOn: Datos orig. Fecha:[%s] Trx:[%s]\n", trx_data.FecOri(), trx_data.NroTicOri());
			if (heap_data.anul_onl[0]=='0') /* Si es devolucion (no es anulacion) */
			{
				strcpy(aux_str, mensaje_price->ObtCuotas());
				
				/* #37322 Cuotas articulos nacionales */
				if (term_data.plan_esp > 0)
				{
					sprintf(aux_str, "%03d", term_data.plan_esp);
				}
				
				sprintf(szCuotas, "013%1.1s%2.2s%04d%6.6s", 
						   trx_data.PlanISO(), &aux_str[1], atoi(trx_data.NroTicOri()), trx_data.FecOri()); 
			}
		}
		
		/* Almacena datos para recuperar con la respuesta */
		strcpy(heap_data.trans_ori, trx_data.NroTicOri());
		strcpy(heap_data.fecha_ori, trx_data.FecOri());

	} /* Fin manejo devoluciones */

	// Campo 48: Cuotas
	if ( strlen(szCuotas) > 0 )
	{
		mensaje_iso->PutField(48, szCuotas);
		LogAlarm.Put(1, "PriceOn: Campo 48 [%s]\n", mensaje_iso->GetField(48));
	}

        /* EMV */
        if(strlen(mensaje_price->GetField(34)) || strlen(mensaje_price->GetField(36)))
        {
            LogAlarm.Put(1, "PriceOn: Mensaje * EMV *\n");
            if(strlen(mensaje_price->GetField(34)))
            {
                sprintf(szCriptograma, "%03d%s", strlen(mensaje_price->GetField(34)), mensaje_price->GetField(34));
                mensaje_iso->PutField(55, szCriptograma);
            }
            sprintf(szVersionEMV, "%03d%s", strlen(mensaje_price->GetField(35)), mensaje_price->GetField(35));
            mensaje_iso->PutField(60, szVersionEMV);
            mensaje_iso->PutField(19, "032");

            strcat(szEMVProductList, "016  02100010040705");
            /*szEMVProductList[3] = 0x0;
            szEMVProductList[4] = 0x14;*/
            szEMVProductList[3] = 1;
            szEMVProductList[4] = 4;

            /*if(strlen(mensaje_price->GetField(36)))
            {
                strcat(szEMVProductList, "");
            } */
            mensaje_iso->PutField(59, szEMVProductList);
            ///mensaje_iso->PutField(22, "052");

            ///mensaje_iso->PutField(23, mensaje_price->GetField(37));
            
            //mensaje_iso->ClearField(12);
            //mensaje_iso->ClearField(13);

            ///mensaje_iso->PutField(46, "0011");
            /*if(!strlen(mensaje_price->GetField(30)))
            {
                mensaje_iso->PutField(46, "0011");
            }*/
        }

	/* Verifica si hay transacciones en vuelo */
	pos_ocup = P.IsPosFree(term_data.nro_ca, term_data.nro_suc, term_data.nro_caj);
	if (pos_ocup)
	{
		TrxEnVuelo=0;
	}
	else
	{
		TrxEnVuelo=1;
	}

	/* Verificamos el estado del canal X.25 */


	/*  Modificacion: 3/2/98
	Autor: Rolando Loustric
	Objetivo: Se utiliza un flag interno para el estado del canal. Este flag
	es utilizado antes del Insert y para resolver la peticion.
	Antes se consultaba CACS.IsDown, y en caso de cambiar el 
	estado del canal en medio del evento se producia un error de 
	consistencia        */
	channel_down = CACS.IsDown(atoi(term_data.nro_ca));

	/* Si el canal esta caido o hay transacciones en vuelo */
	if (channel_down||TrxEnVuelo)
	{
		LogAlarm.Put(0, "PriceOn: Centro abajo [%d] Trx en vuelo [%d]. Autoriza localmente. CAut [%s]\n", 
									channel_down, TrxEnVuelo, term_data.nro_ca);
		if (iTipoOperacion != T_PAGO)		
		{
			/* Intenta aprobar localmente */
			
			str_get_total	opers_data;
			str_get_limit	limit_data;
			
			/* Obtiene el numero de tarjeta */
			strcpy(aux_str, mensaje_price->GetField(4));
			for (cont=0; cont<strlen(aux_str); cont++)
			{
				if (aux_str[cont]==' ')
				{
					aux_str[cont]='\0';
				}
			}
		
			/* Carga datos para consultar los totales de la tarjeta */
			sprintf(opers_data.nro_tar, "%-*s", sizeof(opers_data.nro_tar)-1, aux_str);
			sprintf(opers_data.cod_est, "%0*d", sizeof(opers_data.cod_est)-1, E_PEND);
			strcpy(opers_data.cod_tar, term_data.cod_tar);
			strcpy(opers_data.plan_sf, term_data.plan_sf);
			strcpy(opers_data.cod_trx, trx_data.CodTrx());
		
			/* Carga datos para obtener los limites de respaldo del tipo de tarjeta y plan */
			strncpy(limit_data.cod_tar, mensaje_price->GetCodTar(), sizeof(limit_data.cod_tar));
			strncpy(limit_data.plan_sf,	mensaje_price->ObtPlanSf(),	sizeof(limit_data.plan_sf));
	
			/* Obtiene los limites de respaldo del tipo de tarjeta */
			ret=getLimit(&limit_data);
			if (ret!=OK)
			{
				LogAlarm.Put(0, "PriceOn: ERROR (%d) al obtener el limite de tarjeta\n", ret);
				return NOOK;
			}
			
			LogAlarm.Put(0, "PriceOn: Limites. General:%.2f - Cuotas:%.2f - Plan %s:%.2f\n", 
						(double)limit_data.limite/100.0 , (double)limit_data.limcuot/100.0 ,
						limit_data.plan_sf, (double)limit_data.limplan/100.0 );
		
			/* Obtiene el total comprado con la tarjeta */
			ret=getTotalGeneral(&opers_data);
			if (ret!=OK)
			{
				LogAlarm.Put(0, "PriceOn: ERROR (%d) al obtener total de tarjeta!!\n",	ret);
				return NOOK;
			}
			LogAlarm.Put(0, "PriceOn: Total de la tarjeta: %.2f\n", (double)opers_data.monto/100);
		
			/* Cambia el modo de la operacion a OFF-LINE */
			sprintf(aux_str, "%02d", T_OFLI); 
			trx_data.ModEnv(aux_str);

			/* Cambia el modo de ingreso */
			switch (DBTipoProtocoloISO(trx_data.NroCA()))
			{
			case PROT_ISO_AMEX:
				if (strcmp(trx_data.ModIng(), "072")==0)
				{
					trx_data.ModIng("012");
				}
				if (strcmp(trx_data.ModIng(), "062")==0)
				{
					trx_data.ModIng("022");
				}
				break;
			default:
				break;
			}

			/* Pone el modo de autorizacion por Credito */
			sprintf(aux_str, "%02d", M_CRED);
			trx_data.ModAut(aux_str);
				
			/* Pone el numero de trace (NULL) */
			trx_data.NroTrc("-1");
			
			if (heap_data.anul_onl[0]=='1')
			{
				LogAlarm.Put(0, "PriceOn: Anulacion offline no permitida\n");
				sprintf(aux_str, "%02d", E_RECH);
				trx_data.CodEst(aux_str);
				limite=NOOK;
			}
			else
			{
				/* Obtiene el monto de la transaccion en curso */
				long monto;
				monto=atol(mensaje_price->GetField(6));
				LogAlarm.Put(0, "PriceOn: Esta operacion: %.2f\n", (double)monto/100);
				LogAlarm.Put(0, "PriceOn: Total general de la tarjeta: %.2f\n", (double)opers_data.monto/100.0);
			
				/* Si las compras realizadas anteriormente mas la actual supera el limite */
				if ((opers_data.monto+monto)>limit_data.limite)
				{
					/* Se prepara el estado para registrar la operacion como rechazada */
					LogAlarm.Put(0, "PriceOn: Supera el limite\n");
					limite=NOOK;
					sprintf(aux_str, "%02d", E_RECH);
					trx_data.CodEst(aux_str);
				}
				else
				{
					/* Si el plan es en cuotas */
					if (strncmp(term_data.plan_sf, "00", 2) != 0)
					{
						/* Obtiene el total comprado en cuotas */
						ret= getTotalCuotas(&opers_data);
						if (ret!=OK)
						{
							LogAlarm.Put(0, "PriceOn: ERROR (%d) al obtener el total de la tarjeta en cuotas\n",ret);
							return NOOK;
						}
						LogAlarm.Put(0, "PriceOn: Total de la tarjeta en cuotas: %.2f\n", (double)opers_data.monto/100.0);
						
						/* Si las compras realizadas anteriormente en cuotas mas la actual supera el limite */		
						if ((opers_data.monto+monto)>limit_data.limcuot)
						{
							limite=NOOK;
						}
						else
						{
							/* Obtiene el total comprado en cuotas para ese plan */
							ret= getTotalPlan(&opers_data);
							if (ret!=OK)
							{
								LogAlarm.Put(0, "PriceOn: ERROR (%d) al obtener el total de tarjeta para el plan\n",ret);
								return NOOK;
							}
							LogAlarm.Put(0, "PriceOn: Total de la tarjeta para el plan: %.2f\n", (double)opers_data.monto/100.0);

							/* Si las compras realizadas anteriormente para el plan mas la actual supera el limite */			
							if ((opers_data.monto+monto)>limit_data.limplan)
							{
								limite=NOOK;
							}
							else
							{
								limite=OK;
							}           
						}
					}
					else
					{
						limite=OK;
					}
				
					/* Si la tarjeta tiene limite de respaldo para operrar offline */
					if (limite==OK)
					{	
						LogAlarm.Put(0, "PriceOn: No supera el limite\n");
						sprintf(aux_str, "%02d", E_PEND);
						trx_data.CodEst(aux_str);
						/*Modificacion: Codigo de autorizacion local*/
						/*configurable [28-12-2000][DL]*/
						sprintf(aux_str, "%s", getCodAutLocal(trx_data.CodTar()));
						trx_data.CodAut(aux_str);
					}
					else
					{
						LogAlarm.Put(0, "PriceOn: Supera el limite\n");
						sprintf(aux_str, "%02d", E_RECH);
						trx_data.CodEst(aux_str);
					}
				}
			}
		}		
		else /* iTipoOperacion == T_PAGO */
		{
			/* No se permite pago de resumen offline en cuotas */
			if (strncmp(term_data.plan_sf, "00", 2) != 0)
			{
				LogAlarm.Put(0, "PriceOn: Pago de resumen offline en cuotas no permitido\n");
				sprintf(aux_str, "%02d", E_RECH);
				trx_data.CodEst(aux_str);
				limite=NOOK;
			}
			else
			{
				/* Cambia el modo de la operacion a OFF-LINE */
				sprintf(aux_str, "%02d", T_OFLI); 
				trx_data.ModEnv(aux_str);

				/* Cambia el modo de ingreso */
				switch (DBTipoProtocoloISO(trx_data.NroCA()))
				{
				case PROT_ISO_AMEX:
					if (strcmp(trx_data.ModIng(), "072")==0)
					{
						trx_data.ModIng("012");
					}
					if (strcmp(trx_data.ModIng(), "062")==0)
					{
						trx_data.ModIng("022");
					}
					break;
				default:
					break;
				}

				/* Pone el modo de autorizacion por Credito */
				sprintf(aux_str, "%02d", M_CRED);
				trx_data.ModAut(aux_str);
					
				/* Pone el numero de trace (NULL) */
				trx_data.NroTrc("-1");

				/* Pone el codigo de autorizacion */
				sprintf(aux_str, "%s", getCodAutLocal(trx_data.CodTar()));
				trx_data.CodAut(aux_str);
				
				/* Pone el codigo de estado */
				sprintf(aux_str, "%02d", E_PEND);
				trx_data.CodEst(aux_str);		

				/* Acepta siempre el pago offline */
				limite = OK;
			}
		}
	} 
	else
	{
		/* Si no esta caido el canal X.25 se cambia al estado de enviado */
		sprintf(aux_str, "%02d", E_ENVI);
		trx_data.CodEst(aux_str);
		if (heap_data.anul_onl[0]!='1') /* Si no es anulacion */
		{
			trx_data.CodAut("");
		}
		TraceNumber.Inc();
	}

	/* Carga la fecha de la trx */
	sprintf(aux_str,"%04s%4.4s", trx_data.AnoTrx(), trx_data.FecLoc());
	trx_data.FecTrx(aux_str);

	/* Las transacciones rechazadas localmente no se graban en la BD */
	if (atoi(trx_data.CodEst())!=E_RECH)
	{
		LogAlarm.Put(0, "PriceOn: Inserta anulacion. nro_ref[%s] cod_aut[%s]\n", trx_data.NroRef(), trx_data.CodAut());
		ret=DBTrx.Insert(trx_data.GetInsVenData(), szRowId);
	}
	else
	{
		/* Inserta anulacion rechazada para control */
		if (heap_data.anul_onl[0]=='1')
		{
			ret=DBTrx.Insert(trx_data.GetInsVenData(), szRowId);
			LogAlarm.Put(0, "PriceOn: Inserta anulacion rechazada [%d]\n", DBTrx.GetErrno());
		}
		ret=OK;
	}

	/* Cuando se produce un error en el insert verifica existencia de */
	/* rechazadas, en caso de esto ser cierto las borra para permitir */
	/* el nuevo pedido de autorizacion.                               */
	if (ret==NOOK)
	{
		int testRech=0;   /* Testing de variables rechazadas */
		
		testRech=DBTrx.DeleteRech(trx_data.GetInsVenData(), E_RECH); /* Estado = '03' */
		if (testRech==OK)
		{
			LogAlarm.Put(0, "PriceOn: Intento de Reautorizar Trx: [%s] ya rechazada\n", mensaje_price->GetField(11));
			ret=DBTrx.Insert(trx_data.GetInsVenData(), szRowId);
		}
		if ((testRech==OK && ret==NOOK) || testRech==NOOK)
		{
			LogAlarm.Put(0, "PriceOn: ERROR (%d) en %s!!\n", 
								DBTrx.GetErrno(),	testRech==OK ? "REINSERT" : "Insert Original");
			sprintf(stRta.szRespCA, "105");
			if ( (iTipoOperacion==T_PAGO) || (iTipoOperacion==T_DEVP) )
			{
				Armar_y_Enviar_Respuesta("11", &stRta);
			}
			else
			{
				Armar_y_Enviar_Respuesta("02", &stRta);
			}
			return NOOK;
		}
	}

	/* Verificamos el estado del canal X.25                  */
	/* Si esta caido, generamos la respuesta y la devolvemos */
	if (channel_down||TrxEnVuelo)
	{ 
		/* Arma mensaje de respuesta y lo envia al TPV */
		if (limite==OK)
		{
			sprintf(stRta.szCodAut, getCodAutLocal(trx_data.CodTar()));
			sprintf(stRta.szTermin, term_data.nro_caj_ca);
			sprintf(stRta.szComerc, term_data.nro_com);
			sprintf(stRta.szPlnIso, term_data.plan_iso);
			sprintf(stRta.szNroLot, term_data.nro_lot);
			sprintf(stRta.szFecOri, trx_data.FecOri());
			sprintf(stRta.szTicOri, trx_data.NroTicOri());
			sprintf(stRta.szPlanSF, term_data.plan_sf);
			sprintf(stRta.szRespCA, "000");
			switch (DBTipoProtocoloISO(term_data.nro_ca))
			{
			case PROT_ISO_AMEX:	
				sprintf(stRta.szProtoc, "A");
				break;
			default:
				sprintf(stRta.szProtoc, "B"); 
				break;
			}
			Armar_y_Enviar_Respuesta("00", &stRta);
		}
		else
		{
			sprintf(stRta.szRespCA, "103");
			if ( (atoi(trx_data.CodTrx())==T_PAGO) || (atoi(trx_data.CodTrx())==T_DEVP) )
			{
				Armar_y_Enviar_Respuesta("11", &stRta);
			}
			else
			{
				Armar_y_Enviar_Respuesta("38", &stRta);
			}
		}
		return OK;
	}
	else /* El vinculo esta activo */
	{	
		/* Arma los datos para el heap */
		mensaje_price->GetHeapData(&heap_data);
		if (heap_data.anul_onl[0]=='1')
		{
			strcpy(heap_data.nro_term,  CajVenta);
			strcpy(heap_data.nro_trans, TrxVenta);
		}
		
		strcpy(heap_data.plan_sf,   term_data.plan_sf);
		strcpy(heap_data.nro_caj_ca,term_data.nro_caj_ca);
		heap_data.orig_pid=orig_pid;
		
		char idHeap[20];
		/* Arma clave para el heap */
		sprintf(idHeap,"%2.2s%3.3s%5.5s%8.8s", 
							term_data.nro_ca, term_data.nro_suc, term_data.nro_caj, mensaje_iso->GetField(11));
		
		/* Pone los datos en el heap */
		LogAlarm.Put(95, "PriceOn: idHeap [%s] \n", idHeap);		
		LogAlarm.Put(95, "PriceOn: anul_onl[%s] plan_iso[%s] plan_sf[%s] nro_com[%s]\n", 
							heap_data.anul_onl, heap_data.plan_iso, heap_data.plan_sf, heap_data.nro_com);		
		//LogAlarm.Put(0,  "PriceOn: heap_data.rowid [%s] \n", heap_data.rowid);		
		ret=Heap.PutData(idHeap,(char *)&heap_data, sizeof(heap_data));	
		if (ret==NOOK)
		{
			LogAlarm.Put(0, "PriceOn: ERROR (%d) al poner info en Heap\n", Heap.GetErrno());		
			return NOOK;
		}
		
		/* Registrar en la TimeoutQueue		*/
		Cfg.GetItem("TimeOutDaemon", "MsgTimeOut1", aux_str);	
		ret=timeout_queue.SetTimeOut(idHeap,atoi(aux_str), GetType(), "");
		if (ret==NOOK)
		{
			LogAlarm.Put(0, "PriceOn: ERROR (%d) al agregar a TimeOutQueue!!\n", timeout_queue.GetErrno());			
			return NOOK;
		}
		
		/* Aplana el mensaje */
		memset(msg_str,'\0',sizeof(msg_str));
		len=mensaje_iso->GetMsgString(msg_str);

		/* Envia el mensaje al CA */
		LogAlarm.Put(0, "PriceOn: Envia a X.25. CAut [%s]\n", term_data.nro_ca);
		ret=XQueue.SendMsg(atoi(term_data.nro_ca)+1, msg_str, len);
		if (ret==OK)
		{
			/* Bloquea la caja */
			ret = P.SetPosBusy(term_data.nro_ca, term_data.nro_suc, term_data.nro_caj);
			if (ret!=OK)
			{
				LogAlarm.Put(0, "PriceOn: No se pudo bloquear la caja!!\n");
			}
			LogAlarm.Put(2, "PriceOn: Respuesta enviada OK\n");
		}
		else 
		{
			LogAlarm.Put(0, "PriceOn: ERROR al enviar a X25\n");
			return NOOK;
		} 
	}
	return OK;
}
Exemplo n.º 20
0
  void Acknowledge::
  track_queue (Address const& addr, Queue& q, Messages& msgs)
  {
    unsigned short max_payload_size (
      params_.max_packet_size () - max_service_size);

    u32 max_elem (NAK::max_count (max_payload_size));
    u32 count (0);

    Queue::iterator i (q.begin ()), e (q.end ());

    // Track existing losses.
    //
    while (i != e)
    {
      auto_ptr<NAK> nak (new NAK (addr));

      // Inner loop that fills NAK profile with up to max_elem elements.
      //
      for (; i != e && nak->count () < max_elem; ++i)
      {
        u64 sn ((*i).ext_id_);
        Descr& d = (*i).int_id_;

        if (d.lost ())
        {
          d.timer (d.timer () - 1);

          if (d.timer () == 0)
          {
            //@@ Need exp fallback.
            //
            d.nak_count (d.nak_count () + 1);
            d.timer ((d.nak_count () + 1) * params_.nak_timeout ());

            nak->add (sn);

            ++count;

            // cerr << 6 << "NAK # " << d.nak_count () << ": "
            // << addr << " " << sn << endl;
          }
        }
      }

      // Send this NAK.
      //
      if (nak->count ())
      {
        // cerr << 5 << "NAK: " << addr << " " << nak->count () << " sns"
        //     << endl;

        Message_ptr m (new Message);

        m->add (Profile_ptr (nak.release ()));

        msgs.push_back (m);
      }
    }

    // Detect and record new losses.
    //
    for (u64 sn (q.sn () + 1), end (q.max_sn ()); sn < end; ++sn)
    {
      if (q.find (sn) == -1)
      {
        q.bind (sn, Descr (1));
      }
    }
  }
Exemplo n.º 21
0
int main(int argc, char* argv[]) {

    //Reverse order of a queue using a stack
    Queue<int> q;
    Stack<int> s;
    
    //Enqueue 8 integers (could be any number of objects of any data type)
    q.enqueue(100);
    q.enqueue(101);
    q.enqueue(102);
    q.enqueue(103);
    q.enqueue(104);
    q.enqueue(105);
    q.enqueue(106);
    q.enqueue(107);
    
    //Put these numbers into the stack
    for (int n = 0; n < 8; n++) {
        Node<int> m = q.dequeue();
        s.push(m);
    }
    //Now queue is empty, and stack has 8 integers
    //Latest item on stack contains earliest item in queue
    
    //Transfer elements back to queue
    for (int n = 0; n < 8; n++) {
        Node<int> m = s.pop();
        q.enqueue(m);
    }
    //Stack is now empty, and queue is reversed
    
    //A check for correctness of this program that destroys the queue.
    std::cout << "Reversed queue      ";
    for (int n = 0; n < 8; n++) {
        Node<int> m = q.dequeue();
        std::cout << m.getData() << " ";
    }
    std::cout << std::endl; 
    
    //------------------------------------------------------------------------
    
    //Get "valley" of entries in an array
    const int SIZE_ONE = 7;
    int prices[SIZE_ONE] = {100, 80, 60, 70, 60, 75, 85};
    /*Set all to zero. This eliminates the need to check if an element 
    is smaller than its predecessor, which implies that the valley of
    this element is zero.*/
    int valley[SIZE_ONE] = {0, 0, 0, 0, 0, 0, 0};
    Stack<int> displacement;
    int largest = prices[0];
    displacement.push(0);
    
    
    for (int n = 1; n < SIZE_ONE; n++) {
    
        if (prices[n] >= largest) {  //If element is largest seen thus far,
            valley[n] = n;           //then its valley is its index
            largest = prices[n];
        }
        
        /*If an element is greater than the one before it, then it must
        be compared with previous elements. These previous elements are
        obtained from the stack. Pop the stack while the value of the
        current element is greater than or equal to the popped element.
        This stops when current element is less than the one on top of
        the stack; valley of current element is equal to its index minus
        the index of the larger element minus one. It can be proved by
        contradiction that this eliminates superfluous checking for larger
        elements further down the array because we know that these larger
        elements are greater than or equal to the ones that were 
        popped off the stack*/
        
        else if (prices[n] >= prices[n - 1]) {
            while (prices[n] >= prices[displacement.top()])
                Node<int> garbage = displacement.pop();
            valley[n] = n - displacement.top() - 1;
        }
        
        displacement.push(n);
    }
    
    //A check for the correctness of the algorithm
    std::cout << "First valley array  ";
    for (int n = 0; n < SIZE_ONE; n++)
        std::cout << valley[n] << " ";
    std::cout << std::endl;
    
    //------------------------------------------------------------------------
    
    /*Another run of the algorithm. Note that the largest value appears
    somwhere in the middle of the array.*/
    const int SIZE_TWO = 16;
    double expenditures[SIZE_TWO] = {55.99, 63, 66.66, 69.69, 75, 1337.13,
    82.50, 90.95, 91, 96.50, 100, 105.25, 123.45, 133.70, 144.44, 191};
    int valley2[SIZE_TWO];
    for (int n = 0; n < SIZE_TWO; n++)
        valley2[n] = 0;
    Stack<int> disp;
    int greatest = expenditures[0];
    disp.push(0);
    
    for (int n = 1; n < SIZE_TWO; n++) {
        if (expenditures[n] >= greatest) {
            valley2[n] = n;
            greatest = expenditures[n];
        } else if (expenditures[n] >= expenditures[n - 1]) {
            while (expenditures[n] >= expenditures[disp.top()])
                Node<int> garbage = disp.pop();
            valley2[n] = n - disp.top() - 1;
        }
        disp.push(n);
    }
    
    std::cout << "Second valley array ";
    for (int n = 0; n < SIZE_TWO; n++)
        std::cout << valley2[n] << " ";
    std::cout << std::endl;
    
    return 0;
}
Exemplo n.º 22
0
void MenuStartAdmin::handleAssignPressed(Button *pButton) {
    MenuStartAdmin::instance()->erase();
    
    //Get a course selection from user
    
    //Get course list
    const std::string* courses;
    int count;
    Database::instance()->getCourses(&courses, count);
    //Show dialog
    DialogListSelector *pCourseSelector = new DialogListSelector("Assign TA: Select a Course", courses, count);
    if (pCourseSelector->show() != STATE_SUCCESS) {
        delete pCourseSelector;
        MenuStartAdmin::instance()->draw();
        return;
    }
    std::string strCourse = pCourseSelector->getSelectedValue();
    delete pCourseSelector;
    
    //Show list of applications
    
    Queue<TaApplication*>* pApplications = Database::instance()->getApplications(strCourse);
    if (pApplications == 0 || pApplications->isEmpty()) {
        DialogYesNo* pMsg = new DialogYesNo("No applicants available for " + strCourse, DIALOG_MESSAGE);
        pMsg->show();
        delete pMsg;
        MenuStartAdmin::instance()->draw();
        return;
    }
    //Create str[] from queue for listDialog
    std::string* pStrApplications = new std::string[pApplications->getSize()];
    Node<TaApplication*>* pCur = pApplications->front();
    int i = 0;
    while (pCur != 0) {
        if (pCur->value->getStatus() == STATUS_PENDING) {
            pStrApplications[i] =  pCur->value->getStudentID();
            i++;
        }
        pCur = pCur->m_pNext;
    }
    if (i == 0) {
        //No applicants pending
        DialogYesNo* pMsg = new DialogYesNo("No applicants available for " + strCourse, DIALOG_MESSAGE);
        pMsg->show();
        delete pMsg;
        MenuStartAdmin::instance()->draw();
        return;
    }
    //Show the dialog
    DialogListSelector *pDia = new DialogListSelector("Assign TA: Select an Applicant", pStrApplications, i);
    if (pDia->show() != STATE_SUCCESS) {
        delete pDia;
        delete [] pStrApplications;
        MenuStartAdmin::instance()->draw();
        return;
    }
    std::string strApplication = pDia->getSelectedValue();
    delete [] pStrApplications;
    delete pDia;
    
    //Get the selected application
    
    TaApplication* pApp = 0;
    pCur = pApplications->front();
    while (pCur != 0) {
        if (strApplication.find(pCur->value->getStudentID()) != std::string::npos) {
            pApp = pCur->value;
        }
        pCur = pCur->m_pNext;
    }
    if (pApp == 0) {
        MenuStartAdmin::instance()->draw();
        return;
    }
    Student *pStu = Database::instance()->getStudent(pApp->getStudentID());
    if (pStu == 0) {
        return;
    }
    if (pStu->getApplications() != 0 && pStu->getApplications()->getSize() > 1) {
        pCur = pStu->getApplications()->front();
        while (pCur != 0) {
            if (pCur->value != pApp) {
                pCur->value->setStatus(STATUS_CLOSED);
                pCur->value->saveToFile();
            }
            pCur = pCur->m_pNext;
        }
    }
    pApp->setStatus(STATUS_ACCEPTED);
    pApp->saveToFile();
    DialogYesNo* pMsg = new DialogYesNo("Student " + pApp->getStudentID() + " has been assigned as TA.", DIALOG_MESSAGE);
    pMsg->show();
    delete pMsg;
    MenuStartAdmin::instance()->draw();
}
Exemplo n.º 23
0
int main(int argc, const char * argv[]) {

    /* Definir una cola */
    Queue<Persona>* cola = new Queue<Persona>();
    
    Persona p1("a", "t", 0);
     Persona p2("b", "t", 0);
      Persona p3("c", "t", 0);
       Persona p4("d", "t", 0);
    
    

    cola->enqueue(p1);
    cola->enqueue(p2);
    cola->enqueue(p3);
    cola->enqueue(p4);    
    /* Insertar elementos en la cola 
    cola->enqueue();
    cola->enqueue(2);
    cola->enqueue(3);
    cola->enqueue(4);
    
    */
    /* Mostrar el contenido de la cola */
    std::cout << *cola << std::endl;
    
    /* Obtener el elemento que está al inicio */
    Node<Persona> * node = cola->first();
    
    if (node != nullptr) {
        std::cout << "First = " << *node << std::endl;
    }
    
    /* Obtener el elemento que está al final */
    node = cola->last();
    
    if (node != nullptr) {
        std::cout << "Last = " << *node << std::endl;
    }
    
    /* Eliminar un elemento */
    node = cola->dequeue();
    
    if (node != nullptr) {
        std::cout << "Nodo a eliminar = " << *node << std::endl;
        delete node;
    }
    
    /* Obtener el elemento que está al inicio */
    node = cola->first();
    
    if (node != nullptr) {
        std::cout << "First = " << *node << std::endl;
    }
    
    /* Mostrar el contenido de la cola */
    std::cout << *cola << std::endl;
    
    /* Eliminar la cola.
    * Automáticamente se invoca al destructor.
    */
    
    return 0;
}
int main()
{
    // print my name and this assignment's title
  cout << "Lab 8b, The \"QueueDriver.cpp\" Program \n";
  cout << "Programmer: JEREMY THOMPSON\n";
  cout << "Editor(s) used: JNotePad\n";
  cout << "Compiler(s) used: VC++ 2013\n";
  cout << "File: " << __FILE__ << endl;
  cout << "Complied: " << __DATE__ << " at " << __TIME__ << endl;

  // create the queue
  Queue <int> myQueue;
  for (int i = 0; i < 12; i++)
  {
    myQueue.push(i);
  }
  int queuePeek;
  int queueCopy;
  int queuePop;
  // display queue contents
  cout << "The queue currently contains the following elements: " << endl;
  for (Queue<int> copy = myQueue; !copy.isEmpty(); copy.pop(queueCopy))
  {
    copy.peek(queuePeek);
    cout << queuePeek << " ";
  }

  if (myQueue.isEmpty() == true)
    cout << "\nThe isEmpty function IS NOT working as the queue is NOT empty." << endl;
  else
    cout << "\nThe isEmpty function IS working properly as the queue is NOT empty." << endl;

  if (myQueue.pop(queuePop) == true)
    cout << "The pop function IS working as there ARE elements in the queue." << endl;
  else
    cout << "The pop function IS NOT working as there ARE elements in the queue to pop." << endl;

  if (myQueue.peek(queuePeek) == true)
  {
    cout << "Expected 'peek' output is 1." << endl;
    cout << "Actual 'peek' output is: " << queuePeek << endl;
  }

  myQueue.makeEmpty();
  if (myQueue.isEmpty() == true)
    cout << "The makeEmpty function IS working as the queue is now empty." << endl;
  else
    cout << "The makeEmpty function IS NOT working as the queue is now empty." << endl;

  {
    Queue <int> myQueue1;
    for (int i = 0; i < 12; i++)
    {
      myQueue.push(i);
    }
    // object testing with assignment UPON declaration
    const Queue<int> copy = myQueue;

    cout << "\nObject copy test with assignment UPON declaration";

    if (copy.isEmpty() == true)
      cout << "\nThe isEmpty function IS NOT working as there are elements in the queue." << endl;
    else
      cout << "\nThe isEmpty function IS working as there are elements in the queue." << endl;

    int queuePeek;
    if (copy.peek(queuePeek) == true)
    {
      cout << "Expected 'peek' output is 0." << endl;
      cout << "Actual 'peek' output is: " << queuePeek << endl;
    }
  }
  // object testing with assignment AFTER declaration
  {
    Queue <int> myQueue1;
    for (int i = 0; i < 12; i++)
    {
      myQueue.push(i);
    }
    Queue<int> copy = myQueue;
    cout << "\nObject copy test with assignment AFTER declaration";

    if (copy.isEmpty() == true)
      cout << "\nThe isEmpty function IS NOT working as elements are in the queue." << endl;
    else
      cout << "\nThe isEmpty function IS working as there are elements in the queue." << endl;

    int queuePop;
    if (copy.pop(queuePop) == true)
      cout << "The pop function IS working as there are elements to pop." << endl;
    else  
      cout << "The pop function IS NOT working as there are elements to pop." << endl;

    if (copy.peek(queuePop) == true)
    {
      cout << "Expected 'peek' output is 1." << endl;
      cout << "Actual 'peek' output is: " << queuePeek << endl;
    }

    copy.makeEmpty();
    if (copy.isEmpty() == true)
      cout << "The makeEmpty function IS working as the queue is now empty." << endl;
    else
      cout << "The makeEmpty function IS NOT working as the queue is now empty." << endl;
  }
  cout << "\nPress ENTER to continue...";
  cin.get();
}
Exemplo n.º 25
0
void StrandPrivate::process()
{
  static const unsigned int QI_STRAND_QUANTUM_US =
    qi::os::getEnvDefault<unsigned int>("QI_STRAND_QUANTUM_US", 5000);

  qiLogDebug() << "StrandPrivate::process started";

  _processingThread = qi::os::gettid();

  qi::SteadyClockTimePoint start = qi::SteadyClock::now();

  bool finished = false;

  do
  {
    boost::shared_ptr<Callback> cbStruct;
    {
      boost::mutex::scoped_lock lock(_mutex);
      assert(_processing);
      if (_queue.empty())
      {
        qiLogDebug() << "Queue empty, stopping";
        _processing = false;
        _processFinished.notify_all();
        finished = true;
        break;
      }
      cbStruct = _queue.front();
      _queue.pop_front();
      if (cbStruct->state == State_Scheduled)
      {
        --_aliveCount;
        cbStruct->state = State_Running;
      }
      else
      {
        // Job was canceled, cancel() already has done --_aliveCount
        qiLogDebug() << "Abandoning job id " << cbStruct->id
          << ", state: " << cbStruct->state;
        continue;
      }
    }
    qiLogDebug() << "Executing job id " << cbStruct->id;
    try {
      cbStruct->callback();
      cbStruct->promise.setValue(0);
    }
    catch (std::exception& e) {
      cbStruct->promise.setError(e.what());
    }
    catch (...) {
      cbStruct->promise.setError("callback has thrown in strand");
    }
    qiLogDebug() << "Finished job id " << cbStruct->id;
  } while (qi::SteadyClock::now() - start < qi::MicroSeconds(QI_STRAND_QUANTUM_US));

  _processingThread = 0;

  // if we still have work
  if (!finished)
  {
    assert(_processing);

    qiLogDebug() << "Strand quantum expired, rescheduling";
    _eventLoop.async(boost::bind(&StrandPrivate::process, shared_from_this()),
        qi::Duration(0));
  }
}
Exemplo n.º 26
0
int main() {
  cout << "Lab 8b, The \"QueueDriver\" Program " << endl
       << "File: " << __FILE__ << endl
       << "Complied: " << __DATE__ << " at " << __TIME__ << endl;
  
  Queue<int> queue;
  int peek;
  int pop;
  bool result;
  
  cout << "\nTesting member function push()" << endl;
  queue.push(12);
  queue.push(13);
  
  cout << "\nTesting member function peek()";
  result = queue.peek(peek);
  cout << "\nThe expected result is true and 12"
       << "\nThe actual result is " << boolalpha << result << " and "  << peek << endl;
  assert(result == true);
  assert(peek == 12);
  
  cout << "\nTesting member function isEmpty()"
       << "\nThe expected result is false"
       << "\nThe actual result is " << boolalpha << queue.isEmpty() << endl;
  assert(queue.isEmpty() == false);
  
  cout << "\nTesting member function pop()";
  result = queue.pop(pop);
  cout << "\nThe expected result is true and 12"
       << "\nThe actual result is " << boolalpha << result << " and "  << pop << endl;
  assert(result == true);
  assert(pop == 12);
  
  cout << "\nTesting member function makeEmpty" << endl;
  queue.makeEmpty();
  cout << "\nThe expected result is true"
       << "\nThe actual result is " << boolalpha << queue.isEmpty() << endl;
  assert(queue.isEmpty() == true);
  
   //object copy testing
  cout << "\n**************************************"
       << "\nObject copy testing";
  Queue<int> copy1 = queue;
  
  cout << "\nTesting member function push()" << endl;
  copy1.push(11);
  copy1.push(12);
  copy1.push(13);
  
  cout << "\nTesting member function peek()";
  result = copy1.peek(peek);
  cout << "\nThe expected result is ture and 11"
       << "\nThe actual result is " << boolalpha << result << " and "  << peek << endl;
  assert(result == true);
  assert(peek == 11);
  
  cout << "\nTesting member function isEmpty()"
       << "\nThe expected result is false"
       << "\nThe actual result is " << boolalpha << copy1.isEmpty() << endl;
  assert(copy1.isEmpty() == false);
  
  cout << "\nTesting member function pop()";
  result = copy1.pop(pop);
  cout << "\nThe expected result is true and 11"
       << "\nThe actual result is " << boolalpha << result << " and "  << pop << endl;
  assert(result == true);
  assert(pop == 11);
  
  cout << "\nTesting member function makeEmpty" << endl;
  copy1.makeEmpty();
  cout << "The expected result is true"
       << "\nThe actual result is " << boolalpha << copy1.isEmpty() << endl;
  assert(copy1.isEmpty() == true);
  
  //objecy assignmnet testing
  cout << "\n**************************************"
       << "\nObject assignment testing";
  Queue<int> copy2;
  copy2 = queue;
  
  cout << "\nTesting member function push()" << endl;
  copy2.push(10);
  copy2.push(11);
  copy2.push(12);
  copy2.push(13);
  
  cout << "\nTesting member function peek()";
  result = copy2.peek(peek);
  cout << "\nThe expected result is ture and 10"
       << "\nThe actual result is " << boolalpha << result << " and "  << peek << endl;
  assert(result == true);
  assert(peek == 10);
  
  cout << "\nTesting member function isEmpty()"
       << "\nThe expected result is false"
       << "\nThe actual result is " << boolalpha << copy2.isEmpty() << endl;
  assert(copy2.isEmpty() == false);
  
  cout << "\nTesting member function pop()";
  result = copy2.pop(pop);
  cout << "\nThe expected result is true and 10"
       << "\nThe actual result is " << boolalpha << result << " and "  << pop << endl;
  assert(result == true);
  assert(pop == 10);
  
  cout << "\nTesting member function makeEmpty" << endl;
  copy2.makeEmpty();
  cout << "The expected result is true"
       << "\nThe actual result is " << boolalpha << copy2.isEmpty() << endl;
  assert(copy2.isEmpty() == true);

  return 0;
}
Exemplo n.º 27
0
int main()
{
	ifstream fin(INFILE);
	int V, G, v, g;
	fin >> V;
	int reqs[V];
	for (v = 0; v < V; ++v)
		fin >> reqs[v];
	fin >> G;
	int feeds[G][V];
	for (g = 0; g < G; ++g)
		for (v = 0; v < V; ++v)
			fin >> feeds[g][v];
	fin.close();

	Queue q;
	for (g = 0; g < G; ++g)
		q.push(1 << g);

	ofstream fout(OUTFILE);
	while (! q.empty())
	{
		int s = q.pop();
		int test[V];
		for (v = 0; v < V; ++v)
			test[v] = 0;
		int bit, n = 0;
		for (g = 0, bit = 1; g < G; ++g, bit <<= 1)
			if (bit & s)
			{
				for (v = 0; v < V; ++v)
					test[v] += feeds[g][v];
				++n;
			}
		bool pass = true;
		for (v = 0; v < V; ++v)
			if (test[v] < reqs[v])
			{
				pass = false;
				break;
			}
		if (pass)
		{
			fout << n << ' ';
			for (g = 0, bit = 1; g < G; ++g, bit <<= 1)
				if (bit & s)
				{
					fout << g+1;
					--n;
					if (n != 0)
						fout << ' ';
				}
			fout << endl;
			fout.close();
			return 0;
		}
		else
		{
//			for (g = 0, bit = 1; g < G; ++g, bit <<= 1)
//				if (bit & s)
//					cout << g+1 << ' ';
//			cout << endl;

			for (bit = 1 << G, g = G-1; ! (bit & s); bit >>= 1, --g);
			for (g = g + 2, bit = (bit == 0 ? 1 : bit << 1); g < G; ++g, bit <<= 1)
				q.push(s | bit);
		}
	}

	return 0;
}
Exemplo n.º 28
0
static void *mlt_worker_thread_main(void *)
{
    thread_running = true;
    while (true)
    {
        // wait for request
        //printf("slave: waiting...\n");
        while (async_requests.empty())
        {
            usleep(1000);
        }
        //printf("slave: req queue not empty!\n");
        async_req_t req = async_requests.pop();
        
        /*printf("slave: got req: %s.\n", (req.type == ANIM) ? "anim" :
                            (req.type == LAND_ART) ? "land art" :
                            (req.type == STATIC_ART) ? "static art" :
                            (req.type == LAND_BLOCK) ? "land block" :
                            (req.type == STATICS_BLOCK) ? "statics block" :
                            "<unknown>");*/

        if (req.type == ANIM)
        {
            req.anim.res = ml_read_anim(req.anim.body_id, req.anim.action, req.anim.direction);
        }
        else if (req.type == LAND_ART)
        {
            req.land_art.res = ml_read_land_art(req.land_art.land_id);
        }
        else if (req.type == STATIC_ART)
        {
            req.static_art.res = ml_read_static_art(req.static_art.item_id);
        }
        else if (req.type == GUMP)
        {
            req.gump.res = ml_read_gump(req.gump.gump_id);
        }
        else if (req.type == LAND_BLOCK)
        {
            req.land_block.res = ml_read_land_block(req.land_block.map, req.land_block.block_x, req.land_block.block_y);
        }
        else if (req.type == STATICS_BLOCK)
        {
            req.statics_block.res = ml_read_statics_block(req.statics_block.map, req.statics_block.block_x, req.statics_block.block_y);
        }
        else if (req.type == SHUTDOWN)
        {
            // oh well, we had a good run...
            printf("[MLT] slave thread: shutting down. no more messages will be processed.\n");
            break;
        }
        else
        {
            assert(0 && "slave: unknown req type...");
        }
        async_responses.push(req);

        //printf("slave: sent response.\n");
    }
    printf("[MLT] slave thread: exiting.\n");
    thread_running = false;
    return NULL;
}
Exemplo n.º 29
0
TEST(QueueTest, hasNext) {
    Queue<int>* iq = new Queue<int>();
    EXPECT_FALSE(iq->hasNext());
    iq->push(5);
    EXPECT_TRUE(iq->hasNext());
}
Exemplo n.º 30
0
void queue_isr() {
    queue.put((uint32_t*)2);
    myled = !myled;
}