示例#1
0
void errorOut(char *pFile, CBuffer pError, bool pWrite)
{
	if (pWrite)
	{
		printf("[%s] %s\n", getTimeStr(1).text(), pError.text());
	}

	char buffer[60] = "logs/";
	strcpy(buffer+5, pFile);
	FILE *file = fopen(buffer, "a");
	fprintf(file, "[%s] %s\r\n", getTimeStr(0).text(), pError.text());
	fclose(file);
}
示例#2
0
int realStat(const char *path, long interval, enum FileType file_type, bool isSuppress){
    CacheStat stat;
    int pre = 0;
    bool first = true;
    bool ret = false;

    memset(&stat, 0, sizeof(stat));
    fprintf(stdout, "file:%s\n", path);
    fprintf(stdout, "time\tpageCount\tinCache\tchange\n");

    while(1){
        pre = stat.inCache;
        memset(&stat, 0, sizeof(stat));
        ret = normalStat(path, file_type, &stat);

        if(pre==stat.inCache && isSuppress && !first) continue;
        first = false;
        if(ret == false){
            fprintf(stderr, "real stat error %s\n", path);
            exit(0);
        }else{
            fprintf(stdout, "%s %d\t%d\t%d\n", 
               getTimeStr(), stat.pageCount, stat.inCache, stat.inCache-pre);
        } 
        usleep(interval);
    }
}
示例#3
0
VOID Display::init()
{
   struct sigaction action_quit;

   initscr();
   noecho();

   m_dispIntvl = Config::getInstance()->getDisplayRefreshTimer();
   m_pStats = Stats::getInstance();
   getTimeStr(m_timeStr);
   m_startTime = getMilliSeconds() / 1000;
   m_remPort = Config::getInstance()->getRemoteGtpcPort(); 
   STRCPY(m_remIpAddrStr, (Config::getInstance()->\
         getRemIpAddrStr()).c_str());

   m_pMsgVec = &(Scenario::getInstance()->m_msgVec);
   m_msgVecLen = m_pMsgVec->size();

   /* Map exit handlers to curses reset procedure */
   memset(&action_quit, 0, sizeof(action_quit));
   (*(void **)(&(action_quit.sa_handler))) = (VOID *)screen_exit;
   sigaction(SIGTERM, &action_quit, NULL);
   sigaction(SIGINT, &action_quit, NULL);
   sigaction(SIGKILL, &action_quit, NULL);  

   CLEAR_SCREEN();
}
示例#4
0
void acceptNewPlayers(CSocket& pSocket)
{
	CSocket* newSock = pSocket.accept();
	if(newSock == 0)
		return;

	newPlayers.add(new CPlayer(newSock));
	printf( "[%s] Incoming connection: [%s]\n", getTimeStr(1).text(), newSock->tcpIp() );
}
示例#5
0
void eTimeCorrectionEditWindow::updateTimeDate()
{
	time_t now = time(0)+eDVB::getInstance()->time_difference;
	tm ltime = *localtime( &now );
	lCurTime->setText(getTimeStr(&ltime, gTS_SECS));
	lCurDate->setText(eString().sprintf("%02d.%02d.%04d", ltime.tm_mday, ltime.tm_mon+1, 1900+ltime.tm_year));
	eDVBServiceController *sapi = eDVB::getInstance()->getServiceAPI();
	if ( sapi && sapi->tdt && sapi->transponder )
	{
		time_t tpTime = now + sapi->lastTpTimeDifference;
		tm ltime = *localtime( &tpTime );
		lTpTime->setText(getTimeStr(&ltime, gTS_SECS));
		lTpDate->setText(eString().sprintf("%02d.%02d.%04d", ltime.tm_mday, ltime.tm_mon+1, 1900+ltime.tm_year));
	}
	else
	{
		lTpTime->setText(_("no transponder time"));
		lTpDate->setText("");
	}
}
示例#6
0
文件: com.c 项目: 8l/insieme
void
printReportHeader ( void )
{
  char *now;
  int nameSize;
  char myProcName[MPI_MAX_PROCESSOR_NAME];

  if ( rank == 0 )
  {
    now = getTimeStr (  );
    MPI_Get_processor_name ( myProcName, &nameSize );

    printSeparator (  );
    printf ( "\n  com Point-to-Point MPI Bandwidth and Latency Benchmark\n" );
    printf ( "  Version %d.%d.%d\n", majorVersion, minorVersion,
             patchVersion );
    printf ( "  Run at %s, with rank 0 on %s\n\n", now, myProcName );
    free ( now );
    printParameters (  );

    if ( presta_check_data == 1 )
    {
      printf
        ( "  *** Verifying operation message buffers.  Benchmark results not valid! ***\n" );
    }

    if ( strlen ( procSrcTitle ) > 0 )
      printf ( "  Using Task Pair file %s\n", procSrcTitle );

    printf ( "\n" );

    if ( strcmp ( argStruct.testList, "Latency" ) != 0 )
    {
      if ( argStruct.sumLocalBW == 1 )
        printf ( "  Bandwidth calculated as sum of process bandwidths.\n" );
      else if ( argStruct.sumLocalBW == 0 )
        printf
          ( "  Bandwidth calculated as total volume / longest task communication.\n" );

      /*  TODO : Not necessary unless providing info about sample time.
         printTimingInfo ( );   
       */
    }
  }


  if ( argStruct.printHostInfo )
    printCommTargets ( argStruct.procsPerNode, argStruct.useNearestRank );

  printSeparator (  );

}
示例#7
0
void FileUnit::saveModel()
{
	auto map = Detect::shareDetect()->saveModel();
	ValueMap labelMap;
	auto player = Detect::shareDetect()->getPlayer();
	std::string info = StringUtils::format("%s %d %d %d %d %d",player->getNickName().c_str(),player->getHp(),player->getStr(),player->getDef(),player->getGold(),player->getXp());
	labelMap["info"] = info;
	std::string date = getTimeStr();
	labelMap["date"] = date;
	map["label"] = labelMap;
	map["exist"] = true;
	FileUtils::getInstance()->writeToFile(map,_path);
}
示例#8
0
void CSaveMenu::sendEvent(std::shared_ptr<CEvent> &command)
{
    InputText *pInput = dynamic_cast<InputText*>(mpMenuDialog->CurrentControl());

	// Before all events are sent to the dialog which handles selection catch some specific events
	// required for the saving process.
	if( CommandEvent *ev = dynamic_cast<CommandEvent*>(command.get()) )
	{
		const int sel = mpMenuDialog->Selection();
		if( sel > 0 )
		{            
			if(ev->mCommand == IC_JUMP || ev->mCommand == IC_STATUS)
			{			

#ifdef NOTYPESAVE
                const std::string saveText = getTimeStr();

#else
				if(pInput->Typing())
                {
                    const std::string saveText = pInput->getText();
#endif
                    gpSaveGameController->prepareSaveGame( sel, saveText );
                    g_pBehaviorEngine->setPause(false);
					gEventManager.add( new CloseAllMenusEvent() );
#ifndef NOTYPESAVE
				}          
				else
				{
					if(pInput->getText() == EMPTY_TEXT)
						pInput->setText("");
					pInput->setTypeMode(true);
				}
#endif

				return;
			}
		}
	}

    if(pInput)
    {
        if(pInput->Typing())
            return;
    }


	mpMenuDialog->sendEvent(command);
}
示例#9
0
void addLog(const char * logMessage)
{
    char timeBuffer[80];

    getTimeStr(timeBuffer, sizeof(timeBuffer));

    int newCapacity = strlen(timeBuffer) + strlen(logMessage) + logLength;

    if(newCapacity >= capacity){

        if(capacity==0)
        {
            capacity =1;
        }

         while(newCapacity >= capacity){

            capacity *= 2;

            capacity++; // extra position for NULL

         }

        char * newData = malloc(capacity);

        if(logLength > 0){ // there exists log data

            strcpy(newData, logData); // copy the previous data to newData

            free(logData); // free the space logData pointed

        }

        logData = newData; // make logData points to what newData points, which is the updated log data

    }



    strcpy(logData + logLength, timeBuffer); // change pointer to the next position of the end of previous log, and add time tag to logData

    logLength += strlen(timeBuffer);

    strcpy(logData + logLength, logMessage);// change pointer to the next position of the end of timelog, and add log message to logData

    logLength += strlen(logMessage);

}
示例#10
0
CLevel* CLevel::openMap(CString& pFileName)
{
	CLevel* level = find(pFileName);
	if(level != NULL)
		return level;

	level = new CLevel(pFileName);
	if(!level->opened)
	{
		delete level;
		return NOLEVEL;
	}

	levelList.add(level);
	if ( detailedconsole ) printf("[%s] MAP COUNT: %i\n", getTimeStr(1).text(), levelList.count());
	return level;
}
示例#11
0
void LogAttribute::onTrigger(core::ProcessContext *context, core::ProcessSession *session) {
  logger_->log_trace("enter log attribute");
  std::string dashLine = "--------------------------------------------------";
  LogAttrLevel level = LogAttrLevelInfo;
  bool logPayload = false;
  std::ostringstream message;

  std::shared_ptr<core::FlowFile> flow = session->get();

  if (!flow) {
    return;
  }

  std::string value;
  if (context->getProperty(LogLevel.getName(), value)) {
    logLevelStringToEnum(value, level);
  }
  if (context->getProperty(LogPrefix.getName(), value)) {
    dashLine = "-----" + value + "-----";
  }
  if (context->getProperty(LogPayload.getName(), value)) {
    org::apache::nifi::minifi::utils::StringUtils::StringToBool(value, logPayload);
  }

  message << "Logging for flow file " << "\n";
  message << dashLine;
  message << "\nStandard FlowFile Attributes";
  message << "\n" << "UUID:" << flow->getUUIDStr();
  message << "\n" << "EntryDate:" << getTimeStr(flow->getEntryDate());
  message << "\n" << "lineageStartDate:" << getTimeStr(flow->getlineageStartDate());
  message << "\n" << "Size:" << flow->getSize() << " Offset:" << flow->getOffset();
  message << "\nFlowFile Attributes Map Content";
  std::map<std::string, std::string> attrs = flow->getAttributes();
  std::map<std::string, std::string>::iterator it;
  for (it = attrs.begin(); it != attrs.end(); it++) {
    message << "\n" << "key:" << it->first << " value:" << it->second;
  }
  message << "\nFlowFile Resource Claim Content";
  std::shared_ptr<ResourceClaim> claim = flow->getResourceClaim();
  if (claim) {
    message << "\n" << "Content Claim:" << claim->getContentFullPath();
  }
  if (logPayload && flow->getSize() <= 1024 * 1024) {
    message << "\n" << "Payload:" << "\n";
    ReadCallback callback(flow->getSize());
    session->read(flow, &callback);
    for (unsigned int i = 0, j = 0; i < callback.read_size_; i++) {
      message << std::hex << callback.buffer_[i];
      j++;
      if (j == 80) {
        message << '\n';
        j = 0;
      }
    }
  }
  message << "\n" << dashLine << std::ends;
  std::string output = message.str();

  switch (level) {
    case LogAttrLevelInfo:
      logger_->log_info("%s", output);
      break;
    case LogAttrLevelDebug:
      logger_->log_debug("%s", output);
      break;
    case LogAttrLevelError:
      logger_->log_error("%s", output);
      break;
    case LogAttrLevelTrace:
      logger_->log_trace("%s", output);
      break;
    case LogAttrLevelWarn:
      logger_->log_warn("%s", output);
      break;
    default:
      break;
  }

  // Test Import
  /*
   std::shared_ptr<FlowFileRecord> importRecord = session->create();
   session->import(claim->getContentFullPath(), importRecord);
   session->transfer(importRecord, Success); */

  // Transfer to the relationship
  session->transfer(flow, Success);
}
示例#12
0
void ListServer_Main()
{
	static CBuffer packetBuffer;
	CStringList lines;

	if ( listServerFields[5] == "localhost" ) return;
	if (!lsConnected) return;

	// Read any new data into the socket.
	if ( listServer.getData() == -1 )
	{
		errorOut( "serverlog.txt", "Disconnected from list server." );
		lsConnected = false;
		return;
	}

	// Grab all the data from the socket buffer.
	packetBuffer << listServer.getBuffer();
	listServer.getBuffer().clear();

	// Search for a packet.  If none is found, break out of the loop.
	while (packetBuffer.length() != 0)
	{
		CPacket line;
		if (!nextIsRaw)
		{
			int lineEnd = packetBuffer.find( '\n' );
			if ( lineEnd == -1 ) return;

			// Copy the packet out and remove the \n
			line = packetBuffer.copy( 0, lineEnd + 1 );
			packetBuffer.remove(0, line.length());
			line.remove(line.length() - 1, 1);
		}
		else
		{
			if (packetBuffer.length() < rawPacketSize) return;
			line.writeBytes(packetBuffer.readChars(rawPacketSize), rawPacketSize);
			packetBuffer.remove(0, line.length());
			line.remove(line.length() - 1, 1);
			nextIsRaw = false;
		}
		packetBuffer.setRead(0);

		int messageId = line.readByte1();
		switch (messageId)
		{
			case GSVOLD:
			{
				printf("[%s] SERVER VERSION CHECK - Current: %i, Latest: %i - Old version, please upgrade.\n", getTimeStr(1).text(), GSERVER_BUILD, line.readByte2());
				break;
			}

			case GSVCURRENT:
			{
				printf("[%s] SERVER VERSION CHECK - Current: %i, Latest: %i - You are up to date :)\n", getTimeStr(1).text(), GSERVER_BUILD, GSERVER_BUILD);
				break;
			}

			case GSVACCOUNT:
			{
				CString accountName = line.readChars(line.readByte1());
				CString errorMsg = line.readString("");

				for (int i = 0; i < newPlayers.count(); i++)
				{
					CPlayer *player = (CPlayer *)newPlayers[i];

					if (player->accountName.comparei(accountName) == 0)
					{
						// The serverlist will return case sensitive account names.
						// This helps case sensitive file systems open/save the correct
						// acount.
						player->accountName = accountName;
						if (errorMsg == "SUCCESS")
						{
							player->sendAccount();
						}
						else
						{
							player->sendPacket(CPacket() << (char)DISMESSAGE << errorMsg);
							player->deleteMe = true;
						}

						break;
					}
				}

				break;
			}

			case GSVGUILD:
			{
				int playerId = line.readByte2();
				CPlayer *player = (CPlayer *)playerIds[playerId];

				if (player != NULL)
				{
					CString nick = line.readChars((unsigned char)line.readByte1());
					CString guild = nick.copy( nick.findl( '(' ) ).remove( ")" );

					if ( globalGuilds == false )
					{
						if ( globalGuildList.find( guild ) != -1 )
							player->setNick(nick, false);
					}
					else
						player->setNick(nick, false);
				}

				break;
			}

			case GSVPROFILE: /* Unsure if this works, temp */
			{
				CPacket profile;
				CPlayer *player1 = (CPlayer *)playerIds[line.readByte2()];
				CPlayer *player2 = findPlayerId(line.readChars(line.readByte1()));
				if (player1 == NULL || player2 == NULL)
					return;

				profile << (char)player2->accountName.length() << player2->accountName << line.readString("");

				int time = player2->onlineSecs;
				CString line2;
				//Online time
				line2 << toString((int)time/3600) << " hrs ";
				line2 << toString((int)(time/60)%60) << " mins ";
				line2 << toString((int)time%60) << " secs";
				profile << (char)line2.length() << line2;

				for (int i = 0; i < profileList.count(); i++)
				{
					CStringList a;
					a.load(profileList[i].text(), ":=");
					if (a[0].length() < 1)
						continue;

					CString n;

					if (a[1] == "playerkills")
						n = toString(player2->kills);
					else if (a[1] == "playerdeaths")
						n = toString(player2->deaths);
					else if (a[1] == "playerfullhearts")
					{
						if ( (float)(int)player2->maxPower == (float)player2->maxPower )
							n = toString((int)player2->maxPower);
						else
						{
							n = toString(player2->maxPower);
							n = n.copy( 0, n.length() - 1 );
						}
					}
					else if (a[1] == "playerrating")
						n = toString((int)player2->rating) << "/" << toString((int)player2->deviation);
					else if (a[1] == "playerap")
						n = toString(player2->ap);
					else if (a[1] == "playerrupees")
						n = toString(player2->rubins);
					else if (a[1] == "playerswordpower")
						n = toString(player2->swordPower);
					else if (a[1] == "canspin")
						n = (player2->status & 64 ? "true" : "false");
					else if (a[1] == "playerhearts")
					{
						if ( (float)(int)player2->power == (float)player2->power )
							n = toString((int)player2->power);
						else
						{
							n = toString(player2->power);
							n = n.copy( 0, n.length() - 1 );
						}
					}
					else if (a[1] == "playerdarts")
						n = toString(player2->darts);
					else if (a[1] == "playerbombs")
						n = toString(player2->bombs);
					else if (a[1] == "playermp")
						n = toString(player2->magicPoints);
					else if (a[1] == "playershieldpower")
						n = toString(player2->shieldPower);
					else if (a[1] == "playerglovepower")
						n = toString(player2->glovePower);
					else
					{
						for (int i = 0; i < player2->myFlags.count(); i++)
						{
							CStringList b;
							b.load(player2->myFlags[i].text(), "=");
							if (b[0] == a[1])
							{
								n = b[1];
								break;
							}
						}
					}

					profile << (char)(a[0].length() + n.length() + 2) << a[0] << ":=" << n;
				}

				player1->sendPacket(CPacket() << (char)DPROFILE << profile);
				break;
			}

			case GSVMSG:
				printf("[%s] %s\n", getTimeStr(1).text(), line.readString(""));
			break;

			case GSVFILESTART3:
			{
				unsigned char pTy = (unsigned char)line.readByte1();
				CString fileData, fileName = CString() << dataDir << "global" << fSep;
				switch (pTy)
				{
					case 0: // head
						fileName << "heads" << fSep;
					break;

					case 1: // body
						fileName << "bodies" << fSep;
					break;

					case 2: // sword
						fileName << "swords" << fSep;
					break;

					case 3: // shield
						fileName << "shields" << fSep;
					break;
				}
				fileName << line.readChars(line.readByte1());
				fileData.save(fileName.text());
				break;
			}

			case GSVFILEDATA3:
			{
				unsigned char pTy = (unsigned char)line.readByte1();
				CString fileData, fileName, newData, shortName;
				shortName = line.readChars(line.readByte1());
				fileName = CString() << dataDir << "global" << fSep;
				switch (pTy)
				{
					case 0: // head
						fileName << "heads" << fSep;
					break;

					case 1: // body
						fileName << "bodies" << fSep;
					break;

					case 2: // sword
						fileName << "swords" << fSep;
					break;

					case 3: // shield
						fileName << "shields" << fSep;
					break;
				}
				fileName << shortName.text();
				newData.writeBytes(line.readChars(line.bytesLeft()), line.bytesLeft());

				fileData.load(fileName.text());
				fileData << newData;
				fileData.save(fileName.text());
				break;
			}

			case GSVFILEEND3:
			{
				CPlayer *player = (CPlayer *)playerIds[line.readByte2()];
				int type = line.readByte1();
				char doCompress = line.readByte1();
				time_t modTime = line.readByte5();
				int fileLength = line.readByte5();
				CString shortName = line.readString("");
				CString fileName = CString() << dataDir << "global" << fSep;
				switch (type)
				{
					case 0: // head
						fileName << "heads" << fSep;
					break;

					case 1: // body
						fileName << "bodies" << fSep;
					break;

					case 2: // sword
						fileName << "swords" << fSep;
					break;

					case 3: // shield
						fileName << "shields" << fSep;
					break;
				}
				fileName << shortName.text();

				// If the file was sent compressed, we need to uncompress it.
				if (doCompress == 1)
				{
					// Open the file so we can uncompress it.
					CString fileData;
					fileData.load(fileName.text());

					// Uncompress the file.
					char* buffer = new char[fileLength];
					memset((void*)buffer, 0, fileLength);
					int cLen = fileLength;
					int error = uncompress((Bytef*)buffer,(uLongf*)&cLen,(const Bytef*)fileData.text(), fileData.length());
					if (error != Z_OK) printf("Failed to decompress file: %s\n", shortName.text());

					// Save the file now.
					fileData.clear();
					fileData.writeBytes(buffer, cLen);
					fileData.save(fileName.text());
					delete [] buffer;
				}

				// Set the file mod time.
				if (setFileModTime(fileName.text(), modTime) == false)
					printf("** [WARNING] Could not set modification time on file %s\n", shortName.text());

				if (player)
				{
					player->fileList.add(new COutFile(shortName, 0));
					switch (type)
					{
						case 0: // head
							player->headImage = shortName;
							player->updateProp(HEADGIF);
						break;

						case 1: // body
							player->bodyImage = shortName;
							player->updateProp(BODYIMG);
						break;

						case 2: // sword
							player->swordImage = shortName;
							player->updateProp(SWORDPOWER);
						break;

						case 3: // shield
							player->shieldImage = shortName;
							player->updateProp(SHIELDPOWER);
						break;
					}
				}
				break;
			}

			case GSVPING:
				// Sent every 60 seconds, do nothing.
			break;

			case GSVRAWDATA:
				nextIsRaw = true;
				rawPacketSize = line.readByte3();
			break;

			default:
				printf("[%s] Invalid List Server Message: %i\n", getTimeStr(1).text(), messageId);
			break;
		}
	}
}
示例#13
0
std::string LogMessage::getTimeStr()
{
    return getTimeStr(mtime);
}
示例#14
0
void ListServer_Main()
{
	if ( listServerFields[5] == "localhost" ) return;
    if (!lsConnected) return;

	CBuffer receiveBuff;
	if (listServer.receiveBytes(receiveBuff, 65536) < 0)
	{
		errorOut("serverlog.txt", "Disconnected from list server.");
		lsConnected = false;
		return;
	}

	CStringList lines;
	lines.load(receiveBuff.text(), "\n");
	for (int i = 0; i < lines.count(); i++)
	{
		CPacket line = CPacket() << lines[i];
		int messageId = line.readByte1();

		switch (messageId)
		{
			case GSVOLD:
			{
				printf("[%s] SERVER VERSION CHECK - Current: %i, Latest: %i - Old version, please upgrade.\n", getTimeStr(1).text(), GSERVER_BUILD, line.readByte2());
				break;
			}

			case GSVCURRENT:
			{
				printf("[%s] SERVER VERSION CHECK - Current: %i, Latest: %i - You are up to date :)\n", getTimeStr(1).text(), GSERVER_BUILD, GSERVER_BUILD);
				break;
			}

			case GSVACCOUNT:
			{
				CString accountName = line.readChars(line.readByte1());
				CString errorMsg = line.readString("");

				for (int i = 0; i < newPlayers.count(); i++)
				{
					CPlayer *player = (CPlayer *)newPlayers[i];

					if (player->accountName == accountName)
					{
						if (errorMsg == "SUCCESS")
						{
							player->sendAccount();
						}
						else
						{
							player->sendPacket(CPacket() << (char)DISMESSAGE << errorMsg);
							player->deleteMe = true;
						}

						break;
					}
				}

				break;
			}

			case GSVGUILD:
			{
				int playerId = line.readByte2();
				CPlayer *player = (CPlayer *)playerIds[playerId];

				if (player != NULL)
				{
					CString nick = line.readChars((unsigned char)line.readByte1());
					CString guild = nick.copy( nick.findl( '(' ) ).remove( ")" );

					if ( globalGuilds == false )
					{
						if ( globalGuildList.find( guild ) != -1 )
							player->setNick(nick, false);
					}
					else
						player->setNick(nick, false);
				}

				break;
			}

			case GSVFILEC:
			{
				CString fileData, fileName = CString() << dataDir << "global" << fSep << line.readChars(line.readByte1());
				fileData.save(fileName.text());

				break;
			}

			case GSVFILED:
			{
				CString fileName = line.readChars(line.readByte1());
				CPlayer *player = (CPlayer *)playerIds[line.readByte2()];

				switch (line.readByte1())
				{
					case 0: // head
						player->headImage = fileName;
						player->updateProp(HEADGIF);
					break;

					case 1: // body
						player->bodyImage = fileName;
						player->updateProp(BODYIMG);
					break;

					case 2: // sword
						player->swordImage = fileName;
						player->updateProp(SWORDPOWER);
					break;

					case 3: // shield
						player->shieldImage = fileName;
						player->updateProp(SHIELDPOWER);
					break;
				}

				break;
			}

			case GSVFILES:
			{
				CString fileData, fileName, newData, shortName;
				shortName = line.readChars(line.readByte1());
				int pos = shortName.find("Revision");

				if (pos >= 0)
				{
					#ifdef WIN32
						fileName = CString() << "GServer-NEW.exe";
					#else
						fileName = CString() << "GServer-NEW";
					#endif
					newData = line.readString("");
				}
				else
				{
					fileName = CString() << dataDir << "global" << fSep << shortName.text();
					newData = line.readString("");
				}

				fileData.load(fileName.text());
				fileData << newData.B64_Decode();
				fileData.save(fileName.text());

				break;
			}

			case GSVPROFILE: /* Unsure if this works, temp */
			{
				CPacket profile;
				CPlayer *player1 = (CPlayer *)playerIds[line.readByte2()];
				CPlayer *player2 = findPlayerId(line.readChars(line.readByte1()));
				if (player1 == NULL || player2 == NULL)
					return;

				profile << (char)player2->accountName.length() << player2->accountName << line.readString("");

				int time = player2->onlineSecs;
				CString line2;
				//Online time
				line2 << toString((int)time/3600) << " hrs ";
				line2 << toString((int)(time/60)%60) << " mins ";
				line2 << toString((int)time%60) << " secs";
				profile << (char)line2.length() << line2;

				for (int i = 0; i < profileList.count(); i++)
				{
					CStringList a;
					a.load(profileList[i].text(), ":=");
					if (a[0].length() < 1)
						continue;

					CString n;

					if (a[1] == "playerkills")
						n = toString(player2->kills);
					else if (a[1] == "playerdeaths")
						n = toString(player2->deaths);
					else if (a[1] == "playerfullhearts")
					{
						if ( (float)(int)player2->maxPower == (float)player2->maxPower )
							n = toString((int)player2->maxPower);
						else
						{
							n = toString(player2->maxPower);
							n = n.copy( 0, n.length() - 1 );
						}
					}
					else if (a[1] == "playerrating")
						n = toString((int)player2->rating) << "/" << toString((int)player2->deviation);
					else if (a[1] == "playerap")
						n = toString(player2->ap);
					else if (a[1] == "playerrupees")
						n = toString(player2->rubins);
					else if (a[1] == "playerswordpower")
						n = toString(player2->swordPower);
					else if (a[1] == "canspin")
						n = (player2->status & 64 ? "true" : "false");
					else if (a[1] == "playerhearts")
					{
						if ( (float)(int)player2->power == (float)player2->power )
							n = toString((int)player2->power);
						else
						{
							n = toString(player2->power);
							n = n.copy( 0, n.length() - 1 );
						}
					}
					else if (a[1] == "playerdarts")
						n = toString(player2->darts);
					else if (a[1] == "playerbombs")
						n = toString(player2->bombs);
					else if (a[1] == "playermp")
						n = toString(player2->magicPoints);
					else if (a[1] == "playershieldpower")
						n = toString(player2->shieldPower);
					else if (a[1] == "playerglovepower")
						n = toString(player2->glovePower);
					else
					{
						for (int i = 0; i < player2->myFlags.count(); i++)
						{
							CStringList b;
							b.load(player2->myFlags[i].text(), "=");
							if (b[0] == a[1])
							{
								n = b[1];
								break;
							}
						}
					}

					profile << (char)(a[0].length() + n.length() + 2) << a[0] << ":=" << n;
				}

				player1->sendPacket(CPacket() << (char)DPROFILE << profile);

				break;
			}

			case GSVMSG:
				printf("[%s] %s\n", getTimeStr(1).text(), line.readString(""));
			break;

			case GSVPING:
				// Sent every 60 seconds, do nothing.
			break;

			default:
				printf("[%s] Invalid List Server Message: %i\n", getTimeStr(1).text(), messageId);
			break;
		}
	}
}
示例#15
0
文件: debug.c 项目: GwennG/opendias
void i_o_log(const char *file, const int line, const int verbosity, const char *message, va_list inargs) {

  FILE *fp;
  char *logFile;

	va_list ap;
	va_copy(ap,inargs);

  if( trigger_log_verbosity( verbosity ) ) {

    char *thumb;
    if( VERBOSITY >= DEBUGM ) { 
      thumb = o_strdup("%s:%X:%s:%s:%d ");
    }
    else {
      thumb = o_strdup("%s:%X:%s ");
    }
    char *ltime = getTimeStr();
    char *vb;
    if(verbosity == 1) {
      vb = o_strdup("ERR");
    }
    else if(verbosity == 2) {
      vb = o_strdup("WRN");
    }
    else if(verbosity == 3) {
      vb = o_strdup("INF");
    }
    else if(verbosity == 4) {
      vb = o_strdup("DBG");
    }
    else if(verbosity == 5) {
      vb = o_strdup("SQL");
    }
    else 
      vb = o_strdup("---");

    if( message == strstr(message,"|") ) {
      vprintf((char *)message+1,inargs);
      printf("\n");
      //need to reset inargs to saved ap. reason vprintf function do not do so.
      va_end(inargs);
      va_copy(inargs,ap);
    }

    // Output to file
    if( LOG_DIR ) {
      logFile = o_printf("%s/opendias.log", LOG_DIR);
    }
    else {
      logFile = o_printf("%s/log/opendias/opendias.log", VAR_DIR);
    }
    if((fp = fopen(logFile, "a"))==NULL) {
      fprintf(stderr,"Cannot open log file %s.\n",logFile);
      exit(1);
    }

    // if the apps debug level at DEBUGM or TRACE, then include
    // __FILE__ and __LINE__ detail in the log entry.
    if( VERBOSITY >= DEBUGM ) { 
      fprintf(fp,thumb,ltime,pthread_self(),vb,file,line);
    }
    else {
      fprintf(fp,thumb,ltime,pthread_self(),vb);
    }
    vfprintf(fp,message,inargs);
    fprintf(fp,"\n");

    fclose(fp);

    free(logFile);
    free(ltime);
    free(thumb);
    free(vb);
  }

}
示例#16
0
/**
 * @brief bisystemControl
 * Initiates the bilateral control between master and slave systems
 * @param allSys Vector of pointers to the instantiated DXMotorSystem object pointers
 * @param runFlag Boolean run flag, continues the bilateral control while true - passed by reference to allow changes at runtime
 * @param goalTorqueSetting Desired torque settings to be used (parameters defined as macro in header) - passed by reference to allow modifications at runtime
 * @param filename Prefix filename where recorded position data is saved to
 */
void bisystemControl(vector<DXMotorSystem*>& allSys, bool& runFlag, int& goalTorqueSetting, const string& filename)
{
    try {

        DXMotorSystem dmaster = *(allSys[0]);
        unsigned int numMotors = dmaster.getNumMotors();
        dmaster.setAllTorqueEn(0);
        vector<int> allMasterTorqueLimit(numMotors,MASTER_TORQUE);
        dmaster.setAllTorqueLimit(allMasterTorqueLimit);

        // Check that all systems have the same motor count
        for (unsigned int ii = 1; ii < allSys.size(); ii++)
        {
            if (allSys[ii]->getNumMotors() != numMotors)
                throw(runtime_error("Master and slave motor count do not tally."));
            vector<int> allSlaveTorqueLimit(numMotors, SLAVE_TORQUE);
            allSys[ii]->setAllTorqueLimit(allSlaveTorqueLimit);
        }

        vector<int> posWrite = dmaster.getAllHomePosition(); //dmaster.getAllPosition();
        string writeFilename  = "data/" + filename + getTimeStr() + ".csv";
        ofstream file (writeFilename);

        ostringstream header;
        header << "timestep";
        for (unsigned int ii = 0; ii < numMotors; ii++)
        {
            header << ",#" << ii;
        }
        file << header.str() << endl;

        int torqueSetting = 0;
        vector<int> lowTorques(numMotors,MASTER_LOW_TORQUE);
        vector<int> highTorques(numMotors,MASTER_HIGH_TORQUE);

        vector<queue<vector<int> > > allPosHistory;
        for (unsigned int ii = 0; ii < allSys.size(); ii++)
        {
            queue<vector<int> > posHistory;
            allPosHistory.push_back(posHistory);
        }


        int timestep = 0;
        while(runFlag)
        {
            thread write(write2file, ref(file), ref(posWrite), timestep);

            // Change torque settings of master
            if (torqueSetting != goalTorqueSetting)
            {
                switch(goalTorqueSetting)
                {
                case 1:
                    dmaster.setAllTorqueLimit(lowTorques);
                    dmaster.setAllTorqueEn(1);
                    break;
                case 2:
                    dmaster.setAllTorqueLimit(highTorques);
                    dmaster.setAllTorqueEn(1);
                    break;
                case 0:
                default:
                    dmaster.setAllTorqueLimit(allMasterTorqueLimit);
                    dmaster.setAllTorqueEn(0);
                    break;
                }
                torqueSetting = goalTorqueSetting;
            }

            vector<int> pos = dmaster.getAllPosition();

            thread thr[allSys.size()-1];
            for (unsigned int ii = 0; ii < allSys.size()-1; ii++)
            {
                thr[ii] = thread(setPositions,ref(*(allSys[ii+1])),ref(pos));

//                allSys[ii+1]->setAllPosition(pos);
//                allSys[ii+1]->getAllPosition();
            }
            posWrite = pos; // position data to write (in next time step)

            write.join();
            for (unsigned int ii = 0; ii < allSys.size()-1; ii++)
            {
                thr[ii].join();
            }
            timestep++;
        }

        file.close();
        // Delete pointers
        for (unsigned int nn = 0; nn < allSys.size(); nn++)
        {
            allSys[nn]->setAllTorqueLimit(vector<int>(numMotors,1023));
            allSys[nn]->setAllTorqueEn(0);
            delete allSys[nn];
        }

    } catch(runtime_error e) {
        cout << e.what() << endl;
    }
}
示例#17
0
/* Never was great formulating =P */
bool CWordFilter::apply(CPlayer *pPlayer, CBuffer &pBuffer, int pCheck)
{
	bool logsave = false, rctell = false;
	CBuffer start;
	CStringList found;
	int pos = 0, wc = 0;

	for (int i = 0; i < WordList.count(); i++)
	{
		WordMatch *word = (WordMatch *)WordList[i];
		if (!word->check[pCheck])
			continue;

		for (int j = 0; j < pBuffer.length(); j++)
		{
			for (int k = 0; k < word->match.length(); k++)
			{
				char c1 = pBuffer[j + k];
				char c2 = word->match[k];
				if (c2 != '?' && (isUpper(c2) && c2 != c1) || (isLower(c2) && toLower(c2) != toLower(c1)))
				{
					if (wc >= word->precision)
					{
						found.add(start);

						for (int l = 0; l < (int)sizeof(word->action); l++)
						{
							if (!word->action[l])
								continue;

							switch (l)
							{
								case FILTERA_LOG:
									if (logsave)
										break;

									logsave = true;
									if (pPlayer != NULL)
										errorOut("wordfilter.txt", CBuffer() << pPlayer->accountName << " has used rude words while chatting: " << start);
								break;

								case FILTERA_REPLACE:
									pos = pBuffer.find(' ', j);
									pos = (pos == -1 ? start.length() : pos-j+1);
									for (int m = 0; m < pos; m++)
										pBuffer.replace(j + m, '*');
								break;

								case FILTERA_TELLRC:
									if (rctell)
										break;

									rctell = true;
									if (pPlayer != NULL)
										sendRCPacket(CPacket() << (char)DRCLOG << pPlayer->accountName << " has used rude words while chatting: " << start);
								break;

								case FILTERA_WARN:
									pBuffer = (word->warnmessage.length() > 0 ? word->warnmessage : warnmessage);
								break;

								case FILTERA_JAIL: // kinda useless...?
								break;

								case FILTERA_BAN:
									if (pPlayer != NULL)
									{
										CBuffer pLog = CBuffer() << "\n" << getTimeStr(0) << "\n" << pPlayer->accountName << " has used rude words while chatting: " << start;
										pPlayer->setBan(pLog, true);
									}
								break;
							}
						}
					}

					start.clear();
					wc = 0;
					break;
				}

				start.writeChar(c1);
				wc++;
			}
		}
	}

	return (found.count() > 0);
}