END_TEST START_TEST(test_strSplit) { char *string; char **list; size_t size; string = strCreate(); strCopy(string, "foo bar hurz furz"); list = strSplit(" ", string, -1, &size); fail_unless(size == 4, NULL); fail_unless(strEquals(list[0], "foo"), NULL); fail_unless(strEquals(list[1], "bar"), NULL); fail_unless(strEquals(list[2], "hurz"), NULL); fail_unless(strEquals(list[3], "furz"), NULL); listFreeWithItems(list, &size); list = strSplit(" ", string, 0, &size); fail_unless(size == 0, NULL); listFreeWithItems(list, &size); list = strSplit(" ", string, 2, &size); fail_unless(size == 2, NULL); fail_unless(strEquals(list[0], "foo"), NULL); fail_unless(strEquals(list[1], "bar hurz furz"), NULL); listFreeWithItems(list, &size); strCopy(string, "foo bar hurz bar furz"); list = strSplit("bar", string, 3, &size); fail_unless(size == 3, NULL); fail_unless(strEquals(list[0], "foo "), NULL); fail_unless(strEquals(list[1], " hurz "), NULL); fail_unless(strEquals(list[2], " furz"), NULL); listFreeWithItems(list, &size); }
void VolumeOctreeBase::logDescription() const { const std::string description = getDescription(); std::vector<std::string> lines = strSplit(description, "\r\n"); if (lines.size() == 1) lines = strSplit(description, "\n"); for (size_t i=0; i<lines.size(); i++) LINFO(lines.at(i)); }
std::pair<seqan::CharString, int> getTargetPos(seqan::CharString const & str) { seqan::DirectionIterator<seqan::CharString const, seqan::Input>::Type inputIter = directionIterator(str, seqan::Input()); // Parse out key/value pairs and interpret SVLEN. seqan::CharString key, val; enum { IN_KEY, IN_VALUE } state = IN_KEY; for (; !atEnd(inputIter); ++inputIter) { if (*inputIter == '=') { state = IN_VALUE; continue; } else if (*inputIter == ';') { if (key == "TARGETPOS") { seqan::StringSet<seqan::CharString> xs; strSplit(xs, val, seqan::EqualsChar<':'>()); SEQAN_CHECK(length(xs) == 2u, "TARGETPOS has invalid format %s", toCString(val)); SEQAN_CHECK(!empty(xs[0]) && !empty(xs[1]), "TARGETPOS has invalid format %s", toCString(val)); return std::make_pair(xs[0], seqan::lexicalCast<int>(xs[1])); } clear(val); clear(key); state = IN_KEY; continue; } else if (state == IN_KEY) { appendValue(key, *inputIter); } else // (state == IN_VALUE) { appendValue(val, *inputIter); } } if (key == "TARGETPOS") { seqan::StringSet<seqan::CharString> xs; strSplit(xs, val, seqan::EqualsChar<':'>()); SEQAN_CHECK(length(xs) == 2u, "TARGETPOS has invalid format %s", toCString(val)); SEQAN_CHECK(!empty(xs[0]) && !empty(xs[1]), "TARGETPOS has invalid format %s", toCString(val)); return std::make_pair(xs[0], seqan::lexicalCast<int>(xs[1])); } SEQAN_FAIL("Missing INFO TARGETPOS %s", toCString(str)); return std::make_pair("", 0); }
// Append the transcript names for the given record. void _appendTranscriptNames(seqan::String<unsigned> & tIDs, // transcript ids to write out seqan::StringSet<seqan::CharString> & contigNames, seqan::NameStoreCache<seqan::StringSet<seqan::CharString> > & cache, MyGffRecord const & record) { clear(tIDs); seqan::CharString groupNames; for (unsigned i = 0; i < length(record.tagNames); ++i) if (record.tagNames[i] == options.gffGroupBy) groupNames = record.tagValues[i]; if (empty(groupNames)) return; // Record has no group names. // Write out the ids of the transcripts that the record belongs to as indices in contigNames. unsigned idx = 0; seqan::StringSet<seqan::CharString> ss; strSplit(ss, groupNames, seqan::EqualsChar<','>()); for (unsigned i = 0; i < length(ss); ++i) { if (empty(ss[i])) continue; if (!getIdByName(contigNames, ss[i], idx, cache)) { appendValue(tIDs, length(contigNames)); appendName(contigNames, ss[i], cache); } else { appendValue(tIDs, idx); } } }
bool PropertyMap::updateMapFromString(const std::string& values) { bool status = true; vector<string> valuesMap = strSplit(values, ","); for (size_t i = 0; i < valuesMap.size(); ++i) { vector<string> m = strSplit(valuesMap[i], "="); if (m.size() != 2) { cerr << __PRETTY_FUNCTION__ << ": unable to extract name=value pair from " << valuesMap[i] << endl; continue; } string name = trim(m[0]); string value = trim(m[1]); status = status && updatePropertyFromString(name, value); } return status; }
void adminCmdJump(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { if (strlen (args) == 0) { info("Jump without argument!"); // we must add a random with the map max x/y } else { char **arg; int argc; info("Jump with argument: %s", args); arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc != 3) { info("Wrong number of argument, must be 3."); } else { PositionXYZ position; position.x = atof(arg[0]); info("x = %.6f", position.x); position.y = atof(arg[1]); info("y = %.6f", position.y); position.z = atof(arg[2]); info("z = %.6f", position.z); session->game.commanderSession.currentCommander->pos = position; session->game.commanderSession.currentCommander->dir = PositionXZ_decl(0, 0); zoneBuilderSetPos(session->game.commanderSession.currentCommander->pcId, &position, replyMsg); } free(arg); } }
IntArray * strSplitAndConvert(char delimiter, char * str, int (* function)(const char * data)) { // Auxiliary array. DynArray * array = strSplit(delimiter, str); // Failed. if(array == NULL) { return NULL; } // Create an array. IntArray * result = iaCreate(); for(int i = 0; i < array -> length; i++) { char * tmp = daGetByIndex(array, i); iaPrepend(result, function(tmp)); } // Free the auxiliary array. daDestroy(array, &free); // All done. return result; }
void ProjectSplicedRoi::pushGff(seqan::GffRecord const & record) { if (verbosity >= 3) { std::cerr << "Pushing GFF record.\n "; writeRecord(std::cerr, const_cast<seqan::GffRecord &>(record), seqan::Gff()); } gffRecords.push_back(record); // Get string set of group names for the record. seqan::StringSet<seqan::CharString> groups; for (unsigned i = 0; i < length(record.tagNames); ++i) if (record.tagNames[i] == groupBy) { strSplit(groups, record.tagValues[i], seqan::EqualsChar<','>()); break; } gffGroups.push_back(groups); if (verbosity >= 3) { std::cerr << "Groups:"; for (unsigned i = 0; i < length(groups); ++i) std::cerr << " " << groups[i]; std::cerr << "\n"; } }
void CCommandLayer::updateSelectCity(CCity *data) { CCSprite *build = (CCSprite*)(m_comLayer->findWidgetById("build")); CCTexture2D *textTure = CCTextureCache::sharedTextureCache()->addImage(CCString::createWithFormat("command/%d.jpg",data->cityId*10+1)->getCString()); if (textTure) { build->setTexture(textTure); } CLabel *food = (CLabel*)(m_comLayer->findWidgetById("food")); food->setString(ToString(data->lvFood)); CLabel *heronum = (CLabel*)(m_comLayer->findWidgetById("heronum")); heronum->setString(CCString::createWithFormat("%d/%d",data->haveHeroNum,data->heroNum)->getCString()); CLabel *note1 = (CLabel*)(m_comLayer->findWidgetById("func1")); CLabel *note2 = (CLabel*)(m_comLayer->findWidgetById("func2")); CCArray *strArr = strSplit(data->note.c_str(),"|"); if (strArr->count()==1) { note1->setString(((CCString*)strArr->objectAtIndex(0))->getCString()); note2->setString(""); } else if (strArr->count()==2) { note1->setString(((CCString*)strArr->objectAtIndex(0))->getCString()); note2->setString(((CCString*)strArr->objectAtIndex(1))->getCString()); } CButton *command = (CButton*)(m_comLayer->findWidgetById("strengthen")); UserData *user = DataCenter::sharedData()->getUser()->getUserData(); if (data->cityId != m_commandData.cityInfo.cityId) { if (user->getRoleFood()>=data->lvFood&&data->level< m_commandData.cityInfo.level) { command->setEnabled(true); } else { command->setEnabled(false); } } else { if (user->getRoleFood()>=data->lvFood) { command->setEnabled(true); } else { command->setEnabled(false); } } }
Arc::Rect Arc::parseRect( const string& value ) { ArrayList<string> parts = strSplit(value, ',', 4); if (parts.size() < 4) return Rect::ZERO; return Rect(parseFloat(parts[0]), parseFloat(parts[1]), parseFloat(parts[2]), parseFloat(parts[3])); }
int main (int argc, char* argv[]) { char str[] = {"Every good boy does fine."}; char str2[30] = {"Every good boy does fine."}; char str3[30] = {""}; //Test Word Count int wordCount = strWordCount(str); printf("Word count: %d\n", wordCount); //end test word count // //Test str to upper. strToUpper(str, str2); printStringArray(str); printStringArray(str2); //end test str to upper. // //Test str Strip char c = 'o'; strStrip(str, c, str2); printStringArray(str); printStringArray(str2); //end test str Strip // //Test str Substring char d[] = {"boy"}; printf("Where does the word boy start? %d", strIsSubstring(str, d)); //end test str is Substring // //Test strSubstitute char e, g; e = 'g'; g = 'o'; strSubstitute(str, e, g, str2); printStringArray(str); printStringArray(str2); //end test strSubstitute // //Test strReverse strReverse(str, str2); printStringArray(str); printStringArray(str2); //Test Palindrome char tacocat[] = {"tacocat"}; printf("Is tacocat a Palindrome? %d", strPalindrome(tacocat)); //end palindrome test // //Test strSplit strSplit (str, 'o', 3, str3, str2); printf("The starting str\n"); printStringArray(str); printf("The second half of str\n"); printStringArray(str2); printf("The first half of str\n"); printStringArray(str3); }
void TextureSystem::loadTextures(std::vector<sf::Texture>& dest, const std::string& colonpaths) { std::vector<std::string> paths = strSplit(colonpaths, ":"); for(const std::string& s : paths) { sf::Texture t; t.loadFromFile(s); dest.push_back(std::move(t)); } }
Arc::Vector2 Arc::parseVector2( const string& value ) { ArrayList<string> parts = strSplit(value, ',', 2); if (parts.size() < 2) return Vector2::ZERO; return Vector2(parseFloat(parts[0]), parseFloat(parts[1])); }
Arc::Color Arc::parseColor( const string& value ) { ArrayList<string> parts = strSplit(value, ',', 4); if (parts.size() < 4) return Color::WHITE; return Color(parseInt(parts[0]), parseInt(parts[1]), parseInt(parts[2]), parseInt(parts[3])); }
Arc::Circle Arc::parseCircle( const string& value ) { ArrayList<string> parts = strSplit(value, ',', 3); if (parts.size() < 3) return Circle::ZERO; return Circle(parseFloat(parts[0]), parseFloat(parts[1]), parseFloat(parts[2])); }
char* initialize ( char* cmdline ) { // Get comnmand line std::string str = cmdline; std::vector<std::string> args; while ( str.length() > 0) { args.push_back ( strSplit ( str, " " ) ); } fileName = ""; for (int n=0; n < args.size(); n++ ) { if ( args[n].compare ( "-f" ) == 0 ) { startFrame = strToI ( args[n+1] ); } if ( args[n].compare ( "-d" ) == 0 ) { // max_draw maxDraw = strToI ( args[n+1] ); } if ( args[n].find_first_of ( "." ) != std::string::npos ) { fileName = args[n]; } } if ( fileName.length()== 0 || args.size()==0 ) { app_printf ( "USAGE: state_view [-f #] [-d #] filename.raw\n\n" ); app_printf ( " -f # Start at frame \n" ); app_printf ( " -d # Maximum number of draw calls to read \n" ); _getch(); exit(-1); } for (int n=0; n < 10; n++ ) bShow[n] = true; // Initialize camera cam.setPos ( 0, 0, 1 ); cam.setToPos ( -window_width*3/8, -window_height*3/8, 1 ); cam.updateMatricies (); // Initialize bin and call names setup_bins (); // Load trace file char fname[256]; strcpy ( fname, fileName.c_str() ); load_trace_raw ( fname ); // required init functions init2D ( "arial_12" ); // specify font file (.bin/tga) setText ( 1.0, -0.5 ); // scale by 0.5, kerning adjust -0.5 pixels setview2D ( window_width, window_height ); // draw visualization layer drawMatrix (); PERF_INIT ( false ); // Enable CPU perf (do not require nv-perfmarker DLL) PERF_SET ( false, 2, false, "" ); // Perf CPU?, CPU level, NV Perfmarkers, Log filename return "NVIDIA State Viewer, by Rama Hoetzlein"; // Return Window title }
int parseScalarArray(liScalarVec &v, const gkString& str, const gkString& delims) { if (str.empty()) return 0; liStrVec sv = strSplit(str, delims); v.clear(); v.reserve(sv.size()); for (size_t i = 0; i < sv.size(); i++) v.push_back(Ogre::StringConverter::parseReal(sv[i])); return v.size(); }
CoordinationManager::CoordinationManager() { ////////////////////////////// //(이미지 id enum값 = key, 이미지 id = value)맵을 초기화 imageNameData[IMAGE_BACKGROUND] = "IMAGE_BACKGROUND"; imageNameData[IMAGE_MAIN_BACKGROUND] = "IMAGE_MAIN_BACKGROUND"; imageNameData[IMAGE_BACKGROUND_TABLE] = "IMAGE_BACKGROUND_TABLE"; imageNameData[IMAGE_VERTICALLY_START_BUTTON] ="IMAGE_VERTICALLY_START_BUTTON"; imageNameData[IMAGE_VERTICALLY_TUTORIAL_BUTTON] ="IMAGE_VERTICALLY_TUTORIAL_BUTTON"; imageNameData[IMAGE_TITLE] = "IMAGE_TITLE"; imageNameData[IMAGE_TUTORIAL] = "IMAGE_TUTORIAL"; imageNameData[IMAGE_BACK_BOUTTON] = "IMAGE_BACK_BOUTTON"; imageNameData[IMAGE_HAND] = "IMAGE_HAND"; imageNameData[IMAGE_BLOCK] = "IMAGE_BLOCK"; imageNameData[IMAGE_ACCURACY] = "IMAGE_ACCURACY"; imageNameData[IMAGE_SCORE] = "IMAGE_SCORE"; imageNameData[IMAGE_SCORENUMBER] = "IMAGE_SCORENUMBER"; imageNameData[IMAGE_TIMEBAR] = "IMAGE_TIMEBAR"; imageNameData[IMAGE_GAMEOVER] = "IMAGE_GAMEOVER"; imageNameData[IMAGE_HORIZONTAL_BUTTON] = "IMAGE_HORIZONTAL_BUTTON"; imageNameData[IMAGE_RESULT_WINDOW] = "IMAGE_RESULT_WINDOW"; imageNameData[LABLE_NAME] = "LABLE_NAME"; imageNameData[LABLE_BLOCKS] = "LABLE_BLOCKS"; imageNameData[LABLE_SCORE] = "LABLE_SCORE"; imageNameData[LABLE_FIRST_NAME] = "LABLE_FIRST_NAME"; imageNameData[LABLE_SECOND_NAME] = "LABLE_SECOND_NAME"; imageNameData[LABLE_THIRD_NAME] = "LABLE_THIRD_NAME"; imageNameData[LABLE_FOURTH_NAME] = "LABLE_FOURTH_NAME"; imageNameData[LABLE_FIFTH_NAME] = "LABLE_FIFTH_NAME"; imageNameData[LABLE_FIRST_BLOCKS] = "LABLE_FIRST_BLOCKS"; imageNameData[LABLE_SECOND_BLOCKS] = "LABLE_SECOND_BLOCKS"; imageNameData[LABLE_THIRD_BLOCKS] = "LABLE_THIRD_BLOCKS"; imageNameData[LABLE_FOURTH_BLOCKS] = "LABLE_FOURTH_BLOCKS"; imageNameData[LABLE_FIFTH_BLOCKS] = "LABLE_FIFTH_BLOCKS"; imageNameData[LABLE_FIRST_SCORE] = "LABLE_FIRST_SCORE"; imageNameData[LABLE_SECOND_SCORE] = "LABLE_SECOND_SCORE"; imageNameData[LABLE_THIRD_SCORE] = "LABLE_THIRD_SCORE"; imageNameData[LABLE_FOURTH_SCORE] = "LABLE_FOURTH_SCORE"; imageNameData[LABLE_FIFTH_SCORE] = "LABLE_FIFTH_SCORE"; ////////////////////////////// //파일의 데이터를 읽어 온다 std::string fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("coordinationdata.txt"); unsigned char* pBuffer = NULL; unsigned long bufferSize = 0; pBuffer = CCFileUtils::sharedFileUtils()->getFileData(fullPath.c_str(), "r", &bufferSize); char pzxBuf[256]; CCString* tempstr = CCString::createWithData(pBuffer, bufferSize); fullStr = tempstr->getCString(); strSplit(); //slpit함수로 쪼개 (이미지 id = key, 좌표 구조체 = value)맵에 저장 }
int CTextExtractor::imageToString(const string &imgSrc, vector<TextPatch> &ret) { vector<Mat> imgPatch; vector<string> imgList, txtList; string curLine; int curVal, i, j, avg = 0, cnt = 0; char buff[MAX_BUFF]; if (!det->textDetect(imgSrc, imgPatch)) { fprintf(stderr, "Fail to detect text from imag %s!\n", imgSrc.c_str()); return -1; } ret.clear(); string fname = getFileName(imgSrc); for (i = 0; i < imgPatch.size(); ++i) { if (!ocr->init()) { fprintf(stderr, "OCREngine init failure!\n"); continue; } sprintf(buff, "%s_rslt_%d.jpg", fname.c_str(), i); imgList.push_back(string(buff)); imwrite(buff, imgPatch[i]); curVal = ocr->getTextLine(imgList.back(), curLine); strSplit(curLine, '\n', txtList); //printf("size = %d\n", txtList.size()); for (j = 0; j < txtList.size(); ++j) { if (txtList[j].length() > 5 && curVal >= LIM_CONF) { ret.push_back(make_pair(txtList[j], curVal)); avg += curVal; ++cnt; } } /* if (curLine.length() > 5 && curVal >= LIM_CONF) { ret.push_back(make_pair(curLine, curVal)); avg += curVal; } */ //showResult(imgPatch[i], curLine, curVal); } for (i = 0; i < imgList.size(); ++i) { remove(imgList[i].c_str()); } return ret.size() == 0 ? -1 : avg / ret.size(); }
void FileEntry::ParseSkip(const char *skip) { vector<char*> items; PositionEntry entry; strSplit(&items, skip, ", "); for (int i = 0;i < items.size(); i += 2) { entry.start_time = atoi(items[i]); entry.duration = atoi(items[i+1]); if (entry.start_time > 0 && entry.duration > 0) { skip_list.push_back(entry); } } while (items.size() > 0) { lmbox_free(items.back()); items.pop_back(); } }
void adminCmdChangeCamera(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { const uint16_t MAX_LEN = 128; char message[MAX_LEN]; PositionXYZ pos; float fspd; float ispd; info("Change Camera command used, args = %s", args); if (strlen (args) == 0) { pos.x = 0; pos.y = 0; pos.z = 0; zoneBuilderChangeCamera(0, &pos, 0.0f, 0.0f, replyMsg); } else { char **arg; int argc; arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc >= 3) { pos.x = (strlen(arg[0]) == 1 && arg[0][0] == 'c') ? session->game.commanderSession.currentCommander->pos.x : atof(arg[0]); pos.y = (strlen(arg[1]) == 1 && arg[1][0] == 'c') ? session->game.commanderSession.currentCommander->pos.y : atof(arg[1]); pos.z = (strlen(arg[2]) == 1 && arg[2][0] == 'c') ? session->game.commanderSession.currentCommander->pos.z : atof(arg[2]); } if (argc == 3) zoneBuilderChangeCamera(1, &pos, 10.0f, 0.7f, replyMsg); else if (argc == 5) { fspd = atof(arg[3]); ispd = atof(arg[4]); zoneBuilderChangeCamera(1, &pos, fspd, ispd, replyMsg); } else { snprintf(message, sizeof(message), "Bad usage /changeCamera <x> <y> <z> {<fspd> <ispd>}"); zoneBuilderChat(session->game.commanderSession.currentCommander, message, replyMsg); } free(arg); } }
std::vector<VolumeReader*> VolumeSerializer::getReaders(const std::string& url) const throw (tgt::UnsupportedFormatException) { if (url.empty()) return readers_; VolumeURL origin(url); // check if a reader for the URL's resource type is available std::string protocol = origin.getProtocol(); if (!protocol.empty()) { if (readersProtocolMap_.find(protocol) != readersProtocolMap_.end()) return readersProtocolMap_.find(protocol)->second; else throw tgt::UnsupportedFormatException(protocol, url); } // check if a reader for the filename is available std::string filename = tgt::FileSystem::fileName(origin.getPath()); if (readersFilenameMap_.find(filename) != readersFilenameMap_.end()) return readersFilenameMap_.find(filename)->second; // check if a reader for the filename extension is available std::string extension = tgt::FileSystem::fileExtension(origin.getPath(), true); // construct extension also from last two filename components, e.g. ome.tiff std::string doubleExtension; std::vector<std::string> filenameSplit = strSplit(origin.getFilename(), "."); if (filenameSplit.size() > 2) doubleExtension = filenameSplit.at(filenameSplit.size()-2) + "." + filenameSplit.at(filenameSplit.size()-1); if (readersExtensionMap_.find(doubleExtension) != readersExtensionMap_.end()) //< prefer double extension over single extension return readersExtensionMap_.find(doubleExtension)->second; if (readersExtensionMap_.find(extension) != readersExtensionMap_.end()) return readersExtensionMap_.find(extension)->second; else throw tgt::UnsupportedFormatException(extension, url); }
void adminCmdSetLevel(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { if (strlen (args) == 0) { info("Set level needs a argument!"); } else { char **arg; int argc; info("Set level with argument: %s", args); arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc != 1) { info("Wrong number of arguments, must be 1."); } else { CommanderLevel_t level = atoi(arg[0]); info("Setting level to %d.", level); session->game.commanderSession.currentCommander->level = level; zoneBuilderPCLevelUp(session->game.commanderSession.currentCommander->pcId, level, replyMsg); } free(arg); } }
void MyService::onRecvMsg(sigverse::RecvMsgEvent &evt) { string sender = evt.getSender(); string msg = evt.getMsg(); strSplit(msg, ":"); if (sender == "man_0"){ if (msg == "Start"){ start = true; } else if (headStr == "Question") { this->string2double(bodyStr); cout << "Question index is " << question_index << endl; } else if (headStr == "NEXT") { this->sendMsgToCtr("man_0", "go"); } } else if (sender == "sigverse_DB"){ if (msg == "あり") { cout << "同じ質問をします" << endl; this->sendMsgToCtr("man_0", "roop"); } else if (msg == "なし") { cout << "次の質問をします" << endl; this->sendMsgToCtr("man_0", "inc"); question_counter++; cout << question_counter << endl; if (question_counter > question_index - 1) { cout << "これ以上質問がないので次の物体に切り替えます" << endl; this->sendMsgToCtr("man_0", "fin"); obj_counter++; question_counter = 0; } } } }
void adminCmdSetJobPoints(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { if (strlen (args) == 0) { info("Set job points needs a argument!"); } else { char **arg; int argc; info("Set job points with argument: %s", args); arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc != 2) { info("Wrong number of arguments, must be 2."); } else { CommanderJobId_t jobId = atoi(arg[0]); uint16_t points = atoi(arg[1]); info("Setting job %d, points to to %d.", jobId, points); zoneBuilderJobPoints(jobId, points, replyMsg); } free(arg); } }
void adminCmdSetStamina(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { if (strlen (args) == 0) { info("Set stamina needs a argument!"); } else { char **arg; int argc; info("Set stamina with argument: %s", args); arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc != 1) { info("Wrong number of arguments, must be 1."); } else { Stamina_t stamina = atoi(arg[0]) * 1000; info("Setting stamina to %d.", stamina); session->game.commanderSession.currentCommander->currentStamina = stamina; zoneBuilderStamina(stamina, replyMsg); } free(arg); } }
void load_trace_txt ( char* fname ) { std::string str, word; char buf[1024]; unsigned long totalBytes = getFileSize ( fname ); unsigned long currBytes = 0; FILE* fp = fopen ( fname, "rt" ); int c; std::vector<std::string> changestates; changestates.push_back ( "x" ); // 0 = BIN_NOTUSED changestates.push_back ( "c" ); // 1 = BIN_CREATE changestates.push_back ( "u" ); // 2 = BIN_CHANGE changestates.push_back ( "s" ); // 3 = BIN_SWITCH changestates.push_back ( "-" ); // 4 = BIN_REUSE changestates.push_back ( "D" ); Call cl; Event e; int lin = 0; int max_lin = 5000; std::string szstr; int sz; unsigned long cstart = 0; int cnum = 0; while (!feof(fp) && lin < max_lin) { currBytes = getFilePos ( fp ); printf ( "%d (%.2f%%)\n", currBytes, currBytes*100.0f/totalBytes ); fgets ( buf, 1024, fp ); str = buf; int bin = 0; str = strTrim ( str ); e.name = word; if ( str.compare (0, 2, "C:") == 0 ) { /*word = strSplit ( str, " " ); word = strSplit ( str, " " ); cl.bin_id = strToI(word); word = strSplit ( str, " " ); cl.size = strToI(word); word = strSplit ( str, " " ); cl.obj_id = strToLI(word); word = strSplit ( str, " " ); cl.val_id = strToLI(word); word = strSplit ( str, " " ); cl.name = word; mCalls.push_back ( cl );*/ cnum++; } else if ( str.compare ( 0, 2, "FR" ) == 0 ) { e.count = 1; for (int n=0; n < NUM_BIN; n++ ) { e.bin_id[n] = -1; e.bin_change[n] = -1; } mEvents.push_back ( e ); } else if ( str.compare ( 0, 2, "Dr" ) == 0 ) { e.count = 1; int bin = 0; word = strLeft ( str, 8 ); str = strTrim ( str ); while ( str.length() > 0 ) { word = strSplit ( str, " " ); c = strExtract ( word, changestates ); szstr = strParse ( word, "[", "]" ); e.bin_id[bin] = strToI ( word ); e.bin_change[bin] = c; e.bin_size[bin] = strToI ( szstr ); bin++; } e.call_start = cstart; e.call_num = cnum; if ( e.bin_size[BIN_DRAW] > mMaxSize ) mMaxSize = e.bin_size[BIN_DRAW]; mEvents.push_back ( e ); cstart += cnum; } lin++; } fclose ( fp ); }
void adminCmdSpawnPc(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { // add a fake commander with a fake account CommanderInfo fakePc; commanderInfoInit(&fakePc); fakePc.pos = session->game.commanderSession.currentCommander.info.pos; fakePc.appearance.accountId = r1emuGenerateRandom64(&self->seed); fakePc.socialInfoId = r1emuGenerateRandom64(&self->seed); fakePc.pcId = r1emuGenerateRandom(&self->seed); fakePc.commanderId = r1emuGenerateRandom64(&self->seed); snprintf(fakePc.appearance.familyName, sizeof(fakePc.appearance.familyName), "PcID_%x", fakePc.pcId); snprintf(fakePc.appearance.commanderName, sizeof(fakePc.appearance.commanderName), "AccountID_%llx", fakePc.appearance.accountId); // register the fake socket session SocketSession fakeSocketSession; uint32_t sessionKey = r1emuGenerateRandom(&self->seed); uint8_t sessionKeyStr[SOCKET_SESSION_ID_SIZE]; socketSessionGenSessionKey((uint8_t *)&sessionKey, sessionKeyStr); sprintf(sessionKeyStr, "%.08x", sessionKey); socketSessionInit(&fakeSocketSession, fakePc.appearance.accountId, self->info.routerId, session->socket.mapId, sessionKeyStr, true); RedisSocketSessionKey socketKey = { .routerId = self->info.routerId, .sessionKey = sessionKeyStr }; redisUpdateSocketSession(self->redis, &socketKey, &fakeSocketSession); // register the fake game session GameSession fakeGameSession; gameSessionInit(&fakeGameSession, &fakePc); accountSessionInit(&fakeGameSession.accountSession, "DummyPC", sessionKeyStr, ACCOUNT_SESSION_PRIVILEGES_ADMIN); RedisGameSessionKey gameKey = { .routerId = fakeSocketSession.routerId, .mapId = fakeSocketSession.mapId, .accountId = fakeSocketSession.accountId }; redisUpdateGameSession(self->redis, &gameKey, sessionKeyStr, &fakeGameSession); info("Fake PC spawned.(SocketID=%s, SocialID=%I64x, AccID=%I64x, PcID=%x, CommID=%I64x)", sessionKeyStr, fakePc.socialInfoId, fakePc.appearance.accountId, fakePc.pcId, fakePc.commanderId); GameEventEnterPc event = { .updatePosEvent = { .mapId = fakeSocketSession.mapId, .info = fakePc } }; workerDispatchEvent(self, sessionKeyStr, EVENT_TYPE_ENTER_PC, &event, sizeof(event)); } void adminCmdAddItem(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { uint32_t itemId = strtol(args, &args, 10); args++; uint32_t amount = strtol(args, &args, 10); uint32_t itemPosition = 1; ItemPkt item = { .uniqueId = r1emuGenerateRandom64(&self->seed), .amount = (!amount) ? 1 : amount, .inventoryIndex = INVENTORY_CAT_SIZE * INVENTORY_CAT_CONSUMABLE + itemPosition, .id = itemId }; zoneBuilderItemAdd(&item, INVENTORY_ADD_PICKUP, replyMsg); } void adminCmdJump(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { if (strlen (args) == 0) { info("Jump without argument!"); // we must add a random with the map max x/y } else { char **arg; int argc; info("Jump with argument: %s", args); arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc != 3) { info("Wrong number of argument, must be 3."); } else { PositionXYZ position; position.x = atof(arg[0]); info("x = %.6f", position.x); position.y = atof(arg[1]); info("y = %.6f", position.y); position.z = atof(arg[2]); info("z = %.6f", position.z); session->game.commanderSession.currentCommander.info.pos = position; zoneBuilderSetPos(session->game.commanderSession.currentCommander.info.pcId, &position, replyMsg); } free(arg); } } void adminCmdTest(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { info("Test command launched."); size_t memSize; void *memory = dumpToMem( "[03:12:32][main.c:30 in writePacketToFile] E9 0C 73 2A 86 02 35 00 A2 4E 00 00 02 01 05 00 | ..s*..5..N......\n" "[03:12:32][main.c:30 in writePacketToFile] 4E 61 6D 65 00 0C 00 44 61 72 6B 48 6F 72 69 7A | Name...DarkHoriz\n" "[03:12:32][main.c:30 in writePacketToFile] 6F 6E 00 04 00 57 68 6F 00 0A 00 4C 6F 74 68 62 | on...Who...Lothb\n" "[03:12:32][main.c:30 in writePacketToFile] 72 6F 6F 6B 00 | rook." , NULL, &memSize ); zmsg_add(replyMsg, zframe_new(memory, memSize)); } void adminCmdWhere(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { const uint16_t MAX_LEN = 128; char message[MAX_LEN]; PositionXYZ position; position = session->game.commanderSession.currentCommander.info.pos; snprintf(message, sizeof(message), "[%hu] x = %.0f, y = %.0f, z = %.0f", session->game.commanderSession.mapId, position.x, position.y, position.z); zoneBuilderChat(&session->game.commanderSession.currentCommander.info, message, replyMsg); } void adminCmdChangeCamera(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { const uint16_t MAX_LEN = 128; char message[MAX_LEN]; PositionXYZ pos; float fspd; float ispd; info("Change Camera command used, args = %s", args); if (strlen (args) == 0) { pos.x = 0; pos.y = 0; pos.z = 0; zoneBuilderChangeCamera((uint8_t)0, &pos, (float)0, (float)0, replyMsg); } else { char **arg; int argc; arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc >= 3) { pos.x = (strlen(arg[0]) == 1 && arg[0][0] == 'c') ? session->game.commanderSession.currentCommander.info.pos.x : atof(arg[0]); pos.y = (strlen(arg[1]) == 1 && arg[1][0] == 'c') ? session->game.commanderSession.currentCommander.info.pos.y : atof(arg[1]); pos.z = (strlen(arg[2]) == 1 && arg[2][0] == 'c') ? session->game.commanderSession.currentCommander.info.pos.z : atof(arg[2]); } if (argc == 3) zoneBuilderChangeCamera((uint8_t)1, &pos, (float)10, (float)0.7, replyMsg); else if (argc == 5) { fspd = atof(arg[3]); ispd = atof(arg[4]); zoneBuilderChangeCamera((uint8_t)1, &pos, fspd, ispd, replyMsg); } else { snprintf(message, sizeof(message), "Bad usage /changeCamera <x> <y> <z> {<fspd> <ispd>}"); zoneBuilderChat(&session->game.commanderSession.currentCommander.info, message, replyMsg); } free(arg); } } void adminCmdSetStamina(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { if (strlen (args) == 0) { info("Set stamina needs a argument!"); } else { char **arg; int argc; info("Set stamina with argument: %s", args); arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc != 1) { info("Wrong number of arguments, must be 1."); } else { uint32_t stamina = atoi(arg[0]) * 1000; info("Setting stamina to %d.", stamina); session->game.commanderSession.currentCommander.info.currentStamina = stamina; zoneBuilderStamina(stamina, replyMsg); } free(arg); } } void adminCmdSetSP(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { if (strlen (args) == 0) { info("Set SP needs a argument!"); } else { char **arg; int argc; info("Set SP with argument: %s", args); arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc != 1) { info("Wrong number of arguments, must be 1."); } else { uint32_t sp = atoi(arg[0]); info("Setting SP to %d.", sp); session->game.commanderSession.currentCommander.info.currentSP = sp; zoneBuilderUpdateSP(session->game.commanderSession.currentCommander.info.pcId, sp, replyMsg); } free(arg); } } void adminCmdSetLevel(Worker *self, Session *session, char *args, zmsg_t *replyMsg) { if (strlen (args) == 0) { info("Set level needs a argument!"); } else { char **arg; int argc; info("Set level with argument: %s", args); arg = strSplit(args, ' '); argc = 0; while (arg[++argc] != NULL); if (argc != 1) { info("Wrong number of arguments, must be 1."); } else { uint32_t level = atoi(arg[0]); info("Setting level to %d.", level); session->game.commanderSession.currentCommander.info.appearance.level = level; zoneBuilderPCLevelUp(session->game.commanderSession.currentCommander.info.pcId, level, replyMsg); } free(arg); } }
/// =-=-=-=-=-=-=- /// @brief interface for POSIX Stat irods::error univ_mss_file_stat( irods::resource_plugin_context& _ctx, struct stat* _statbuf ) { // =-=-=-=-=-=-=- // check context irods::error err = univ_mss_check_param< irods::data_object >( _ctx ); if ( !err.ok() ) { std::stringstream msg; msg << __FUNCTION__; msg << " - invalid context"; return PASSMSG( msg.str(), err ); } // =-=-=-=-=-=-=- // get the script property std::string script; err = _ctx.prop_map().get< std::string >( SCRIPT_PROP, script ); if ( !err.ok() ) { return PASSMSG( __FUNCTION__, err ); } // =-=-=-=-=-=-=- // snag a ref to the fco irods::data_object_ptr fco = boost::dynamic_pointer_cast< irods::data_object >( _ctx.fco() ); std::string filename = fco->physical_path(); int i, status; execCmd_t execCmdInp; char cmdArgv[HUGE_NAME_LEN] = ""; char splchain1[13][MAX_NAME_LEN], splchain2[4][MAX_NAME_LEN], splchain3[3][MAX_NAME_LEN]; char *outputStr; const char *delim1 = ":\n"; const char *delim2 = "-"; const char *delim3 = "."; execCmdOut_t *execCmdOut = NULL; struct tm mytm; time_t myTime; bzero( &execCmdInp, sizeof( execCmdInp ) ); rstrcpy( execCmdInp.cmd, script.c_str(), LONG_NAME_LEN ); strcat( cmdArgv, "stat" ); strcat( cmdArgv, " '" ); strcat( cmdArgv, filename.c_str() ); strcat( cmdArgv, "' " ); rstrcpy( execCmdInp.cmdArgv, cmdArgv, HUGE_NAME_LEN ); rstrcpy( execCmdInp.execAddr, "localhost", LONG_NAME_LEN ); status = _rsExecCmd( _ctx.comm(), &execCmdInp, &execCmdOut ); if ( status == 0 && NULL != execCmdOut ) { // JMC cppcheck - nullptr if ( execCmdOut->stdoutBuf.buf != NULL ) { outputStr = ( char* )execCmdOut->stdoutBuf.buf; memset( &splchain1, 0, sizeof( splchain1 ) ); strSplit( outputStr, delim1, splchain1 ); _statbuf->st_dev = atoi( splchain1[0] ); _statbuf->st_ino = atoi( splchain1[1] ); _statbuf->st_mode = atoi( splchain1[2] ); _statbuf->st_nlink = atoi( splchain1[3] ); _statbuf->st_uid = atoi( splchain1[4] ); _statbuf->st_gid = atoi( splchain1[5] ); _statbuf->st_rdev = atoi( splchain1[6] ); _statbuf->st_size = atoll( splchain1[7] ); _statbuf->st_blksize = atoi( splchain1[8] ); _statbuf->st_blocks = atoi( splchain1[9] ); for ( i = 0; i < 3; i++ ) { memset( &splchain2, 0, sizeof( splchain2 ) ); memset( &splchain3, 0, sizeof( splchain3 ) ); strSplit( splchain1[10 + i], delim2, splchain2 ); mytm.tm_year = atoi( splchain2[0] ) - 1900; mytm.tm_mon = atoi( splchain2[1] ) - 1; mytm.tm_mday = atoi( splchain2[2] ); strSplit( splchain2[3], delim3, splchain3 ); mytm.tm_hour = atoi( splchain3[0] ); mytm.tm_min = atoi( splchain3[1] ); mytm.tm_sec = atoi( splchain3[2] ); myTime = mktime( &mytm ); switch ( i ) { case 0: _statbuf->st_atime = myTime; break; case 1: _statbuf->st_mtime = myTime; break; case 2: _statbuf->st_ctime = myTime; break; } } } } else { status = UNIV_MSS_STAT_ERR - errno; std::stringstream msg; msg << "univ_mss_file_stat - failed for ["; msg << filename; msg << "]"; return ERROR( status, msg.str() ); } return CODE( status ); } // univ_mss_file_stat
bool serverCreateProcess ( ServerInfo *self, char *executableName ) { MySQLInfo *sqlInfo = &self->workersInfo[0].sqlInfo; RedisInfo *redisInfo = &self->workersInfo[0].redisInfo; char *globalServerIp = self->workersInfo[0].globalServerIp; int globalServerPort = self->workersInfo[0].globalServerPort; #ifdef WIN32 executableName = zsys_sprintf("%s.exe", executableName); #endif char *commandLine = zsys_sprintf("%s %d %s %d", executableName, self->routerInfo.routerId, self->routerInfo.ip, self->routerInfo.port ); char *lastCommandLine; lastCommandLine = zsys_sprintf("%s %d %s %d %s %s %s %s %s %d %d %s", commandLine, self->routerInfo.workersCount, globalServerIp, globalServerPort, sqlInfo->hostname, sqlInfo->user, sqlInfo->password, sqlInfo->database, redisInfo->hostname, redisInfo->port, self->serverType, self->output ); zstr_free(&commandLine); commandLine = lastCommandLine; info("CommandLine : %s", commandLine); #ifdef WIN32 STARTUPINFO si = {0}; PROCESS_INFORMATION pi = {0}; if (!CreateProcess (executableName, commandLine, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) { error("Cannot launch Zone Server executable : %s.", executableName); char *errorReason; FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &errorReason, 0, NULL ); error("Error reason : %s", errorReason); return false; } #else char **argv = strSplit (commandLine, ' '); if (fork () == 0) { if (execv (executableName, (char * const *) argv) == -1) { error("Cannot launch Zone Server executable : %s.", executableName); return false; } } free(argv); #endif zstr_free(&commandLine); return true; }