void PiIO::loadPins() { // fullPath = CCFileUtils::sharedFileUtils()->fullPathForFilename("pins.json"); //http://rapidjson.org/md_doc_stream.html#FileReadStream cout << "load pins" << endl; FILE* fp = fopen("pins.json", "r"); // non-Windows use "r" char readBuffer[65536]; FileReadStream is(fp, readBuffer, sizeof(readBuffer)); Document document; document.ParseStream(is); fclose(fp); assert(document.HasMember("pins")); assert(document.IsObject()); const Value& data = document["pins"]; //const Value& data = document.FindMember("pins");//.value; int size = data.Size(); size = size - 1; cout << "Size is " << size << endl; for (int i = size; i >= 0; i--){ // Uses SizeType instead of size_t int wpi = -1; if(data[i].HasMember("wpi")){ wpi = data[i]["wpi"].GetInt(); } pins[i].startup(data[i]["pin"].GetInt(), data[i]["name"].GetString(), wpi, i); } cout << getInfoString() << endl; }
void ParseGameTitlesFromFile(std::map<GameID, std::string>& GameTitlesListOut) { SetCurrentDirectory(NativeStr(g_sHomeDir).c_str()); FILE* pf = nullptr; fopen_s(&pf, RA_TITLES_FILENAME, "rb"); if (pf != nullptr) { Document doc; doc.ParseStream(FileStream(pf)); if (!doc.HasParseError() && doc.HasMember("Success") && doc["Success"].GetBool() && doc.HasMember("Response")) { const Value& List = doc["Response"]; for (Value::ConstMemberIterator iter = List.MemberBegin(); iter != List.MemberEnd(); ++iter) { if (iter->name.IsNull() || iter->value.IsNull()) continue; GameID nID = static_cast<GameID>(std::strtoul(iter->name.GetString(), nullptr, 10)); // KEYS ARE STRINGS, must convert afterwards! const std::string sTitle = iter->value.GetString(); GameTitlesListOut[nID] = sTitle; } } fclose(pf); } }
void Scene::save() { std::ifstream ifs(settings_file); rapidjson::IStreamWrapper isw(ifs); Document doc; doc.ParseStream(isw); ifs.close(); ofstream ofs(settings_file); OStreamWrapper osw(ofs); Writer<OStreamWrapper> writer(osw); Value& scene = doc["scene"]; scene["carcas_enabled"].SetBool(carcas_enabled); scene["animation_enabled"].SetBool(animation_enabled); scene["texture_enabled"].SetBool(texture_enabled); scene["partition"].SetInt(partition); scene["current_time"].SetFloat(current_time); scene["rotate_x"].SetFloat(rotate_x); scene["rotate_y"].SetFloat(rotate_y); scene["scale"].SetFloat(scale); auto lights = doc["lighting"]["local"].GetArray(); for(auto light : local_lights) lights[light.num]["enabled"].SetBool(light.enabled); doc.Accept(writer); ofs.close(); }
// Parse specified string as JSON and set any settings contained in the string // to their specified values bool Settings::SetFromJSONString(const std::string& str) { bool retVal = false; StringStream ss(str.c_str()); try { Document defaultsDoc; defaultsDoc.Parse(_defaultJSON.c_str()); Document doc; doc.ParseStream(ss); const Value& root = doc[SETTINGS_ROOT_KEY]; // first validate the name & type of each setting from the given string for (Value::ConstMemberIterator itr = root.MemberBegin(); itr != root.MemberEnd(); ++itr) { const char* name = itr->name.GetString(); if (!IsValidSettingName(name)) { HandleError(UnknownSetting, true, name); return false; } if (!AreSameType(defaultsDoc[SETTINGS_ROOT_KEY][name], doc[SETTINGS_ROOT_KEY][name])) { HandleError(WrongTypeForSetting, true, name); return false; } } // then set each value into the settings document for (Value::ConstMemberIterator itr = root.MemberBegin(); itr != root.MemberEnd(); ++itr) { const char* name = itr->name.GetString(); if (_settingsDoc[SETTINGS_ROOT_KEY][name].IsString()) { // need to make a copy of the string to be stored const char* str = doc[SETTINGS_ROOT_KEY][name].GetString(); Value s; s.SetString(str, strlen(str), _settingsDoc.GetAllocator()); _settingsDoc[SETTINGS_ROOT_KEY][name] = s; } else _settingsDoc[SETTINGS_ROOT_KEY][name] = doc[SETTINGS_ROOT_KEY][name]; } Save(); retVal = true; } catch(std::exception) { HandleError(CantReadSettingsString, true, str.c_str()); } return retVal; }
string ConfigParser::GetField(const char* field) { stringstream err; FILE* fp = fopen(configPath.c_str(), "rb"); if(!fp){ err << "Could not open file " << configPath << "!"; errors.push_back(err.str()); return ""; } char readBuffer[CONFIGPARSER_BUF_SIZE] = {}; FileReadStream configStream(fp, readBuffer, sizeof(readBuffer)); Document d; d.ParseStream(configStream); if(d.HasMember(field)){ Value& s = d[field]; string value; if ( s.IsString() ) { value = s.GetString(); } fclose(fp); return value; } err << "Could not find field " << field << "!"; errors.push_back(err.str()); fclose(fp); return ""; }
int ConfigParser::GetPort() { stringstream err; FILE* fp = fopen(configPath.c_str(), "rb"); if(!fp){ err << "Could not open file " << configPath << "!"; errors.push_back(err.str()); return -1; } char readBuffer[CONFIGPARSER_BUF_SIZE] = {}; FileReadStream configStream(fp, readBuffer, sizeof(readBuffer)); Document d; d.ParseStream(configStream); if(d.HasMember("Port")){ Value& s = d["Port"]; fclose(fp); return s.GetInt(); } err << "Could not find field [Port]!"; errors.push_back(err.str()); fclose(fp); return -1; }
static void* pfwl_field_tags_load_L7(pfwl_field_id_t field, const char* fileName){ void* db = NULL; if(pfwl_get_L7_field_type(field) == PFWL_FIELD_TYPE_STRING){ db = new pfwl_field_matching_db_t; }else if(pfwl_get_L7_field_type(field) == PFWL_FIELD_TYPE_MMAP){ db = new std::map<std::string, pfwl_field_matching_db_t>; } if(fileName){ std::ifstream ifs(fileName); IStreamWrapper isw(ifs); Document d; d.ParseStream(isw); if (d.HasParseError()){ return NULL; } const Value& rules = d["rules"]; assert(rules.IsArray()); for (Value::ConstValueIterator itr = rules.Begin(); itr != rules.End(); ++itr) { const Value& stringToMatch = (*itr)["value"]; const Value& matchingType = (*itr)["matchingType"]; const Value& tag = (*itr)["tag"]; if(pfwl_get_L7_field_type(field) == PFWL_FIELD_TYPE_STRING){ pfwl_field_string_tags_add_internal(static_cast<pfwl_field_matching_db_t*>(db), stringToMatch.GetString(), getFieldMatchingType(matchingType.GetString()), tag.GetString()); }else if(pfwl_get_L7_field_type(field) == PFWL_FIELD_TYPE_MMAP){ const Value& key = (*itr)["key"]; pfwl_field_mmap_tags_add_internal(static_cast<std::map<std::string, pfwl_field_matching_db_t>*>(db), key.GetString(), stringToMatch.GetString(), getFieldMatchingType(matchingType.GetString()), tag.GetString()); } } } return db; }
/** * class ResourceManager */ bool ResourceManager::v_initialize(void) { FILE* fp = fopen(m_configFile.c_str(), "rb"); char readBuffer[65536]; FileReadStream is(fp, readBuffer, sizeof(readBuffer)); Document jsonConfig; jsonConfig.ParseStream(is); const Value& a = jsonConfig; assert(a.IsArray()); for (SizeType i = 0; i < a.Size(); i++) {// Uses SizeType instead of size_t assert(a[i].IsObject()); assert(a[i].HasMember("id")); assert(a[i]["id"].IsInt()); assert(a[i].HasMember("name")); assert(a[i]["name"].IsString()); assert(a[i].HasMember("path")); assert(a[i]["path"].IsString()); assert(a[i].HasMember("pipeline")); assert(a[i]["pipeline"].IsString()); int id = a[i]["id"].GetInt(); // pipeline string pipeline = a[i]["pipeline"].GetString(); if (pipeline.length() >= SIZE_RESOURCE_NAME-1) assert(false); long pipelineHash = hashString(pipeline); string name = a[i]["name"].GetString(); if (name.length() >= SIZE_RESOURCE_NAME-1) assert(false); string path = a[i]["path"].GetString(); if (path.length() >= SIZE_RESOURCE_PATH-1) assert(false); InternalResHandler *rHandler = new InternalResHandler(id, pipelineHash, name, path); if (a[i].HasMember("links")) { const Value& links = a[i]["links"]; assert(links.IsArray()); for (SizeType i = 0; i < links.Size(); i++) { rHandler->m_linkedResouces[rHandler->m_amountLinkedResouces] = links[i].GetInt(); rHandler->m_amountLinkedResouces++; } } ResourcesMap::iterator it = m_resources.find(id); //TODO better handling of already existant pipeline for a given resource type assert(it == m_resources.end()); m_resources.insert(std::pair<int, InternalResHandler*>(id, rHandler)); _INFO("found resource with id [" << id << "] (" << rHandler->m_name.c_str() << ")"); } fclose(fp); return true; }
void run(char* configFilename) { Document config; FILE* fp = fopen(configFilename, "r"); char buffer[4096]; FileReadStream configFile(fp, buffer, sizeof(buffer)); config.ParseStream(configFile); FMFeature trainData, testData; FMTarget prediction; load_data(config["train_data"].GetString(), trainData, true); load_data(config["test_data"].GetString(), testData, false); fm_train_test(config, trainData, testData, prediction); ofstream fout(config["pred"].GetString()); for (int i = 0; i < prediction.size(); i++) { fout << prediction[i] << ' '; int place = testData.feature[i][0].first; if (place == place_count) fout << endl; } }
void ParseGameHashLibraryFromFile(std::map<std::string, GameID>& GameHashLibraryOut) { SetCurrentDirectory(NativeStr(g_sHomeDir).c_str()); FILE* pf = NULL; fopen_s(&pf, RA_GAME_HASH_FILENAME, "rb"); if (pf != NULL) { Document doc; doc.ParseStream(FileStream(pf)); if (!doc.HasParseError() && doc.HasMember("Success") && doc["Success"].GetBool() && doc.HasMember("MD5List")) { const Value& List = doc["MD5List"]; for (Value::ConstMemberIterator iter = List.MemberBegin(); iter != List.MemberEnd(); ++iter) { if (iter->name.IsNull() || iter->value.IsNull()) continue; const std::string sMD5 = iter->name.GetString(); //GameID nID = static_cast<GameID>( std::strtoul( iter->value.GetString(), NULL, 10 ) ); // MUST BE STRING, then converted to uint. Keys are strings ONLY GameID nID = static_cast<GameID>(iter->value.GetUint()); GameHashLibraryOut[sMD5] = nID; } } fclose(pf); } }
void load(const std::string &filename, vector<unique_ptr<Trellis>> &trellis_buffer) { ifstream file_stream(filename); IStreamWrapper stream_wrapper(file_stream); Document document; document.ParseStream(stream_wrapper); load_trellises(document["trellises"], trellis_buffer); }
void ReadTestConfig(char* fname){ /* Read from JSON file. */ FILE* fp = fopen(fname, "rb"); // non-Windows use "r" assert(fp); char readBuffer[65536*2]; FileReadStream is(fp, readBuffer, sizeof(readBuffer)); /* Parse from stream*/ d.ParseStream(is); fclose(fp); }
TEST(IStreamWrapper, fstream) { fstream fs; ASSERT_TRUE(Open(fs, "utf8bom.json")); IStreamWrapper isw(fs); EncodedInputStream<UTF8<>, IStreamWrapper> eis(isw); Document d; EXPECT_TRUE(!d.ParseStream(eis).HasParseError()); EXPECT_TRUE(d.IsObject()); EXPECT_EQ(5, d.MemberCount()); }
int main(int argc, char** argv) { if(argc < 2){ printf("Usage: %s json_file\n\n", argv[0]); return -1; } FILE* fp = fopen(argv[1], "r"); char readBuffer[65535]; FileReadStream is(fp, readBuffer, sizeof(readBuffer)); Document d; d.ParseStream(is); fclose(fp); //将读取的json重新格式化输出 printf("\nModified JSON with reformatting:\n"); StringBuffer sb; PrettyWriter<StringBuffer> writer(sb); d.Accept(writer); // Accept() traverses the DOM and generates Handler events. puts(sb.GetString()); printf("\n\n"); //解析json,生成配置相关的map assert(d.HasMember("keyname")); //get keyname const Value& key = d["keyname"]; assert(key.IsString()); const char* key_name = key.GetString(); printf("key:%s\n", key_name); //read values const Value& values = d["values"]; assert(values.IsArray()); printf("values size is:%d\n", values.Size()); for(Value::ConstValueIterator it=values.Begin(); it != values.End(); ++it) { assert(it->IsObject()); //查找实际的key // Value::ConstMemberIterator itr = it->FindMember(key_name); if(itr != it->MemberEnd()){ printf("%s : %d\n", itr->name.GetString(), itr->value.GetInt()); } } return 0; }
Document loadDocument(const std::string& documentPath) { FILE *fp = fopen(documentPath.c_str(), "r"); // non-Windows use "r" char readBuffer[65536]; //TODO: check this magic constant FileReadStream is(fp, readBuffer, sizeof(readBuffer)); Document doc; doc.ParseStream(is); fclose(fp); return doc; }
bool testJson(const char *json, size_t &line, size_t &col) { StringStream ss(json); CursorStreamWrapper<StringStream> csw(ss); Document document; document.ParseStream(csw); bool ret = document.HasParseError(); if (ret) { col = csw.GetColumn(); line = csw.GetLine(); } return ret; }
StreamingAnomalyDetector::StreamingAnomalyDetector(const char* modelFile) { FILE* pFile = fopen(modelFile, "r"); char buffer[256]; FileReadStream is(pFile, buffer, sizeof(buffer)); Document doc; doc.ParseStream(is); windowSize_ = (doc["WindowSize"]).GetInt(); const Value& thresholds = doc["Thresholds"]; for (auto itr = thresholds.Begin(); itr != thresholds.End(); ++itr) Thresholds.push_back((float)itr->GetDouble()); Init(); }
int ConfigParser::SetField(const char* field, const char* value) { stringstream err; FILE* fpRead = fopen(configPath.c_str(), "rb"); if(!fpRead){ err << "Could not open file " << configPath << "!"; errors.push_back(err.str()); return -1; } char readBuffer[CONFIGPARSER_BUF_SIZE] = {}; FileReadStream configStream(fpRead, readBuffer, sizeof(readBuffer)); Document d; d.ParseStream(configStream); if(d.HasMember(field)){ Value& tmp(d[field]); tmp.SetString(StringRef(value)); } else { Value::AllocatorType& a(d.GetAllocator()); d.AddMember(StringRef(field), StringRef(value), a); if(!d.HasMember(field)){ fclose(fpRead); err << "Failed to set field '" << field << "'' in config file " << configPath << "!"; errors.push_back(err.str()); return -1; } } fclose(fpRead); FILE* fpWrite = fopen(configPath.c_str(), "wb"); if(!fpWrite){ err << "Could not open file " << configPath << "!"; errors.push_back(err.str()); return -1; } char writeBuffer[CONFIGPARSER_BUF_SIZE] = {}; FileWriteStream configWriteStream(fpWrite, writeBuffer, sizeof(writeBuffer)); PrettyWriter<FileWriteStream> writer(configWriteStream); d.Accept(writer); fclose(fpWrite); return 0; }
void FileTypes::load_filetypes() { auto filetypes_path = string(XSEARCHPATH); filetypes_path.append("/shared/filetypes.json"); if (!FileUtil::file_exists(filetypes_path)) { string msg = "Filetypes file not found: "; msg.append(filetypes_path); log_error(msg); // TODO: SearchException return; } FILE* fp = fopen(filetypes_path.c_str(), "r"); char readBuffer[65536]; FileReadStream is(fp, readBuffer, sizeof(readBuffer)); Document document; document.ParseStream(is); fclose(fp); assert(document.HasMember("filetypes")); const Value& filetypes = document["filetypes"]; assert(filetypes.IsArray()); for (SizeType i = 0; i < filetypes.Size(); i++) { const Value::ConstObject &filetype = filetypes[i].GetObject(); assert(filetype.HasMember("type")); const Value &typeValue = filetype["type"]; string type = typeValue.GetString(); assert(filetype.HasMember("extensions")); const Value& extensions = filetype["extensions"]; for (SizeType j = 0; j < extensions.Size(); j++) { if (type == "archive") { archive_extensions.insert(extensions[j].GetString()); } else if (type == "binary") { binary_extensions.insert(extensions[j].GetString()); } else if (type == "code") { code_extensions.insert(extensions[j].GetString()); } else if (type == "text") { text_extensions.insert(extensions[j].GetString()); } else if (type == "xml") { xml_extensions.insert(extensions[j].GetString()); } } } }
void Dlg_MemBookmark::ImportFromFile( std::string sFilename ) { FILE* pFile = nullptr; errno_t nErr = fopen_s( &pFile, sFilename.c_str(), "r" ); if ( pFile != nullptr ) { Document doc; doc.ParseStream( FileStream( pFile ) ); if ( !doc.HasParseError() ) { if ( doc.HasMember( "Bookmarks" ) ) { ClearAllBookmarks(); const Value& BookmarksData = doc[ "Bookmarks" ]; for ( SizeType i = 0; i < BookmarksData.Size(); ++i ) { MemBookmark* NewBookmark = new MemBookmark(); wchar_t buffer[ 256 ]; swprintf_s ( buffer, 256, L"%s", Widen( BookmarksData[ i ][ "Description" ].GetString() ).c_str() ); NewBookmark->SetDescription ( buffer ); NewBookmark->SetAddress( BookmarksData[ i ][ "Address" ].GetUint() ); NewBookmark->SetType( BookmarksData[ i ][ "Type" ].GetInt() ); NewBookmark->SetDecimal( BookmarksData[ i ][ "Decimal" ].GetBool() ); NewBookmark->SetValue( GetMemory( NewBookmark->Address(), NewBookmark->Type() ) ); NewBookmark->SetPrevious ( NewBookmark->Value() ); AddBookmark ( NewBookmark ); AddBookmarkMap( NewBookmark ); } if ( m_vBookmarks.size() > 0 ) PopulateList(); } else { ASSERT ( " !Invalid Bookmark File..." ); MessageBox( nullptr, _T("Could not load properly. Invalid Bookmark file."), _T("Error"), MB_OK | MB_ICONERROR ); return; } } fclose( pFile ); } }
std::map<std::string, std::string> ConfigParser::GetConfigMap() { std::map<std::string, std::string> configMap; stringstream err; FILE* fp = fopen(configPath.c_str(), "rb"); if(!fp){ err << "Could not open file " << configPath << "!"; errors.push_back(err.str()); return configMap; } char readBuffer[CONFIGPARSER_BUF_SIZE] = {}; FileReadStream configStream(fp, readBuffer, sizeof(readBuffer)); Document d; d.ParseStream(configStream); if(!d.IsObject()){ return configMap; } for(Value::MemberIterator it = d.MemberBegin(); it != d.MemberEnd(); ++it){ if ( !it->name.IsString() ) { LOG_RELEASE("Warning: JSON key value is not a string."); continue; } if(strcmp(it->name.GetString(),"Port") == 0){ configMap[it->name.GetString()] = ""; } else if(strcmp(it->name.GetString(),"Roster") == 0){ configMap[it->name.GetString()] = ""; } else{ // Ignore non-string if ( it->value.IsString() ) { configMap[it->name.GetString()] = it->value.GetString(); } } } fclose(fp); return configMap; }
int ConfigParser::SetPort(int value) { stringstream err; FILE* fpRead = fopen(configPath.c_str(), "rb"); if(!fpRead){ err << "Could not open file " << configPath << "!"; errors.push_back(err.str()); return -1; } char readBuffer[CONFIGPARSER_BUF_SIZE] = {}; FileReadStream configStream(fpRead, readBuffer, sizeof(readBuffer)); Document d; d.ParseStream(configStream); if(!d.HasMember("Port")){ fclose(fpRead); err << "Could not set field Port! NOT FOUND"; return 1; } Value& tmp = d["Port"]; fclose(fpRead); FILE* fpWrite = fopen(configPath.c_str(), "wb"); if(!fpWrite){ err << "Could not open file " << configPath << "!"; errors.push_back(err.str()); return -1; } char writeBuffer[CONFIGPARSER_BUF_SIZE] = {}; FileWriteStream configWriteStream(fpWrite, writeBuffer, sizeof(writeBuffer)); PrettyWriter<FileWriteStream> writer(configWriteStream); tmp.SetInt(value); d.Accept(writer); std::ofstream of(configPath.c_str()); of << writeBuffer; fclose(fpWrite); return 0; }
// Overrides base type to insert the registration URL & code in the screen void RegistrationScreen::Draw(IDisplay* pDisplay, PrinterStatus* pStatus) { // look for the ScreenLines with replaceable text ReplaceableLine* regURLLine = _pScreenText->GetReplaceable(1); ReplaceableLine* regCodeLine = _pScreenText->GetReplaceable(2); if (regURLLine != NULL && regCodeLine != NULL) { // get registration code & URL from file created by web client const char* regURL = UNKNOWN_REGISTRATION_URL; const char* regCode = UNKNOWN_REGISTRATION_CODE; try { FILE* pFile = fopen(PRIMARY_REGISTRATION_INFO_FILE, "r"); char buf[LOAD_BUF_LEN]; FileReadStream frs1(pFile, buf, LOAD_BUF_LEN); // first parse into a temporary doc, for validation Document doc; doc.ParseStream(frs1); // make sure the file is valid RAPIDJSON_ASSERT(doc.IsObject() && doc.HasMember(REGISTRATION_URL_KEY) && doc.HasMember(REGISTRATION_CODE_KEY)) regURL = doc[REGISTRATION_URL_KEY].GetString(); regCode = doc[REGISTRATION_CODE_KEY].GetString(); fclose(pFile); } catch(std::exception) { Logger::HandleError(CantReadRegistrationInfo, false, PRIMARY_REGISTRATION_INFO_FILE); } // insert the URL & registration code regURLLine->ReplaceWith(regURL); regCodeLine->ReplaceWith(regCode); } Screen::Draw(pDisplay, pStatus); }
void ParseMyProgressFromFile(std::map<GameID, std::string>& GameProgressOut) { FILE* pf = nullptr; fopen_s(&pf, RA_MY_PROGRESS_FILENAME, "rb"); if (pf != nullptr) { Document doc; doc.ParseStream(FileStream(pf)); if (!doc.HasParseError() && doc.HasMember("Success") && doc["Success"].GetBool() && doc.HasMember("Response")) { //{"ID":"7","NumAch":"14","Earned":"10","HCEarned":"0"}, const Value& List = doc["Response"]; for (Value::ConstMemberIterator iter = List.MemberBegin(); iter != List.MemberEnd(); ++iter) { GameID nID = static_cast<GameID>(std::strtoul(iter->name.GetString(), nullptr, 10)); // KEYS MUST BE STRINGS const unsigned int nNumAchievements = iter->value["NumAch"].GetUint(); const unsigned int nEarned = iter->value["Earned"].GetUint(); const unsigned int nEarnedHardcore = iter->value["HCEarned"].GetUint(); std::stringstream sstr; sstr << nEarned; if (nEarnedHardcore > 0) sstr << " (" << std::to_string(nEarnedHardcore) << ")"; sstr << " / " << nNumAchievements; if (nNumAchievements > 0) { const int nNumEarnedTotal = nEarned + nEarnedHardcore; char bufPct[256]; sprintf_s(bufPct, 256, " (%1.1f%%)", (nNumEarnedTotal / static_cast<float>(nNumAchievements)) * 100.0f); sstr << bufPct; } GameProgressOut[nID] = sstr.str(); } } fclose(pf); } }
TEST(test_emws_seger, test_emws_seger_test_save) { el::Logger *testLogger = el::Loggers::getLogger("emws_seger_unittest"); using namespace std; using namespace rapidjson; const string filename = "./conf/emws_config.json"; FILE* fp = fopen(filename.data(), "rb"); char readBuffer[65536]; FileReadStream is(fp, readBuffer, sizeof(readBuffer)); Document config; config.ParseStream(is); fclose(fp); StringBuffer buffer; PrettyWriter<StringBuffer> writer(buffer); config.Accept(writer); testLogger->info("=====parameters====\n%v", buffer.GetString()); testLogger->info("initial model ..."); string const model_name = "emws"; base_seger *seger = base_seger::create_seger(config, model_name); string const model_path = utf8_io::gen_model_path(model_name, "./model"); testLogger->info("save model to %v\n\n", model_path); // save model bool ret = seger->save(model_path); EXPECT_EQ(ret, true); // load model testLogger->info("load model ..."); base_seger *loaded_seger = base_seger::load(model_path, model_name); testLogger->info("train ..."); loaded_seger->train(); testLogger->info("train done"); }
void Scene::load() { std::ifstream ifs(settings_file); rapidjson::IStreamWrapper isw(ifs); Document doc; doc.ParseStream(isw); deserializeLightParams(doc, global_light, local_lights, materials); deserializeTextures(textures, doc); if (!doc.HasMember("scene")) { std::cerr << "Incorrect settings file. Directive scene is absent" << endl; return; } Value& scene = doc["scene"]; carcas_enabled = scene["carcas_enabled"].GetBool(); animation_enabled = scene["animation_enabled"].GetBool(); partition = scene["partition"].GetInt(); current_time = scene["current_time"].GetFloat(); rotate_x = scene["rotate_x"].GetFloat(); rotate_y = scene["rotate_y"].GetFloat(); scale = scene["scale"].GetFloat(); texture_enabled = scene["texture_enabled"].GetBool(); if (!doc.HasMember("optimization")) { std::cout << "NOTE: optimization directive is absent" << std::endl; return; } Value& jOParams = doc["optimization"]; optimization.optimize_drawing = jOParams["optimize_drawing"].GetBool(); optimization.optimize_animation = jOParams["optimize_animation"].GetBool(); optimization.display_lists = jOParams["display_lists"].GetBool(); optimization.optimize_lighting = jOParams["optimize_lighting"].GetBool(); }
void pkg::ImageConfig::load(std::istream &config) { IStreamWrapper isw(config); Document doc; doc.ParseStream(isw); this->Deserialize(doc); }
int _tmain(int argc, char *argv[]) { int AddToSSGS(); int RemoveFromSSGS(); LPCTSTR RegisterGameArg = L"/add"; LPCTSTR UnregisterGameArg = L"/remove"; LPCTSTR CommandLineArgs = NULL; // Exit if no arguments found. if (argc >= 2) { // Setup args for processing. CommandLineArgs = GetCommandLine(); PathGetArgs(CommandLineArgs); } else { return INFO_NO_ARGUMENTS; } // Get path to SteelSeries Engine 3's coreProps.json and grab the address from it. GetEnvironmentVariableA("PROGRAMDATA", SSGS_corePropsJsonPath, MAX_PATH); strcat_s(SSGS_corePropsJsonPath, MAX_PATH, "\\SteelSeries\\SteelSeries Engine 3\\coreProps.json"); // Grab address. FILE* fp; if (fopen_s(&fp, SSGS_corePropsJsonPath, "rb") != 0) { // No coreProps.json?! return ERR_COREPROPS_NOT_FOUND; } FileReadStream is(fp, SSGS_corePropsJsonBuffer, corePropsJsonBufferSize); Document d; d.ParseStream(is); strcpy_s(SSGS_ServerAddress, SSGS_ServerAddressBufferSize, d["address"].GetString()); fclose(fp); // Setup special addresses. // Game event. strcpy_s(SSGS_ServerAddress_GameEvent, SSGS_ServerAddressBufferSize, SSGS_ServerAddress); strcat_s(SSGS_ServerAddress_GameEvent, SSGS_ServerAddressBufferSize, "/game_event"); // Game Metadata. strcpy_s(SSGS_ServerAddress_GameMetadata, SSGS_ServerAddressBufferSize, SSGS_ServerAddress); strcat_s(SSGS_ServerAddress_GameMetadata, SSGS_ServerAddressBufferSize, "/game_metadata"); // Register Game Events. strcpy_s(SSGS_ServerAddress_RegisterGameEvent, SSGS_ServerAddressBufferSize, SSGS_ServerAddress); strcat_s(SSGS_ServerAddress_RegisterGameEvent, SSGS_ServerAddressBufferSize, "/register_game_event"); // Remove Game event. strcpy_s(SSGS_ServerAddress_RemoveGameEvent, SSGS_ServerAddressBufferSize, SSGS_ServerAddress); strcat_s(SSGS_ServerAddress_RemoveGameEvent, SSGS_ServerAddressBufferSize, "/remove_game_event"); // Remove Game. strcpy_s(SSGS_ServerAddress_RemoveGame, SSGS_ServerAddressBufferSize, SSGS_ServerAddress); strcat_s(SSGS_ServerAddress_RemoveGame, SSGS_ServerAddressBufferSize, "/remove_game"); // AddGameArg. if (StrStrI(CommandLineArgs, RegisterGameArg) != NULL) { cout << "\nAdding Fallout 4 to SteelSeries Engine 3 GameSense.\n\n"; AddToSSGS(); cout << "\n\nFallout 4 added to SteelSeries Engine 3 GameSense & Config in My Games\\Fallout4 created.\n"; } // RemoveGameArg. else if (StrStrI(CommandLineArgs, UnregisterGameArg) != NULL) { cout << "\n\nRemoving Fallout 4 from SteelSeries Engine 3 GameSense.\n\n"; RemoveFromSSGS(); cout << "\n\nFallout 4 removed from SteelSeries Engine 3 GameSense & Config in My Games\\Fallout4 deleted.\n"; } return 0; }
// Load all the Settings from a file. If 'initializing' is true, then any // corrupted or missing settings are given their default values. In that way, // when new settings are added in new versions of the firmware, any values for // existing settings will not be lost. bool Settings::Load(const std::string& filename, bool initializing) { bool retVal = false; std::vector<std::string> missing; try { FILE* pFile = fopen(filename.c_str(), "r"); char buf[LOAD_BUF_LEN]; FileReadStream frs1(pFile, buf, LOAD_BUF_LEN); // first parse into a temporary doc, for validation Document doc; doc.ParseStream(frs1); // make sure the file is valid RAPIDJSON_ASSERT(doc.IsObject() && doc.HasMember(SETTINGS_ROOT_KEY)) // create a default doc, to check that all the expected setting names // are present and have the correct type // (we may not yet have a valid _settingsDoc) Document defaultDoc; defaultDoc.Parse(_defaultJSON.c_str()); for (std::set<std::string>::iterator it = _names.begin(); it != _names.end(); ++it) { if (doc[SETTINGS_ROOT_KEY].HasMember(it->c_str())) { if (!AreSameType(defaultDoc[SETTINGS_ROOT_KEY][it->c_str()], doc[SETTINGS_ROOT_KEY][it->c_str()])) { HandleError(WrongTypeForSetting, true, it->c_str()); return false; } } else { if (initializing) // record the missing member to be added missing.push_back(*it); else throw std::exception(); } } // parse again, but now into _settingsDoc fseek(pFile, 0, SEEK_SET); FileReadStream frs2(pFile, buf, LOAD_BUF_LEN); _settingsDoc.ParseStream(frs2); fclose(pFile); if (initializing && missing.size() > 0) { // add any missing settings, with their default values for (std::vector<std::string>::iterator it = missing.begin(); it != missing.end(); ++it) { _settingsDoc[SETTINGS_ROOT_KEY].AddMember(StringRef(it->c_str()), defaultDoc[SETTINGS_ROOT_KEY][StringRef(it->c_str())], _settingsDoc.GetAllocator()); } Save(); } retVal = true; } catch(std::exception) { // if we're initializing, we'll handle this by simply regenerating // the settings file from scratch if (!initializing) HandleError(CantLoadSettings, true, filename.c_str()); } return retVal; }
bool parse_space_file(const std::string & filename) { using namespace rapidjson; std::ifstream space_file(filename, std::ifstream::in); if(!space_file.good()) { std::cerr << "Unable to open parameter space specification file " << filename << std::endl; assert(false); return false; } else { IStreamWrapper space_file_wrapper(space_file); Document document; document.ParseStream(space_file_wrapper); if(!document.IsObject()) { std::cerr << "Parameter space file root must be an object." << std::endl; return false; } if(!document.HasMember("tuning_space")) { std::cerr << "Parameter space file root must contain a member named 'tuning_space'." << std::endl; return false; } const auto & tuning_spec = document["tuning_space"]; if(!tuning_spec.IsObject()) { std::cerr << "Parameter space file's 'tuning_space' member must be an object." << std::endl; return false; } if(!tuning_spec.HasMember("omp_num_threads")) { std::cerr << "Parameter space file's 'tuning_space' object must contain a member named 'omp_num_threads'" << std::endl; return false; } if(!tuning_spec.HasMember("omp_schedule")) { std::cerr << "Parameter space file's 'tuning_space' object must contain a member named 'omp_schedule'" << std::endl; return false; } if(!tuning_spec.HasMember("omp_chunk_size")) { std::cerr << "Parameter space file's 'tuning_space' object must contain a member named 'omp_chunk_size'" << std::endl; return false; } const auto & omp_num_threads_array = tuning_spec["omp_num_threads"]; const auto & omp_schedule_array = tuning_spec["omp_schedule"]; const auto & omp_chunk_size_array = tuning_spec["omp_chunk_size"]; // Validate array types if(!omp_num_threads_array.IsArray()) { std::cerr << "Parameter space file's 'omp_num_threads' member must be an array." << std::endl; return false; } if(!omp_schedule_array.IsArray()) { std::cerr << "Parameter space file's 'omp_schedule' member must be an array." << std::endl; return false; } if(!omp_chunk_size_array.IsArray()) { std::cerr << "Parameter space file's 'omp_chunk_size' member must be an array." << std::endl; return false; } // omp_num_threads std::list<std::string> num_threads_list; for(auto itr = omp_num_threads_array.Begin(); itr != omp_num_threads_array.End(); ++itr) { if(itr->IsInt()) { const unsigned int this_num_threads = itr->GetInt(); if (this_num_threads <= apex::hardware_concurrency()) { const std::string this_num_threads_str = std::to_string(this_num_threads); num_threads_list.push_back(this_num_threads_str); } } else if(itr->IsString()) { const char * this_num_threads = itr->GetString(); if ((unsigned int)(atoi(this_num_threads)) <= apex::hardware_concurrency()) { const std::string this_num_threads_str = std::string(this_num_threads, itr->GetStringLength()); num_threads_list.push_back(this_num_threads_str); } } else { std::cerr << "Parameter space file's 'omp_num_threads' member must contain only integers or strings" << std::endl; return false; } } thread_space = new std::list<std::string>{num_threads_list}; // omp_schedule std::list<std::string> schedule_list; for(auto itr = omp_schedule_array.Begin(); itr != omp_schedule_array.End(); ++itr) { if(itr->IsString()) { const char * this_schedule = itr->GetString(); const std::string this_schedule_str = std::string(this_schedule, itr->GetStringLength()); schedule_list.push_back(this_schedule_str); } else { std::cerr << "Parameter space file's 'omp_schedule' member must contain only strings" << std::endl; return false; } } schedule_space = new std::list<std::string>{schedule_list}; // omp_chunk_size std::list<std::string> chunk_size_list; for(auto itr = omp_chunk_size_array.Begin(); itr != omp_chunk_size_array.End(); ++itr) { if(itr->IsInt()) { const int this_chunk_size = itr->GetInt(); const std::string this_chunk_size_str = std::to_string(this_chunk_size); chunk_size_list.push_back(this_chunk_size_str); } else if(itr->IsString()) { const char * this_chunk_size = itr->GetString(); const std::string this_chunk_size_str = std::string(this_chunk_size, itr->GetStringLength()); chunk_size_list.push_back(this_chunk_size_str); } else { std::cerr << "Parameter space file's 'omp_chunk_size' member must contain only integers or strings" << std::endl; return false; } } chunk_space = new std::list<std::string>{chunk_size_list}; } return true; }