void ItemsMaker::doWork() { int r = rand_r(&m_randSeed); r = r % (int)m_sleepMs(); int first = -1; string bucket; ItemsListPtr items; { boost::lock_guard<boost::mutex> lock(g_data.m_mutex); if (g_data.m_buckets.empty()) { return; } int n = r % g_data.m_buckets.size(); BucketsMap::iterator iter = g_data.m_buckets.begin(); for (int i = 0; iter != g_data.m_buckets.end(); i++, iter++) { if (i == n) { break; } } if (iter == g_data.m_buckets.end()) { cout << "ItemsMaker: Failed to find bucket" << endl; return; } bucket = iter->first; items = iter->second; if (!items->empty()) { first = *items->begin(); } } if (r < m_multipliyer() * m_reconnectProbability()) { m_sock.disconnect(); sleepMs(20); m_sock.connect("localhost", m_port); } int prob = m_multipliyer() * m_createProbability(); if (r < prob) { // Add item string cmd = string("create ") + bucket + " 1111"; execCommand(m_sock, cmd, m_buffer); int id; int n = sscanf(m_buffer.raw(), "%d", &id); if (n == 1) { boost::lock_guard<boost::mutex> lock(g_data.m_mutex); items->push_back(id); } else { //cout << "Failed to add item: " << m_buffer.raw() << endl; } return; } prob += m_multipliyer() * m_deleteProbability(); if (r < prob && !items->empty()) { // Delete item string cmd = string("delete ") + bucket + " " + boost::lexical_cast<string>(first); execCommand(m_sock, cmd, m_buffer); if (strcmp(m_buffer.raw(), "ok") == 0) { boost::lock_guard<boost::mutex> lock(g_data.m_mutex); if (*items->begin() == first) { items->erase(items->begin()); } } else { //cout << "Failed to delete item: " << m_buffer.raw() << endl; } return; } prob += m_multipliyer() * m_updateProbability(); if (r < prob && !items->empty()) { // Update item string cmd = string("update ") + bucket + " " + boost::lexical_cast<string>(first) + " 2222"; execCommand(m_sock, cmd, m_buffer); if (strcmp(m_buffer.raw(), "ok") != 0) { //cout << "Failed to update item: " << m_buffer.raw() << endl; } return; } prob += m_multipliyer() * m_readProbability(); if (r < prob && !items->empty()) { // Read item string cmd = string("read ") + bucket + " " + boost::lexical_cast<string>(first); execCommand(m_sock, cmd, m_buffer); } prob += m_multipliyer() * m_invalidProbability(); if (r < prob && !items->empty()) { // Invalid command string cmd = string("invalide command"); execCommand(m_sock, cmd, m_buffer); } }
virtual bool run(const string& , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) { log() << "replSet replSetInitiate admin command received from client" << rsLog; if( !replSet ) { errmsg = "server is not running with --replSet"; return false; } if( theReplSet ) { errmsg = "already initialized"; result.append("info", "try querying " + rsConfigNs + " to see current configuration"); return false; } { // just make sure we can get a write lock before doing anything else. we'll reacquire one // later. of course it could be stuck then, but this check lowers the risk if weird things // are up. time_t t = time(0); Lock::GlobalWrite lk; if( time(0)-t > 10 ) { errmsg = "took a long time to get write lock, so not initiating. Initiate when server less busy?"; return false; } /* check that we don't already have an oplog. that could cause issues. it is ok if the initiating member has *other* data than that. */ BSONObj o; if( Helpers::getFirst(rsoplog, o) ) { errmsg = rsoplog + string(" is not empty on the initiating member. cannot initiate."); return false; } } if( ReplSet::startupStatus == ReplSet::BADCONFIG ) { errmsg = "server already in BADCONFIG state (check logs); not initiating"; result.append("info", ReplSet::startupStatusMsg.get()); return false; } if( ReplSet::startupStatus != ReplSet::EMPTYCONFIG ) { result.append("startupStatus", ReplSet::startupStatus); errmsg = "all members and seeds must be reachable to initiate set"; result.append("info", cmdLine._replSet); return false; } BSONObj configObj; if( cmdObj["replSetInitiate"].type() != Object ) { result.append("info2", "no configuration explicitly specified -- making one"); log() << "replSet info initiate : no configuration specified. Using a default configuration for the set" << rsLog; string name; vector<HostAndPort> seeds; set<HostAndPort> seedSet; parseReplsetCmdLine(cmdLine._replSet, name, seeds, seedSet); // may throw... bob b; b.append("_id", name); bob members; members.append("0", BSON( "_id" << 0 << "host" << HostAndPort::me().toString() )); result.append("me", HostAndPort::me().toString()); for( unsigned i = 0; i < seeds.size(); i++ ) members.append(bob::numStr(i+1), BSON( "_id" << i+1 << "host" << seeds[i].toString())); b.appendArray("members", members.obj()); configObj = b.obj(); log() << "replSet created this configuration for initiation : " << configObj.toString() << rsLog; } else { configObj = cmdObj["replSetInitiate"].Obj(); } bool parsed = false; try { scoped_ptr<ReplSetConfig> newConfig(ReplSetConfig::make(configObj)); parsed = true; if( newConfig->version > 1 ) { errmsg = "can't initiate with a version number greater than 1"; return false; } log() << "replSet replSetInitiate config object parses ok, " << newConfig->members.size() << " members specified" << rsLog; checkMembersUpForConfigChange(*newConfig, result, true); log() << "replSet replSetInitiate all members seem up" << rsLog; createOplog(); Lock::GlobalWrite lk; bo comment = BSON( "msg" << "initiating set"); newConfig->saveConfigLocally(comment); log() << "replSet replSetInitiate config now saved locally. Should come online in about a minute." << rsLog; result.append("info", "Config now saved locally. Should come online in about a minute."); ReplSet::startupStatus = ReplSet::SOON; ReplSet::startupStatusMsg.set("Received replSetInitiate - should come online shortly."); // Dummy minvalid - just something non-null so we can be "up" OpTime minvalid(1, 0); BSONObjBuilder bob; bob.appendTimestamp("ts", minvalid.asDate()); ReplSet::setMinValid(bob.done()); } catch( DBException& e ) { log() << "replSet replSetInitiate exception: " << e.what() << rsLog; if( !parsed ) errmsg = string("couldn't parse cfg object ") + e.what(); else errmsg = string("couldn't initiate : ") + e.what(); return false; } catch( string& e2 ) { log() << e2 << rsLog; errmsg = e2; return false; } return true; }
//React on events from METKManager void METKAutoFading::handleObjMgrNotification() { omEventContainer myEventList = getEventContainer(); //Durchiterieren der EventList omEventContainer::const_iterator iter; for ( iter = myEventList.begin();iter!=myEventList.end(); iter++) { ObjMgrEvent myEvent = (*iter); if (myEvent.layerID == LAY_VIEWER_CAMERA && myEvent.infoID == INF_VIEWER_CAMERA_POSITION && _EnableFading->getBoolValue() && _UseMETKValues->getBoolValue() ) { _calc->notify(); } else if (myEvent.layerID == LAY_APPEARANCE) { if (myEvent.infoID == INF_VISIBLE) { if (myEvent.newValue.getStringValue() == "TRUE") { //std::cout << "ENABLE" << myEvent.objectID << std::endl; m_calcVis.setStatus(myEvent.objectID,true); } else { //std::cout << "DISABLE" << myEvent.objectID << std::endl; m_calcVis.setStatus(myEvent.objectID,false); } } } else if (myEvent.objectID == OBJ_COMMUNICATION && myEvent.layerID == LAY_GLOBALEVENTS && string(myEvent.newValue) == MSG_LOADED) { std::cout << "METKAutoFading loaded event ... call _init" << std::endl; _init->notify(); } } clearEventContainer(); }
//!Set the value of an attribute in the ObjMgr-DB - no Notification will be send void ObjMgrCommunicator::setObjAttribute(const string ObjID, const string LayerID, const string InfoID, void* value, const string omInfoType, const bool createIfNotExists, const bool persistent, const bool ignoreType) { // Get writable access to object container bool attrCreated = false; omObjectContainer* oc = getObjContainer(); if(oc == NULL) { kDebug::Debug("ObjContainer not found!",kDebug::DL_LOW); } else { if (!(*oc).exists(ObjID) && !createIfNotExists) { kDebug::Debug("invalidObject "+ObjID,kDebug::DL_LOW); } else { omObject& obj = (*oc)[ObjID]; omAttribute& attr = obj.getAttribute(LayerID,InfoID); if (!obj.hasAttribute(LayerID,InfoID) && createIfNotExists) { attr.createDataType(omInfoType); attrCreated = true; } if (obj.hasAttribute(LayerID,InfoID)) { if (string(attr.getDataType()->getName())!=omInfoType && !ignoreType) { obj.removeAttribute(LayerID,InfoID); attr.createDataType(omInfoType); attrCreated = true; } } attr.flags().markPersistent(persistent); //Diese Sache mit den void*-Pointern zur Verallgemeinerung wird uns irgendwann mal mächtig um die Ohren fliegen ... if (omInfoType == omINFOTYPE_STRING) { obj[LayerID][InfoID].setStringValue(*((string *)value)); } else if (omInfoType == omINFOTYPE_DOUBLE) { const double oldV = obj[LayerID][InfoID]; const double newV = *((double *)value); if (fabs(oldV-newV)>=0.000001f || attrCreated) obj[LayerID][InfoID] = *((double *)value); } else if (omInfoType == omINFOTYPE_INT32) { const double oldV = obj[LayerID][InfoID]; const double newV = *((int *)value); if (fabs(oldV-newV)>=0 || attrCreated) obj[LayerID][InfoID] = *((int *)value); } else if (omInfoType == omINFOTYPE_VEC3) { const vec3 tempVec3 = *(vec3*)value; const vec3 objVec3 = obj[LayerID][InfoID].get_vec3(); const SbVec3f oldV = SbVec3f(objVec3[0],objVec3[1],objVec3[2]); const SbVec3f newV = SbVec3f(tempVec3[0],tempVec3[1],tempVec3[2]); if(kBasics::maxDiff(oldV,newV)>=0.000001f || attrCreated) { obj[LayerID][InfoID] = tempVec3; } } else if (omInfoType == omINFOTYPE_VEC4) { const vec4 tempVec4 = *(vec4*)value; const vec4 objVec4 = obj[LayerID][InfoID].get_vec4(); const SbVec4f oldV = SbVec4f(objVec4[0],objVec4[1],objVec4[2],objVec4[3]); const SbVec4f newV = SbVec4f(tempVec4[0],tempVec4[1],tempVec4[2],tempVec4[3]); if (kBasics::maxDiff(oldV,newV)>=0.000001f || attrCreated) obj[LayerID][InfoID] = tempVec4; } else if (omInfoType == omINFOTYPE_BOOL) { const bool oldV = obj[LayerID][InfoID]; if (oldV!=*(bool *)value || attrCreated) obj[LayerID][InfoID] = *(bool *)value; } else if (omInfoType == omINFOTYPE_MESSAGE) { obj[LayerID][InfoID] = *((omMessage *)value); } } } }
Lexeme Scanner::get_lex() { int number, j; current_state = START; type_of_lex tmp; do { switch(current_state) { case START: if(next == ' ' || next == '\n' || next == '\t') { if(next == '\n') line++; get_next(); } else if(isalpha(next)) { current_state = IDENT; clear_buffer(); add_next_to_buffer(); get_next(); } else if(isdigit(next)) { current_state = NUMB; number = next - '0'; get_next(); } else if(next == '\'') { current_state = STRI1; clear_buffer(); get_next(); } else if(next == '\"') { current_state = STRI2; clear_buffer(); get_next(); } else if(next == '>' || next == '<' || next == '=' || next == '&' || next == '|' || next == '!' || next == '/' || next == '-' || next == '+') { current_state = DELIM2; clear_buffer(); add_next_to_buffer(); get_next(); } else if(next == -1) { return Lexeme(LEX_FIN); } else { current_state = DELIM; clear_buffer(); add_next_to_buffer(); } break; case IDENT: if(isalpha(next) || isdigit(next)) { add_next_to_buffer(); get_next(); } else if(MJSWords.find(scan_buffer) != MJSWords.end()) { tmp = MJSWords[scan_buffer]; if(tmp == LEX_TRUE) { return Lexeme(LEX_BOOL, true); } else if(tmp == LEX_FALSE) { return Lexeme(LEX_BOOL, false); } else { return Lexeme(tmp); } } else if(find(MJSFields.begin(), MJSFields.end(), scan_buffer) != MJSFields.end()) { return Lexeme(LEX_FIELDS, string(scan_buffer)); } else if(find(MJSMethods.begin(), MJSMethods.end(), scan_buffer) != MJSMethods.end()) { return Lexeme(LEX_METHODS, string(scan_buffer)); } else { return Lexeme(LEX_ID, TOI.put(scan_buffer)); } break; case NUMB: if(isdigit(next)) { number = number * 10 + (next - '0'); get_next(); } else { return Lexeme(LEX_NUM, number); } break; case STRI1: if(next == '\'') { get_next(); return Lexeme(LEX_STR, string(scan_buffer)); } else if(next == -1) { throw lexical_exception(next, line, "Unexpected EOF in LEX_STR"); } else if(next == '\\') { get_next(); if(next == 'n') add_to_buffer('\n'); get_next(); } else { add_next_to_buffer(); get_next(); } break; case STRI2: if(next == '\"') { get_next(); return Lexeme(LEX_STR, string(scan_buffer)); } else if(next == -1) { throw lexical_exception(next, line, "Unexpected EOF in LEX_STR"); } else if(next == '\\') { get_next(); if(next == 'n') { add_to_buffer('\n'); } else { add_next_to_buffer(); } get_next(); } else { add_next_to_buffer(); get_next(); } break; case DELIM: if(MJSDelims.find(scan_buffer) != MJSDelims.end()) { get_next(); return Lexeme(MJSDelims[scan_buffer]); } else { throw lexical_exception(next, line, "Forbidden symbol"); } break; case DELIM2: add_next_to_buffer(); if(scan_buffer[0] == '=' && next == '=') { current_state = DELIM3; get_next(); } else if(MJSDelims.find(scan_buffer) != MJSDelims.end()) { get_next(); if(MJSDelims[scan_buffer] == LEX_COMM) { current_state = COMM; } else { return Lexeme(MJSDelims[scan_buffer]); } } else { scan_buffer[1] = '\0'; if(MJSDelims.find(scan_buffer) != MJSDelims.end()) { return Lexeme(MJSDelims[scan_buffer]); } else { throw lexical_exception(next, line, "Forbidden symbol"); } } break; case DELIM3: if(next == '=') { get_next(); return Lexeme(LEX_IDENT); } else { return Lexeme(LEX_EQ); } break; case COMM: if(next == '\n' || next == -1) { line++; current_state = START; clear_buffer(); get_next(); } else { get_next(); } default: break; } } while(true); }
Mave FromBson(bsoncxx::types::value bson) { Mave result; vector<function<bool()>> continuations; auto root = bson; while (true) { switch (bson.type()) { case bsoncxx::type::k_undefined: case bsoncxx::type::k_minkey: case bsoncxx::type::k_maxkey: break; case bsoncxx::type::k_null: result = nullptr; break; case bsoncxx::type::k_bool: result = bson.get_bool().value; break; case bsoncxx::type::k_int32: result = bson.get_int32().value; break; case bsoncxx::type::k_int64: result = bson.get_int64().value; break; case bsoncxx::type::k_double: result = bson.get_double().value; break; case bsoncxx::type::k_date: result = milliseconds(bson.get_date().value); break; case bsoncxx::type::k_utf8: result = bson.get_utf8().value.to_string(); break; case bsoncxx::type::k_oid: result = make_pair(BSON_OID, bson.get_oid().value.to_string()); break; case bsoncxx::type::k_dbpointer: result = make_pair(BSON_OID, bson.get_dbpointer().value.to_string()); break; case bsoncxx::type::k_timestamp: auto t = bson.get_timestamp(); result = (long)(((unsigned long long)t.timestamp << 32) | t.increment); break; case bsoncxx::type::k_binary: auto b = bson.get_binary(); result = string((const char*)b.bytes, b.size); break; case bsoncxx::type::k_regex: result = bson.get_regex().regex.to_string(); break; case bsoncxx::type::k_symbol: result = bson.get_symbol().symbol.to_string(); break; case bsoncxx::type::k_code: result = bson.get_code().code.to_string(); break; case bsoncxx::type::k_codewscope: result = bson.get_codewscope().code.to_string(); break; case bsoncxx::type::k_document: continuations.push_back( [& , m = map<string, Mave>() , i = bson.get_document().value.cbegin() , e = bson.get_document().value.cend() , f = false]() mutable -> bool { if (f) { m.insert({ i->key().to_string(), result }); ++i; } if (i != e) { bson = i->get_value(); return f = true; } result = move(m); return false; }); break; case bsoncxx::type::k_array: continuations.push_back( [& , v = vector<Mave>() , i = bson.get_array().value.cbegin() , e = bson.get_array().value.cend() , f = false]() mutable -> bool { if (f) { v.push_back(result); ++i; } if (i != e) { bson = i->get_value(); return f = true; } result = move(v); return false; }); break; default: throw exception("Mave::FromBson(): unsupported type encountered"); } while (true) { if (continuations.size() == 0) { return result; } if (continuations.back()()) { break; } continuations.pop_back(); } } }
const string& Gamedata::getXmlStr(const string& tag) const { std::map<string, string>::const_iterator ptr = gameData.find(tag); if ( ptr == gameData.end() ) throw string("Game: Didn't find string tag ")+tag+string(" in xml"); else return ptr->second; }
int DSMFactory::onLoad() { if (loaded) return 0; loaded = true; if(cfg.loadFile(AmConfig::ModConfigPath + string(MOD_NAME ".conf"))) return -1; // get application specific global parameters configureModule(cfg); DebugDSM = cfg.getParameter("debug_raw_dsm") == "yes"; CheckDSM = cfg.getParameter("dsm_consistency_check", "yes") == "yes"; if (!loadPrompts(cfg)) return -1; if (!loadPromptSets(cfg)) return -1; if (!loadDiags(cfg, MainScriptConfig.diags)) return -1; vector<string> registered_apps; if (!registerApps(cfg, MainScriptConfig.diags, registered_apps)) return -1; InboundStartDiag = cfg.getParameter("inbound_start_diag"); if (InboundStartDiag.empty()) { INFO("no 'inbound_start_diag' set in config. " "inbound calls with application 'dsm' disabled.\n"); } OutboundStartDiag = cfg.getParameter("outbound_start_diag"); if (OutboundStartDiag.empty()) { INFO("no 'outbound_start_diag' set in config. " "outbound calls with application 'dsm' disabled.\n"); } if (!InboundStartDiag.empty()) AmPlugIn::instance()->registerFactory4App("dsm",this); MainScriptConfig.config_vars.insert(cfg.begin(), cfg.end()); // for (std::map<string,string>::const_iterator it = // cfg.begin(); it != cfg.end(); it++) // MainScriptConfig.config_vars[it->first] = it->second; MainScriptConfig.RunInviteEvent = cfg.getParameter("run_invite_event")=="yes"; MainScriptConfig.SetParamVariables = cfg.getParameter("set_param_variables")=="yes"; vector<string> system_dsms = explode(cfg.getParameter("run_system_dsms"), ","); for (vector<string>::iterator it=system_dsms.begin(); it != system_dsms.end(); it++) { string status; if (createSystemDSM("main", *it, false /* reload */, status)) { DBG("created SystemDSM '%s'\n", it->c_str()); } else { ERROR("creating system DSM '%s': '%s'\n", it->c_str(), status.c_str()); return -1; } } #ifdef USE_MONITORING string monitoring_full_callgraph = cfg.getParameter("monitoring_full_stategraph"); MonitoringFullCallgraph = monitoring_full_callgraph == "yes"; DBG("%sogging full call graph (states) to monitoring.\n", MonitoringFullCallgraph?"L":"Not l"); string monitoring_full_transitions = cfg.getParameter("monitoring_full_transitions"); MonitoringFullTransitions = monitoring_full_transitions == "yes"; DBG("%sogging full call graph (transitions) to monitoring.\n", MonitoringFullTransitions?"L":"Not l"); string cfg_usecaller = cfg.getParameter("monitor_select_use_caller"); if (cfg_usecaller.empty() || cfg_usecaller=="from") MonSelectCaller = MonSelect_FROM; else if (cfg_usecaller=="no") MonSelectCaller = MonSelect_NONE; else if (cfg_usecaller=="pai") MonSelectCaller = MonSelect_PAI; else { ERROR("monitor_select_use_caller value '%s' not understood\n", cfg_usecaller.c_str()); } string cfg_usecallee = cfg.getParameter("monitor_select_use_callee"); if (cfg_usecallee.empty() || cfg_usecallee=="ruri") MonSelectCallee = MonSelect_RURI; else if (cfg_usecallee=="no") MonSelectCallee = MonSelect_NONE; else if (cfg_usecallee=="from") MonSelectCallee = MonSelect_FROM; else { ERROR("monitor_select_use_callee value '%s' not understood\n", cfg_usecallee.c_str()); } MonSelectFilters = explode(cfg.getParameter("monitor_select_filters"), ","); string filters; for (vector<string>::iterator it = MonSelectFilters.begin(); it != MonSelectFilters.end(); it++) { if (it != MonSelectFilters.begin()) filters += ", "; filters+=*it; } if (MonSelectFilters.size()) { DBG("using additional monitor app select filters: %s\n", filters.c_str()); } else { DBG("not using additional monitor app select filters\n"); } MonSelectFallback = cfg.getParameter("monitor_select_fallback"); #endif string conf_d_dir = cfg.getParameter("conf_dir"); if (!conf_d_dir.empty()) { if (conf_d_dir[conf_d_dir.length()-1] != '/') conf_d_dir += '/'; DBG("processing configurations in '%s'...\n", conf_d_dir.c_str()); int err=0; struct dirent* entry; DIR* dir = opendir(conf_d_dir.c_str()); if(!dir){ INFO("DSM config files loader (%s): %s\n", conf_d_dir.c_str(), strerror(errno)); } else { while( ((entry = readdir(dir)) != NULL) && (err == 0) ){ string conf_name = string(entry->d_name); if (conf_name.find(".conf",conf_name.length()-5) == string::npos){ continue; } string conf_file_name = conf_d_dir + conf_name; DBG("loading %s ...\n",conf_file_name.c_str()); if (!loadConfig(conf_file_name, conf_name, false, NULL)) return -1; } closedir(dir); } } if(cfg.hasParameter("enable_session_timer") && (cfg.getParameter("enable_session_timer") == string("yes")) ){ DBG("enabling session timers\n"); session_timer_f = AmPlugIn::instance()->getFactory4Seh("session_timer"); if(session_timer_f == NULL){ ERROR("Could not load the session_timer module: disabling session timers.\n"); } } return 0; }
/* * Returns the type of this pragma */ enum pragmaType PragmaParser::getPragmaType() { if(!isPopcornPragma()) throw string("Cannot get type because this is an unknown pragma"); return PragmaBuilder::string2type(pragmaType); }
void CrewUI::helmsUI() { sf::RenderTarget* window = getRenderTarget(); sf::Vector2f mouse = InputHandler::getMousePos(); if (InputHandler::mouseIsPressed(sf::Mouse::Left)) { sf::Vector2f diff = mouse - sf::Vector2f(800, 450); if (sf::length(diff) < 400) mySpaceship->commandTargetRotation(sf::vector2ToAngle(diff)); } //Radar float radarDistance = 5000; drawRaderBackground(mySpaceship->getPosition(), sf::Vector2f(800, 450), 400, 400.0f / radarDistance); foreach(SpaceObject, obj, spaceObjectList) { if (obj != mySpaceship && sf::length(obj->getPosition() - mySpaceship->getPosition()) < radarDistance) obj->drawRadar(*window, sf::Vector2f(800, 450) + (obj->getPosition() - mySpaceship->getPosition()) / radarDistance * 400.0f, 400.0f / radarDistance, false); } P<SpaceObject> target = mySpaceship->getTarget(); if (target) { sf::Sprite objectSprite; textureManager.setTexture(objectSprite, "redicule.png"); objectSprite.setPosition(sf::Vector2f(800, 450) + (target->getPosition() - mySpaceship->getPosition()) / radarDistance * 400.0f); window->draw(objectSprite); } mySpaceship->drawRadar(*window, sf::Vector2f(800, 450), 400.0f / radarDistance, false); drawHeadingCircle(sf::Vector2f(800, 450), 400); //!Radar text(sf::FloatRect(10, 100, 200, 20), "Energy: " + string(int(mySpaceship->energy_level)), AlignLeft, 20); float res = vslider(sf::FloatRect(20, 500, 50, 300), mySpaceship->impulseRequest, 1.0, -1.0); if (res > -0.15 && res < 0.15) res = 0.0; if (res != mySpaceship->impulseRequest) mySpaceship->commandImpulse(res); text(sf::FloatRect(20, 800, 50, 20), string(int(mySpaceship->impulseRequest * 100)) + "%", AlignLeft, 20); text(sf::FloatRect(20, 820, 50, 20), string(int(mySpaceship->currentImpulse * 100)) + "%", AlignLeft, 20); float x = 100; if (mySpaceship->hasWarpdrive) { res = vslider(sf::FloatRect(x, 500, 50, 300), mySpaceship->warpRequest, 4.0, 0.0); if (res != mySpaceship->warpRequest) mySpaceship->commandWarp(res); text(sf::FloatRect(100, 800, 50, 20), string(int(mySpaceship->warpRequest)), AlignLeft, 20); text(sf::FloatRect(100, 820, 50, 20), string(int(mySpaceship->currentWarp * 100)) + "%", AlignLeft, 20); x += 80; } if (mySpaceship->hasJumpdrive) { jumpDistance = vslider(sf::FloatRect(x, 500, 50, 300), jumpDistance, 40.0, 1.0, 1.0); jumpDistance = roundf(jumpDistance * 10.0f) / 10.0f; text(sf::FloatRect(x, 800, 50, 20), string(jumpDistance, 1) + "km", AlignLeft, 20); if (mySpaceship->jumpDelay > 0.0) { text(sf::FloatRect(x, 820, 50, 20), string(int(ceilf(mySpaceship->jumpDelay))), AlignLeft, 20); }else{ if (button(sf::FloatRect(x - 10, 820, 70, 30), "Jump", 20)) { mySpaceship->commandJump(jumpDistance); } } x += 80; } switch(mySpaceship->docking_state) { case DS_NotDocking: { PVector<Collisionable> obj_list = CollisionManager::queryArea(mySpaceship->getPosition() - sf::Vector2f(1000, 1000), mySpaceship->getPosition() + sf::Vector2f(1000, 1000)); P<SpaceStation> station; foreach(Collisionable, obj, obj_list) { station = obj; if (station && sf::length(station->getPosition() - mySpaceship->getPosition()) < 1000.0) { break; } } if (station) { if (button(sf::FloatRect(x, 800, 280, 50), "Request Dock", 30)) mySpaceship->commandDock(station); }else{ disabledButton(sf::FloatRect(x, 800, 280, 50), "Request Dock", 30); } } break; case DS_Docking: disabledButton(sf::FloatRect(x, 800, 280, 50), "Docking...", 30); break; case DS_Docked: if (button(sf::FloatRect(x, 800, 280, 50), "Undock", 30)) mySpaceship->commandUndock(); break; }
int main() { // unsigned char key[16] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10}; // unsigned char input[16] = "关关雎"; // unsigned char output[16]; // SM4::Apis::encrypt(input, 16, output); // SM4::Apis::decrypt(output, 16, output); // printf("%s\n",output); // sm4_context ctx; //// unsigned long i; // // //encrypt standard testing vector // sm4_setkey_enc(&ctx,key); // sm4_crypt_ecb(&ctx,1,16,input,output); //// for(i=0;i<16;i++) //// printf("%02x ", output[i]); // printf("[%s]",output); // printf("\n"); // // //decrypt testing // sm4_setkey_dec(&ctx,key); // sm4_crypt_ecb(&ctx,0,16,output,output); // printf("%s\n",output); //// for(i=0;i<16;i++) //// printf("%02x ", output[i]); // printf("\n"); // const char * str = "关关雎鸠,在河之洲。窈窕淑女,君子好逑。参差荇菜,左右流之。窈窕淑女,寤寐求之。求之不得,寤寐思服。悠哉悠哉,辗转反侧。参差荇菜,左右采之。窈窕淑女,琴瑟友之。参差荇菜,左右芼之。窈窕淑女,钟鼓乐之。"; int len = (int)strlen(str); printf("%d\n",len); crypto::BlockList blockList = crypto::Utils::toBlocks(str, len); crypto::BlockList blockList1 = crypto::Utils::toBlocks(str, len); crypto::BlockListIterator iter; char encryptData[len]; char decryptData[len]; memset(encryptData, 0, len); memset(decryptData, 0, len); string ret; crypto::Apis::encryptBlocks(blockList); crypto::Apis::encryptBlocksTo(blockList1,encryptData); printf("++++++[%s]\n",encryptData); printf("========================\n"); crypto::BlockList blockList2 = crypto::Utils::toBlocks(encryptData, len); for(iter = blockList2.begin();iter != blockList2.end();++iter) { ret += string(iter -> constData()); } int flag = strcmp(ret.c_str(), encryptData); printf("%d\n",flag); crypto::Apis::decryptBlocksTo(blockList2, decryptData); printf("222222222222[%s]\n",decryptData); crypto::Apis::decrpytBlocks(blockList); for(iter = blockList.begin();iter != blockList.end(); ++iter) { printf("%s",iter ->constData()); } printf("\n"); return 0; }
SceneManager::SceneManager(GLint width, GLint height) #endif { Log << Function << endl; // The projection matrix is represented by the perspective matrix given by glm, assign it to each one of the objects GLfloat aspect = static_cast<GLfloat>(width) / static_cast<GLfloat>(height); projectionMatrix = glm::perspective( 45.0f, // Field of view, is the amount of zoom. A wide angle is 90 and a narrow angle is 30 aspect, // Depends on the size of the window 0.1f, // Near clipping plane 500.0f // Far clipping plane ); // Read the resources.txt file to obtain the valid configuration for the engine string resourcesFileName = "resources.txt"; #if defined(__ANDROID__) AAssetManager* mgr = AAssetManager_fromJava(*env, assetManager); AAsset* pFile = AAssetManager_open(mgr, resourcesFileName.c_str(), AASSET_MODE_UNKNOWN); if (!pFile) #else ifstream resourcesFile(resourcesFileName, ios::in); if (!resourcesFile.is_open()) #endif { Log << Error << "Unable to read the resources file: " << resourcesFileName << endl; terminate(); } #if defined(__ANDROID__) // Get the file size size_t fileSize = AAsset_getLength(pFile); // Read data from the file char* pData = (char*)calloc(fileSize + 1, sizeof(char)); AAsset_read(pFile, pData, fileSize); // fix the string to be zero-terminated pData[fileSize] = 0; // Copy the data to a stringstream stringstream resourcesFile(pData); AAsset_close(pFile); free(pData); #endif Log << Debug << "Parsing the resources.txt file." << endl; string line, name, vertex, fragment, object, texture, projection, modelview; vector<string> cubeTextures{ NumCubeFaces }; GLuint size, bufferType; vec3 pos, scl, rot; char token; bool finished = true; while (getline(resourcesFile, line)) { stringstream ssLine(line); // Ignore empty lines on the configuration file if(line.size() == 0) continue; ssLine >> token; switch (token) { // If the line is a comment get the next token case '#': continue; // Start of object definition case '.': // Create a new scene object Log << Debug << "Starting an object definition." << endl; sceneobjects.push_back(make_unique<SceneObject>()); finished = false; break; // End of an object definition case '-': Log << Debug << "End an object definition." << endl; finished = true; break; // Attributes used on the shaders case 'A': ssLine >> name >> size >> bufferType; Log << Debug << "Adding the attribute: " << name << endl; attributes.push_back(make_unique<Variable>(name, size, (BufferType)bufferType)); break; // Uniforms used on the shaders case 'U': ssLine >> name; Log << Debug << "Adding the uniform: " << name << endl; uniforms.push_back(make_unique<Variable>(name)); break; // Shaders creation case 'S': ssLine >> vertex >> fragment; Log << Debug << "Creating the shaders." << endl; #if defined (__ANDROID__) sceneobjects.back()->SetShader(make_shared<Shader>(&mgr, vertex, fragment, attributes, uniforms)); #else sceneobjects.back()->SetShader(make_shared<Shader>(vertex, fragment, attributes, uniforms)); #endif break; // Object definitions case 'O': ssLine >> object; Log << Debug << "Loading a model." << endl; #if defined (__ANDROID__) sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, object, sceneobjects.back()->GetShader())); #else sceneobjects.back()->SetMesh(make_unique<Mesh>(object, sceneobjects.back()->GetShader())); #endif break; // Textures case 'T': ssLine >> texture; Log << Debug << "Loading a texture." << endl; #if defined(__ANDROID__) sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, texture, sceneobjects.back()->GetShader())); #else sceneobjects.back()->SetTexture(make_unique<Texture>(texture, sceneobjects.back()->GetShader())); #endif break; // Initial coordinates case 'C': Log << Debug << "Adding coordinates to the object." << endl; ssLine >> pos.x >> pos.y >> pos.z >> scl.x >> scl.y >> scl.z >> rot.x >> rot.y >> rot.z >> angle; sceneobjects.back()->SetCoordinates(pos, scl, rot, angle); break; // Projection matrix case 'P': ssLine >> projection; break; // Modelview matrix case 'M': ssLine >> modelview; break; // Skybox case 'B': Log << Debug << "Adding a skybox." << endl; ssLine >> cubeTextures[0] >> cubeTextures[1] >> cubeTextures[2] >> cubeTextures[3] >> cubeTextures[4] >> cubeTextures[5]; sceneobjects.back()->SetSkymap(); #if defined(__ANDROID__) sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, string(""), sceneobjects.back()->GetShader())); sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, cubeTextures, sceneobjects.back()->GetShader())); #else sceneobjects.back()->SetMesh(make_unique<Mesh>(string(""), sceneobjects.back()->GetShader())); sceneobjects.back()->SetTexture(make_unique<Texture>(cubeTextures, sceneobjects.back()->GetShader())); #endif break; // Terrain Heightmap case 'H': Log << Debug << "Loading the terrain." << endl; ssLine >> texture >> object; #if defined(__ANDROID__) sceneobjects.back()->SetTexture(make_unique<Texture>(&mgr, texture, sceneobjects.back()->GetShader())); sceneobjects.back()->SetMesh(make_unique<Mesh>(&mgr, object, sceneobjects.back()->GetShader(), &sceneobjects.back()->GetTexture())); #else sceneobjects.back()->SetTexture(make_unique<Texture>(texture, sceneobjects.back()->GetShader())); sceneobjects.back()->SetMesh(make_unique<Mesh>(object, sceneobjects.back()->GetShader(), &sceneobjects.back()->GetTexture())); #endif break; default: continue; } // Check if the definition of an object is complete or if more lines are needed if (finished) { // Get the projection and modelview uniforms if (!projection.empty()) { sceneobjects.back()->SetProjectionUni(glGetUniformLocation(sceneobjects.back()->GetShader()->getProgramObject(), "Projection")); projection.clear(); } if (!modelview.empty()) { sceneobjects.back()->SetModelviewUni(glGetUniformLocation(sceneobjects.back()->GetShader()->getProgramObject(), "Modelview")); modelview.clear(); } // Clear the attributes and uniforms in order to load the next object attributes.clear(); uniforms.clear(); } } #if !defined(__ANDROID__) // Close de the resources file resourcesFile.close(); #endif // Set the initial position of the camera camera = vec3(2.5f, -1.0f, -5.0f); // Initial value of the rotation angle angle = 0.0f; }
void CInterProcessLock::Lock(const CTimeout& timeout, const CTimeout& granularity) { CFastMutexGuard LOCK(s_ProcessLock); // Check that lock with specified name not already locked // in the current process. TLocks::iterator it = s_Locks->find(m_SystemName); if (m_Handle != kInvalidLockHandle) { // The lock is already set in this CInterProcessLock object, // just increase reference counter. _VERIFY(it != s_Locks->end()); it->second++; return; } else { if (it != s_Locks->end()) { // The lock already exists in the current process. // We can use one CInterProcessLock object with // multiple Lock() calls, but not with different // CInterProcessLock objects. For example, on MS-Windows, // we cannot wait on the same mutex in the same thread. // So, two different objects can set locks simultaneously. // And for OS-compatibility we can do nothing here, // except throwing an exception. NCBI_THROW(CInterProcessLockException, eMultipleLocks, "Attempt to lock already locked object " \ "in the same process"); } } // Try to acquire a lock with specified timeout #if defined(NCBI_OS_UNIX) // Open lock file mode_t perm = CDirEntry::MakeModeT( CDirEntry::fRead | CDirEntry::fWrite /* user */, CDirEntry::fRead | CDirEntry::fWrite /* group */, 0, 0 /* other & special */); int fd = open(m_SystemName.c_str(), O_CREAT | O_RDWR, perm); if (fd == -1) { NCBI_THROW(CInterProcessLockException, eCreateError, string("Error creating lockfile ") + m_SystemName + ": " + strerror(errno)); } // Try to acquire the lock int x_errno = 0; if (timeout.IsInfinite() || timeout.IsDefault()) { while ((x_errno = s_UnixLock(fd))) { if (errno != EAGAIN) break; } } else { unsigned long ms = timeout.GetAsMilliSeconds(); if ( !ms ) { // Timeout == 0 x_errno = s_UnixLock(fd); } else { // Timeout > 0 unsigned long ms_gran; if ( granularity.IsInfinite() || granularity.IsDefault() ) { ms_gran = min(ms/5, (unsigned long)500); } else { ms_gran = granularity.GetAsMilliSeconds(); } // Try to lock within specified timeout for (;;) { x_errno = s_UnixLock(fd); if ( !x_errno ) { // Successfully locked break; } if (x_errno != EACCES && x_errno != EAGAIN ) { // Error break; } // Otherwise -- sleep granularity timeout unsigned long ms_sleep = ms_gran; if (ms_sleep > ms) { ms_sleep = ms; } if ( !ms_sleep ) { break; } SleepMilliSec(ms_sleep); ms -= ms_sleep; } // Timeout if ( !ms ) { close(fd); NCBI_THROW(CInterProcessLockException, eLockTimeout, "The lock could not be acquired in the time " \ "allotted"); } } // if (!ms) } // if (timeout.IsInfinite()) // Error if ( x_errno ) { close(fd); NCBI_THROW(CInterProcessLockException, eLockError, "Error creating lock"); } // Success m_Handle = fd; #elif defined(NCBI_OS_MSWIN) HANDLE handle = ::CreateMutex(NULL, TRUE, _T_XCSTRING(m_SystemName)); errno_t errcode = ::GetLastError(); if (handle == kInvalidLockHandle) { switch(errcode) { case ERROR_ACCESS_DENIED: // Mutex with specified name already exists, // but we don't have enough rights to open it. NCBI_THROW(CInterProcessLockException, eLockError, "The lock already exists"); break; case ERROR_INVALID_HANDLE: // Some system object with the same name already exists NCBI_THROW(CInterProcessLockException, eLockError, "Error creating lock, system object with the same" \ "name already exists"); break; default: // Unknown error NCBI_THROW(CInterProcessLockException, eCreateError, "Error creating lock"); break; } } else { // Mutex with specified name already exists if (errcode == ERROR_ALREADY_EXISTS) { // Wait DWORD res; if (timeout.IsInfinite() || timeout.IsDefault()) { res = WaitForSingleObject(handle, INFINITE); } else { res = WaitForSingleObject(handle, timeout.GetAsMilliSeconds()); } switch(res) { case WAIT_OBJECT_0: // The lock has been acquired break; case WAIT_TIMEOUT: ::CloseHandle(handle); NCBI_THROW(CInterProcessLockException, eLockTimeout, "The lock could not be acquired in the time " \ "allotted"); break; case WAIT_ABANDONED: // The lock is in abandoned state... Other thread/process // owning it was terminated. We can reuse this mutex, but // it is better to wait until it will be released by OS. /* FALLTHRU */ default: ::CloseHandle(handle); NCBI_THROW(CInterProcessLockException, eLockError, "Error creating lock"); break; } } m_Handle = handle; } #endif // Set reference counter to 1 (*s_Locks)[m_SystemName] = 1; }
// Runs program with input from test files in testFiles vector. void TestSuite::runTests() { int numCorrect = 0, numWrong = 0; int i; string name; string logName; string stored_dir; double rate; bool crit = false; string crit_string = "crit.tst"; bool crit_passed = true; char buff[40]; int chpid = 45; //Get directory of current program i = testProgram.rfind('.'); testProgram = testProgram.substr(0, i); // Create log file. logName = testProgram + "-"; logName += exeTime; logName += ".log"; ofstream fout(logName.c_str()); if (!fout) { return; } // Iterate over test files. vector<string>::iterator it; for ( it = testFiles.begin(); it != testFiles.end() ; it++ ) { //Determine if this is a critical test if(it->find(crit_string) != string::npos) { crit = true; } // Get test file name without path. size_t pos = it->rfind("/"); if(pos != std::string::npos) { name = it->substr(pos+1,it->length()); } // Output test file name to log file. fout << name; // Run program with given test file. run_code(*it,name); //else, do a failed program log file i supposd // Determine corresponding answer file. string ans = *it; ans.replace(ans.end()-4, ans.end(),answerExtension); // Output results. if (correct_answer(ans)) { numCorrect++; fout << ": PASS" << endl; } else { //If this was a crit test, they auto fail if(crit) { crit_passed = false; } numWrong++; fout << ": FAIL" << endl; } } //If all possible crit tests were passed if(crit_passed) { // Output pass and fail stats. rate = ( numCorrect / (double)(numCorrect + numWrong) ) * 100; fout << rate << "% CORRECT," << numCorrect << " PASSED," << numWrong << " FAILED"; sprintf(buff, " %f%% Correct\n", rate); i = testProgram.rfind('/'); studentResults.push_back(testProgram.substr(i+1) + string(buff)); } else { //If one or more were not passed fout << "Failed: Did not pass one or more acceptance tests (Labeled as crit)" << endl; i = testProgram.rfind('/'); studentResults.push_back(testProgram.substr(i) + " FAILED\n"); } fout << "\n" << get_gcov(testProgram) << endl; fout.close(); if(profiling) get_gprof(testProgram); }
RoutingPlan* RoutingPlan::normalizeRules( const string& planname ) { DEBUG( "Normalizing plan [" << m_Name << "] target is [" << planname << "]" ); // check if the name is ok if ( m_IsTerminal || m_Exitpoint.isValid() ) { // if it's this plan, start normalizing if ( planname == m_Name ) { // terminal paths need no normalization if ( m_IsNormalized ) { DEBUG( "Plan already normalized/not terminal" ); return NULL; } m_IsNormalized = true; return this; } else return NULL; } if ( m_Name.length() > planname.length() ) { TRACE( "Unable to normalize plan [not terminal]" ); return NULL; } string nextStr = planname.substr( m_Name.length() ); RoutingPlan* plan = NULL; // success plan if ( nextStr.substr( 0, 2 ) == string( "-1" ) ) { if ( m_SuccessPlan == NULL ) throw runtime_error( string( "Unable to find a plan with name" ) + planname ); plan = m_SuccessPlan->normalize( planname ); if ( plan == NULL ) return NULL; for ( unsigned int i=0; i<m_ForkConditions.size(); i++ ) { plan->m_SuccessConditions.push_back( m_ForkConditions[ i ] ); } } else // fail plan { if ( m_FailPlan == NULL ) throw runtime_error( string( "Unable to find a plan with name" ) + planname ); plan = m_FailPlan->normalize( planname ); if ( plan == NULL ) return NULL; for ( unsigned int i=0; i<m_ForkConditions.size(); i++ ) { plan->m_FailConditions.push_back( m_ForkConditions[ i ] ); } } // add all rules for ( unsigned int i=0; i<m_Rules.size(); i++ ) { ( void )plan->m_Rules.insert( plan->m_Rules.begin() + i, m_Rules[ i ] ); } return plan; }
/* * Get the names contained in the pragma, if there are any */ set<string> PragmaParser::getNames() { if(!isPopcornPragma()) throw string("Cannot get names because this is an unknown pragma"); return names; }
void renderString(int x, int y, string glstring){ unsigned int i = 0; int uc; double tx, ty, span = 0; //Textures::TEXTURE_RGBA Tex; TextureID ftex; wchar_t* wstr = nullptr; MBToWC(glstring.c_str(), wstr, 128); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, ww, wh, 0, -1.0, 1.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glEnable(GL_TEXTURE_2D); for (unsigned int k = 0; k < wstrlen(wstr); k++){ glLoadIdentity(); glColor4f(r, g, b, a); glTranslated(x + 1 + span, y + 1, 0); uc = wstr[k]; if (!useUnicodeASCIIFont && glstring[i]>=0 && glstring[i] <= 127){ glprint(x + 1 + (int)span, y + 1, string() + glstring[i]); } else{ if (!unicodeTexAval[uc / 256]) { //printf("[Console][Event]"); //printf("Loading unicode font texture #%d\n", uc / 256); std::stringstream ss; ss << "Textures\\Fonts\\unicode\\unicode_glyph_" << uc / 256 << ".bmp"; ftex = Textures::LoadFontTexture(ss.str()); unicodeTex[uc / 256] = ftex; unicodeTexAval[uc / 256] = true; } else{ ftex = unicodeTex[uc / 256]; } tx = ((uc % 256) % 16) / 16.0; ty = 1 - ((uc % 256) / 16) / 16.0; glBindTexture(GL_TEXTURE_2D, ftex); glBegin(GL_QUADS); glColor4f(0.5, 0.5, 0.5, a); glTexCoord2d(tx, ty); glVertex2i(1, 1); glTexCoord2d(tx + 0.0625, ty); glVertex2i(17, 1); glTexCoord2d(tx + 0.0625, ty - 0.0625); glVertex2i(17, 17); glTexCoord2d(tx, ty - 0.0625); glVertex2i(1, 17); glColor4f(r, g, b, a); glTexCoord2d(tx, ty); glVertex2i(0, 0); glTexCoord2d(tx + 0.0625, ty); glVertex2i(16, 0); glTexCoord2d(tx + 0.0625, ty - 0.0625); glVertex2i(16, 16); glTexCoord2d(tx, ty - 0.0625); glVertex2i(0, 16); glEnd(); } if (glstring[i] >= 0 && glstring[i] <= 127){ i += 1; span += 10; } else{ i += 2; span += 16; } } glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glColor4f(1.0, 1.0, 1.0, 1.0); free(wstr); }
CValueConvert<SSafeSqlCP, CDB_Object>::operator string(void) const { if (m_Value.IsNULL()) { return string(); } string result; const EDB_Type cur_type = m_Value.GetType(); switch (cur_type) { case eDB_Int: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_Int&>(m_Value).Value()), std::string); case eDB_SmallInt: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_SmallInt&>(m_Value).Value()), std::string); case eDB_TinyInt: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_TinyInt&>(m_Value).Value()), std::string); case eDB_BigInt: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_BigInt&>(m_Value).Value()), std::string); case eDB_Bit: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_Bit&>(m_Value).Value()), std::string); case eDB_Float: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_Float&>(m_Value).Value()), std::string); case eDB_Double: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_Double&>(m_Value).Value()), std::string); case eDB_Numeric: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_Numeric&>(m_Value).Value()), std::string); case eDB_Char: case eDB_VarChar: case eDB_LongChar: { const CDB_String& cdb_str = static_cast<const CDB_String&>(m_Value); const string& str = cdb_str.AsString(); return ConvertSafe(str); } case eDB_Binary: return ConvertSafe(string( static_cast<const char*>(static_cast<const CDB_Binary&>(m_Value).Value()), static_cast<const CDB_Binary&>(m_Value).Size() )); case eDB_VarBinary: return ConvertSafe(string( static_cast<const char*>(static_cast<const CDB_VarBinary&>(m_Value).Value()), static_cast<const CDB_VarBinary&>(m_Value).Size() )); case eDB_LongBinary: return Convert(string( static_cast<const char*>(static_cast<const CDB_LongBinary&>(m_Value).Value()), static_cast<const CDB_LongBinary&>(m_Value).DataSize() )); case eDB_Text: case eDB_Image: { CDB_Stream& strm = const_cast<CDB_Stream&>(static_cast<const CDB_Stream&>(m_Value)); result.resize(strm.Size()); strm.Read(const_cast<void*>(static_cast<const void*>(result.data())), strm.Size() ); } break; case eDB_DateTime: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_DateTime&>(m_Value).Value()), std::string); case eDB_SmallDateTime: return NCBI_CONVERT_TO(ConvertSafe(static_cast<const CDB_SmallDateTime&>(m_Value).Value()), std::string); default: ReportTypeConvError(cur_type, "string"); break; } return Convert(result); }
void XtfsUtilServer::ParseAndExecute(const xtreemfs::pbrpc::UserCredentials& uc, const std::string& input_str, XCtlFile* file) { if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "xctl op: " << input_str << endl; } // Parse json input and validate. Json::Reader reader; Json::Value input; if (!reader.parse(input_str, input, false)) { file->set_last_result("{ \"error\":\"Input is not valid JSON\" }"); return; } if (!input.isObject() || !input.isMember("operation") || !input["operation"].isString()) { file->set_last_result("{ \"error\":\"Input is not valid JSON. " "Expected object with operation field.\" }"); return; } string op_name = input["operation"].asString(); Json::Value result(Json::objectValue); try { if (op_name == "getErrors") { OpGetErrors(uc, input, &result); } else if (op_name == "getattr") { OpStat(uc, input, &result); } else if (op_name == "setDefaultSP") { OpSetDefaultSP(uc, input, &result); } else if (op_name == "setDefaultRP") { OpSetDefaultRP(uc, input, &result); } else if (op_name == "setOSP") { OpSetOSP(uc, input, &result); } else if (op_name == "setRSP") { OpSetRSP(uc, input, &result); } else if (op_name == "addReplica") { OpAddReplica(uc, input, &result); } else if (op_name == "removeReplica") { OpRemoveReplica(uc, input, &result); } else if (op_name == "getSuitableOSDs") { OpGetSuitableOSDs(uc, input, &result); } else if (op_name == "setPolicyAttr") { OpSetPolicyAttr(uc, input, &result); } else if (op_name == "listPolicyAttrs") { OpListPolicyAttr(uc, input, &result); } else if (op_name == "setReplicationPolicy") { OpSetReplicationPolicy(uc, input, &result); } else if (op_name == "enableDisableSnapshots") { OpEnableDisableSnapshots(uc, input, &result); } else if (op_name == "listSnapshots") { OpListSnapshots(uc, input, &result); } else if (op_name == "createDeleteSnapshot") { OpCreateDeleteSnapshot(uc, input, &result); } else if (op_name == "setRemoveACL") { OpSetRemoveACL(uc, input, &result); } else { file->set_last_result( "{ \"error\":\"Unknown operation '" + op_name + "'.\" }\n"); return; } } catch (const XtreemFSException &e) { result["error"] = Json::Value(e.what()); } catch (const exception &e) { result["error"] = Json::Value(string("Unknown error: ") + e.what()); } Json::FastWriter writer; file->set_last_result(writer.write(result)); }
inline TO Convert_CDB_ObjectSql(const CDB_Object& value) { if (value.IsNULL()) { return TO(); } const EDB_Type cur_type = value.GetType(); switch (cur_type) { case eDB_BigInt: return NCBI_CONVERT_TO(Convert(static_cast<const CDB_BigInt&>(value).Value()), TO); case eDB_Int: return NCBI_CONVERT_TO(Convert(static_cast<const CDB_Int&>(value).Value()), TO); case eDB_SmallInt: return NCBI_CONVERT_TO(Convert(static_cast<const CDB_SmallInt&>(value).Value()), TO); case eDB_TinyInt: return NCBI_CONVERT_TO(Convert(static_cast<const CDB_TinyInt&>(value).Value()), TO); case eDB_Bit: return NCBI_CONVERT_TO(Convert(static_cast<const CDB_Bit&>(value).Value()), TO); case eDB_Float: return NCBI_CONVERT_TO(Convert(static_cast<const CDB_Float&>(value).Value()), TO); case eDB_Double: return NCBI_CONVERT_TO(Convert(static_cast<const CDB_Double&>(value).Value()), TO); case eDB_Numeric: return NCBI_CONVERT_TO(Convert(static_cast<const CDB_Numeric&>(value).Value()), TO); case eDB_Char: case eDB_VarChar: case eDB_LongChar: { const CDB_String& cdb_str = static_cast<const CDB_String&>(value); const string& str = cdb_str.AsString(); return Convert(str); } case eDB_Binary: return Convert(string( static_cast<const char*>(static_cast<const CDB_Binary&>(value).Value()), static_cast<const CDB_Binary&>(value).Size() )); case eDB_VarBinary: return Convert(string( static_cast<const char*>(static_cast<const CDB_VarBinary&>(value).Value()), static_cast<const CDB_VarBinary&>(value).Size() )); case eDB_LongBinary: return Convert(string( static_cast<const char*>(static_cast<const CDB_LongBinary&>(value).Value()), static_cast<const CDB_LongBinary&>(value).DataSize() )); case eDB_Text: case eDB_Image: { string result; CDB_Stream& strm = const_cast<CDB_Stream&>(static_cast<const CDB_Stream&>(value)); result.resize(strm.Size()); strm.Read(const_cast<void*>(static_cast<const void*>(result.data())), strm.Size() ); return Convert(result); } default: ReportTypeConvError(cur_type, "bool"); } return TO(); }
void Spice::readFile(string nome, Circuit& netlist, bool reading_cadence) { ifstream arq (nome.c_str()); string linha; if (!arq.is_open()) throw AstranError("Could not open Spice file: " + nome ); vector<string> palavras; string palavra; CellNetlst subcktCell,topCell; CellNetlst *currentCell=&topCell; topCell.setName(upcase(removeExt(getFileName(nome)))); string cellName; unsigned int lineNr=0; while (!arq.eof()){ lineNr++; getline(arq,linha); palavras.clear(); istrstream clin(linha.c_str()); while (clin>>palavra) palavras.push_back(upcase(palavra)); if (palavras.size() == 0 || palavras[0] == ".GLOBAL") continue; if (palavras[0] == "*INTERFACE"){ if(palavras.size() == 4 || palavras.size() == 6){ IOType type; direction orient; switch(palavras[2][palavras[2].size()-1]){ case 'N': orient=N; break; case 'S': orient=S; break; case 'E': orient=E; break; case 'W': orient=W; break; default: throw AstranError("Line" + intToStr(lineNr) + ": Interface orientation unknown."); } switch(palavras[3][0]){ case 'I': type=IOTYPE_INPUT; break; case 'O': type=IOTYPE_OUTPUT; break; default: throw AstranError("Line" + intToStr(lineNr) + ": Interface type unknown. Use INPUT or OUTPUT"); } topCell.insertInOut(palavras[1]); netlist.insertInterface(palavras[1], orient, type, 0, 0); } else throw AstranError("Line" + intToStr(lineNr) + ": Number of parameters for *interface is not correct"); continue; } if (reading_cadence && palavras[0] == "*" && palavras.size() == 5 && palavras[1] == "SUBCIRCUIT"){ currentCell->clear(); topCell.setName(palavras[4].substr(0,palavras[4].size()-1)); } if (palavras[0][0] == '*' || palavras[0][0] == 'C' || palavras[0][0] == '+' || palavras[0][0] == 'D' || (palavras[0][0]=='X' && reading_cadence)) // corrigir aqui para ler o '+' e ignorar os parâmetros desnecessários continue; if (palavras[0] == ".MODEL" || palavras[0] == ".END") break; if (palavras[0] == ".SUBCKT" && currentCell==&topCell && !reading_cadence){ // It's a new cell definition. . . subcktCell.clear(); currentCell=&subcktCell; cellName=palavras[1]; // compare if subcircuit name is the same as the top cell name if(cellName == topCell.getName()){ string topname = topCell.getName() + "-TOP"; topCell.setName(topname); } for (int p=2; p<palavras.size(); p++) currentCell->insertInOut(palavras[p]); } else if (palavras[0] == string(".INCLUDE")){ readFile(getPath(nome)+palavras[1],netlist,reading_cadence); // throw AstranError("Could not read included file in line: " + intToStr(lineNr)); } // declaring transistor in subcircuit read from Cadence else if (palavras[0][0] == 'M' && palavras.size()>=5){ // insert in and out pins if (reading_cadence){ for (int p=1; p<5; ++p){ if (!isNumber(palavras[p]) || palavras[p] == "0") currentCell->insertInOut(palavras[p]); } } // identify transistor type transType type; if(palavras[5]=="PMOS" || palavras[5]=="CMOSP" || palavras[5]=="MODP" || palavras[5]=="PMOS_VTL") type=PMOS; else if(palavras[5]=="NMOS" || palavras[5]=="CMOSN" || palavras[5]=="MODN" || palavras[5]=="NMOS_VTL") type=NMOS; else throw AstranError("Line" + intToStr(lineNr) + ": Parameter " + palavras[5] + " is incorrect. Use NMOS or PMOS"); // get parameters' values float length=0, width=0; for (int p=6; p<palavras.size(); p++){ int pos=palavras[p].find("="); string parm=palavras[p].substr(0,pos++); float tam=atof((palavras[p].substr(pos)).c_str())*getFactor(palavras[p][palavras[p].size()-1])*getFactor(palavras[p][palavras[p].size()-2]); if(parm=="L") length=tam; else if(parm=="W") width=tam; else if(parm!="AD" && parm!="PD" && parm!="AS" && parm!="PS" && parm!="NRD" && parm!="NRS" && parm!="M") throw AstranError("Line" + intToStr(lineNr) + ": Parameter " + parm + " not supported"); } // insert transistor in cell currentCell->insertTrans(palavras[0], palavras[1], palavras[2], palavras[3], type, length, width); } else if (palavras[0][0] == 'X' && !reading_cadence){ string instName=palavras[0]; vector<string> net_ids; int p; for (p=1; p<palavras.size()-1; p++) net_ids.push_back(palavras[p]); currentCell->insertInstance(instName, palavras[p], net_ids); } else if (currentCell==&subcktCell && palavras[0] == ".ENDS"){ currentCell->setName(cellName); netlist.insertCell(*currentCell); currentCell=&topCell; } else throw AstranError("Line" + intToStr(lineNr)); } if(topCell.getNets().size() != 0) netlist.insertCell(topCell); }
// this function should be deprecated (conflicts with C++ stdlib) char *string(const mv & obj, const char *fp /* = NULL */) { // not multithreading safe, but not fatal either. static char str[2048]; return string(obj, str, 2047, fp); }
/** * Saves the contents of the sampler * to a file. */ bool Sampler::saveGig(string path) { try { // where to store it //string path = "presets/"+name+".gig"; printf("Saving to %s\n", path.c_str()); // create a file object gig::File file; gig::Group* group = file.AddGroup(); group->Name = "Main"; file.pInfo->Name = "TEST"; // create an instrument gig::Instrument* pInstrument = file.AddInstrument(); gig::Sample* pSamples[samples.size()]; gig::Region* pRegions[samples.size()]; pInstrument->IsDrum = false; map<int,Sample*>::iterator it; int i = 0; for ( it=samples.begin() ; it != samples.end(); it++ ) { int key = (*it).first; sample = (*it).second; char chars[20]; itoa(i, chars); string name = "Sample "+ string(chars); pSamples[i] = file.AddSample(); pSamples[i]->pInfo->Name = name; pSamples[i]->Channels = 1; // mono pSamples[i]->BitDepth = 16; // 16 bits pSamples[i]->FrameSize = 16/*bitdepth*/ / 8/*1 byte are 8 bits*/ * 1/*mono*/; pSamples[i]->SamplesPerSecond = 44100; pSamples[i]->Resize(sample->length); group->AddSample(pSamples[i]); pRegions[i] = pInstrument->AddRegion(); pRegions[i]->SetSample(pSamples[i]); pRegions[i]->SetKeyRange(key, key); pRegions[i]->UnityNote = key; pRegions[i]->pDimensionRegions[0]->pSample = pSamples[i]; pRegions[i]->pDimensionRegions[0]->UnityNote = key; i++; } file.Save(path); i = 0; for ( it=samples.begin() ; it != samples.end(); it++ ) { sample = (*it).second; short int data[sample->length]; floatToPCM16(sample->data, data, sample->length); pSamples[i]->Write(data, sample->length); i++; } return true; } catch (RIFF::Exception e) { e.PrintMessage(); return false; } }
char *c_str(const mv & obj, const char *fp /* = NULL */) { return string(obj, fp); }
bool TeSQLite::insertTheme(TeAbstractTheme *theme) { errorMessage_ = ""; string sql = "INSERT INTO te_theme (layer_id, view_id, name, parent_id, priority, node_type, "; sql += "min_scale, max_scale, generate_attribute_where, generate_spatial_where, "; sql += "generate_temporal_where, collection_table, visible_rep, enable_visibility, "; sql += "lower_x, lower_y, upper_x, upper_y, creation_time) VALUES("; if(theme->type()==TeTHEME) sql += Te2String(static_cast<TeTheme*>(theme)->layerId()); else sql += " NULL "; sql += ", "; sql += Te2String(theme->view()); sql += ", '"; sql += theme->name(); sql += "', "; sql += Te2String(theme->parentId()); sql += ", "; sql += Te2String(theme->priority()); sql += ", "; sql += Te2String(theme->type()); sql += ", "; sql += Te2String(theme->minScale(), 15); sql += ", "; sql += Te2String(theme->maxScale(), 15); sql += ", '"; sql += escapeSequence(theme->attributeRest()); sql += "', '"; sql += escapeSequence(theme->spatialRest()); sql += "', '"; sql += escapeSequence(theme->temporalRest()); sql += "', '"; if(theme->type()==TeTHEME) sql += static_cast<TeTheme*>(theme)->collectionTable(); sql += "', "; sql += Te2String(theme->visibleRep()); sql += ", "; sql += Te2String(theme->visibility()); sql += ", "; sql += Te2String(theme->box().x1(), 15); sql += ", "; sql += Te2String(theme->box().y1(), 15); sql += ", "; sql += Te2String(theme->box().x2(), 15); sql += ", "; sql += Te2String(theme->box().y2(), 15); sql += ", "; TeTime creationTime = theme->getCreationTime(); sql += getSQLTime(creationTime); sql += " )"; if(this->execute(sql)) { //int newId = getMaxValue(this, "te_theme", "theme_id"); int newId = getLastInsertedSerial(); if(newId >= 0) { theme->id(newId); } } else return false; if((theme->type()==TeTHEME || theme->type()==TeEXTERNALTHEME) && static_cast<TeTheme*>(theme)->collectionTable().empty()) { sql = "UPDATE te_theme SET"; sql += " collection_table = 'te_collection_" + Te2String(theme->id()) + "'"; sql += " WHERE theme_id = "; sql += Te2String(theme->id()); static_cast<TeTheme*>(theme)->collectionTable(string("te_collection_") + Te2String(theme->id())); if(!this->execute(sql)) return false; } if(theme->parentId() == 0) { std::string sql = "UPDATE te_theme SET"; sql += " parent_id = " + Te2String(theme->id()); sql += " WHERE theme_id = "; sql += Te2String(theme->id()); theme->parentId(theme->id()); if(!this->execute(sql)) return false; } bool status; // insert grouping int numSlices = 0; if(theme->grouping().groupMode_ != TeNoGrouping) { if(!insertGrouping (theme->id(), theme->grouping())) return false; numSlices = theme->grouping().groupNumSlices_; } // insert legend theme->outOfCollectionLegend().group(-1); theme->outOfCollectionLegend().theme(theme->id()); status = insertLegend (&(theme->outOfCollectionLegend())); if (!status) return status; theme->withoutDataConnectionLegend().group(-2); theme->withoutDataConnectionLegend().theme(theme->id()); status = insertLegend (&(theme->withoutDataConnectionLegend())); if (!status) return status; theme->defaultLegend().group(-3); theme->defaultLegend().theme(theme->id()); status = insertLegend (&(theme->defaultLegend())); if (!status) return status; theme->pointingLegend().group(-4); theme->pointingLegend().theme(theme->id()); status = insertLegend (&(theme->pointingLegend())); if (!status) return status; theme->queryLegend().group(-5); theme->queryLegend().theme(theme->id()); status = insertLegend (&(theme->queryLegend())); if (!status) return status; theme->queryAndPointingLegend().group(-6); theme->queryAndPointingLegend().theme(theme->id()); status = insertLegend (&(theme->queryAndPointingLegend())); if (!status) return status; for (int i = 0; i < numSlices; i++) { theme->legend()[i].group(i); theme->legend()[i].theme(theme->id()); status = insertLegend (&(theme->legend()[i])); if (!status) return status; } if (!status) return status; //insert metadata theme if(!theme->saveMetadata(this)) return false; themeMap()[theme->id()] = theme; if(theme->type()==TeTHEME && !updateThemeTable(static_cast<TeTheme*>(theme))) return false; return true; }
list<LispToken*> LispInterpreter::lex(char* input) { list<LispToken*> tokens; long len = strlen(input); string accumulator = ""; bool inString = false; bool inChar = false; /* Loop through all input */ for(int i = 0;i <= len;i++) { /* Catches Open Parens */ if(input[i] == '(' ) { LispToken* paren = LispToken::newToken(string(input + i, 1)); tokens.push_back(paren); /* Catches Close Parens */ } else if(input[i] == ')') { if(accumulator.size()) { LispToken *token = LispToken::newToken(accumulator); tokens.push_back(token); accumulator = ""; } LispToken* paren = LispToken::newToken(string(input + i, 1)); tokens.push_back(paren); /* Special Case for Strings */ } else if(input[i] == '"') { if(inString) { accumulator += input[i]; LispToken *token = LispToken::newToken(accumulator); tokens.push_back(token); accumulator = ""; inString = false; } else { inString = true; accumulator += input[i]; } } else if(inString) { accumulator += input[i]; /* Special Case for Characters */ } else if(input[i] == 39) { if(inChar) { accumulator += input[i]; LispToken *token = LispToken::newToken(accumulator); tokens.push_back(token); accumulator = ""; inChar = false; } else if(!inString){ inChar = true; accumulator += input[i]; } } else if(inChar) { accumulator += input[i]; /* General case for symbols and numbers */ } else { /* if it is a space && the accumlator is filled create new token */ if (input[i] == ' ') { if(accumulator.size()) { LispToken *token = LispToken::newToken(accumulator); tokens.push_back(token); accumulator = ""; } /* otherwise just append to the char to the accum */ } else { accumulator += input[i]; } } } return tokens; }
/* called on a reconfig AND on initiate throws @param initial true when initiating */ void checkMembersUpForConfigChange(const ReplSetConfig& cfg, BSONObjBuilder& result, bool initial) { int failures = 0, allVotes = 0, allowableFailures = 0; int me = 0; stringstream selfs; for( vector<ReplSetConfig::MemberCfg>::const_iterator i = cfg.members.begin(); i != cfg.members.end(); i++ ) { if( i->h.isSelf() ) { me++; if( me > 1 ) selfs << ','; selfs << i->h.toString(); if( !i->potentiallyHot() ) { uasserted(13420, "initiation and reconfiguration of a replica set must be sent to a node that can become primary"); } } allVotes += i->votes; } allowableFailures = allVotes - (allVotes/2 + 1); uassert(13278, "bad config: isSelf is true for multiple hosts: " + selfs.str(), me <= 1); // dups? if( me != 1 ) { stringstream ss; ss << "can't find self in the replset config"; if( !cmdLine.isDefaultPort() ) ss << " my port: " << cmdLine.port; if( me != 0 ) ss << " found: " << me; uasserted(13279, ss.str()); } vector<string> down; for( vector<ReplSetConfig::MemberCfg>::const_iterator i = cfg.members.begin(); i != cfg.members.end(); i++ ) { // we know we're up if (i->h.isSelf()) { continue; } BSONObj res; { bool ok = false; try { int theirVersion = -1000; ok = requestHeartbeat(cfg._id, "", i->h.toString(), res, -1, theirVersion, initial/*check if empty*/); if( theirVersion >= cfg.version ) { stringstream ss; ss << "replSet member " << i->h.toString() << " has too new a config version (" << theirVersion << ") to reconfigure"; uasserted(13259, ss.str()); } } catch(DBException& e) { log() << "replSet cmufcc requestHeartbeat " << i->h.toString() << " : " << e.toString() << rsLog; } catch(...) { log() << "replSet cmufcc error exception in requestHeartbeat?" << rsLog; } if( res.getBoolField("mismatch") ) uasserted(13145, "set name does not match the set name host " + i->h.toString() + " expects"); if( *res.getStringField("set") ) { if( cfg.version <= 1 ) { // this was to be initiation, no one should be initiated already. uasserted(13256, "member " + i->h.toString() + " is already initiated"); } else { // Assure no one has a newer config. if( res["v"].Int() >= cfg.version ) { uasserted(13341, "member " + i->h.toString() + " has a config version >= to the new cfg version; cannot change config"); } } } if( !ok && !res["rs"].trueValue() ) { down.push_back(i->h.toString()); if( !res.isEmpty() ) { /* strange. got a response, but not "ok". log it. */ log() << "replSet warning " << i->h.toString() << " replied: " << res.toString() << rsLog; } bool allowFailure = false; failures += i->votes; if( !initial && failures <= allowableFailures ) { const Member* m = theReplSet->findById( i->_id ); if( m ) { verify( m->h().toString() == i->h.toString() ); } // it's okay if the down member isn't part of the config, // we might be adding a new member that isn't up yet allowFailure = true; } if( !allowFailure ) { string msg = string("need all members up to initiate, not ok : ") + i->h.toString(); if( !initial ) msg = string("need most members up to reconfigure, not ok : ") + i->h.toString(); uasserted(13144, msg); } } } if( initial ) { bool hasData = res["hasData"].Bool(); uassert(13311, "member " + i->h.toString() + " has data already, cannot initiate set. All members except initiator must be empty.", !hasData || i->h.isSelf()); } } if (down.size() > 0) { result.append("down", down); } }
bool ConfigFile::SetSource(const char* file, bool ignorecase) { /* wipe any existing settings. */ m_settings.clear(); /* open the file */ if(file != 0) { //the right mode in Windows is "rb" since '\n' is saved as 0x0D,0x0A but fopen(file,"r") reads these 2 chars //as only 1 char, so ftell(f) returns a higher value than the required by fread() to the file to buf. #ifdef WIN32 FILE* f = fopen(file, "rb"); #else FILE* f = fopen(file, "r"); #endif char* buf; int length; if(!f) { sLog.outError("Could not open %s.", file); return false; } /* get the length of the file */ fseek(f, 0, SEEK_END); length = ftell(f); buf = new char[length + 1]; fseek(f, 0, SEEK_SET); fread(buf, length, 1, f); buf[length] = '\0'; string buffer = string(buf); delete [] buf; /* close the file, it is no longer needed */ fclose(f); /* let's parse it. */ string line; string::size_type end; string::size_type offset; bool in_multiline_comment = false; bool in_multiline_quote = false; bool in_block = false; string current_setting = ""; string current_variable = ""; string current_block = ""; ConfigBlock current_block_map; ConfigSetting current_setting_struct; /* oh god this is awful */ try { for(;;) { /* grab a line. */ end = buffer.find(EOL); if(end == string::npos) { if(buffer.size() == 0) break; line = buffer; buffer.clear(); goto parse; } line = buffer.substr(0, end); buffer.erase(0, end + EOL_SIZE); goto parse; parse: if(!line.size()) continue; /* are we a comment? */ if(!in_multiline_comment && is_comment(line, &in_multiline_comment)) { /* our line is a comment. */ if(!in_multiline_comment) { /* the entire line is a comment, skip it. */ continue; } } /* handle our cases */ if(in_multiline_comment) { // we need to find a "*/". offset = line.find("*/", 0); /* skip this entire line, eh? */ if(offset == string::npos) continue; /* remove up to the end of the comment block. */ line.erase(0, offset + 2); in_multiline_comment = false; } if(in_block) { /* handle settings across multiple lines */ if(in_multiline_quote) { /* attempt to find the end of the quote block. */ offset = line.find("\""); if(offset == string::npos) { /* append the whole line to the quote. */ current_setting += line; current_setting += "\n"; continue; } /* only append part of the line to the setting. */ current_setting.append(line.c_str(), offset + 1); line.erase(0, offset + 1); /* append the setting to the config block. */ if(current_block == "" || current_variable == "") { sLog.outError("Quote without variable."); return false; } /* apply the setting */ apply_setting(current_setting, current_setting_struct); /* the setting is done, append it to the current block. */ current_block_map[ahash(current_variable)] = current_setting_struct; #ifdef _CONFIG_DEBUG sLog.outDebug("Block: '%s', Setting: '%s', Value: '%s'", current_block.c_str(), current_variable.c_str(), current_setting_struct.AsString.c_str()); #endif /* no longer doing this setting, or in a quote. */ current_setting = ""; current_variable = ""; in_multiline_quote = false; } /* remove any leading spaces */ remove_spaces(line); if(!line.size()) continue; /* our target is a *setting*. look for an '=' sign, this is our seperator. */ offset = line.find("="); if(offset != string::npos) { ASSERT(current_variable == ""); current_variable = line.substr(0, offset); /* remove any spaces from the end of the setting */ remove_all_spaces(current_variable); /* remove the directive *and* the = from the line */ line.erase(0, offset + 1); } /* look for the opening quote. this signifies the start of a setting. */ offset = line.find("\""); if(offset != string::npos) { ASSERT(current_setting == ""); ASSERT(current_variable != ""); /* try and find the ending quote */ end = line.find("\"", offset + 1); if(end != string::npos) { /* the closing quote is on the same line, oh goody. */ current_setting = line.substr(offset + 1, end - offset - 1); /* erase up to the end */ line.erase(0, end + 1); /* apply the setting */ apply_setting(current_setting, current_setting_struct); /* the setting is done, append it to the current block. */ current_block_map[ahash(current_variable)] = current_setting_struct; #ifdef _CONFIG_DEBUG sLog.outDebug("Block: '%s', Setting: '%s', Value: '%s'", current_block.c_str(), current_variable.c_str(), current_setting_struct.AsString.c_str()); #endif /* no longer doing this setting, or in a quote. */ current_setting = ""; current_variable = ""; in_multiline_quote = false; /* attempt to grab more settings from the same line. */ goto parse; } else { /* the closing quote is not on the same line. means we'll try and find it on the next. */ current_setting.append(line.c_str(), offset); /* skip to the next line. (after setting our condition first, of course :P */ in_multiline_quote = true; continue; } } /* are we at the end of the block yet? */ offset = line.find(">"); if(offset != string::npos) { line.erase(0, offset + 1); // freeeee! in_block = false; /* assign this block to the main "big" map. */ m_settings[ahash(current_block)] = current_block_map; /* erase all data for this so it doesn't seep through */ current_block_map.clear(); current_setting = ""; current_variable = ""; current_block = ""; } } else { /* we're not in a block. look for the start of one. */ offset = line.find("<"); if(offset != string::npos) { in_block = true; /* whee, a block! let's cut the string and re-parse. */ line.erase(0, offset + 1); /* find the name of the block first, though. */ offset = line.find(" "); if(offset != string::npos) { current_block = line.substr(0, offset); line.erase(0, offset + 1); } else { sLog.outError("Block without name."); return false; } /* skip back */ goto parse; } } } } catch(...) { sLog.outError("Exception in config parsing."); return false; } /* handle any errors */ if(in_block) { sLog.outError("Unterminated block."); return false; } if(in_multiline_comment) { sLog.outError("Unterminated comment."); return false; } if(in_multiline_quote) { sLog.outError("Unterminated quote."); return false; } /* we're all good :) */ return true; } return false; }
bool SFXDebugger::property(unsigned id, string &name, string &value) { unsigned n = 0; #define item(name_, value_) \ if(id == n++) { \ name = name_; \ value = value_; \ return true; \ } item("$3000-$301f", "") for (int i = 0; i < 16; i++) { item(string("Register R", i), string("0x", hex<4>(regs.r[i]))) } item("$3030", "") item("Status Flag Register (SFR)", string("0x", hex<4>(regs.sfr))) item("$3033", "") item("Backup RAM Register (BRAMR)", string("0x", hex<2>(regs.bramr))) item("$3034", "") item("Program Bank Register", string("0x", hex<2>(regs.pbr))) item("$3037", "") item("Multiplier Speed", (regs.cfgr & 0x20) ? "High Speed" : "Normal") item("IRQ Enable", (regs.cfgr & 0x80) ? "Disabled" : "Enabled") item("$3038", "") item("Screen Base Register (SCBR)", string("0x", hex<2>(regs.scbr))) item("$3039", "") item("Clock Register (CLSR)", regs.clsr.divider > 1 ? "21.4 MHz" : "10.7 MHz") item("$303a", "") string md, ht; switch (regs.scmr & 0x3) { case 0: md = "4 colors"; break; case 1: md = "16 colors"; break; case 2: md = "Invalid"; break; case 3: md = "256 colors"; break; } if (regs.por & 0x10) { ht = "OBJ mode"; } else switch (regs.scmr & 0x24) { case 0x00: ht = "128 pixels"; break; case 0x04: ht = "160 pixels"; break; case 0x20: ht = "192 pixels"; break; case 0x24: ht = "OBJ mode"; break; } item("Color Mode", md) item("Screen Height", ht); item("Game Pak WRAM Access", (regs.scmr & 0x8) ? "Super FX" : "SNES") item("Game Pak ROM Access", (regs.scmr & 0x10) ? "Super FX" : "SNES") item("$303b", "") item("Version Register (VCR)", string("0x", hex<2>(regs.vcr))) item("$303c", "") item("Game Pak RAM Bank", regs.rambr ? "0x71" : "0x70") item("$303e-$303f", "") item("Cache Base Register (CBR)", string("0x", hex<4>(regs.cbr))) item("", "") item("Color Data", string(regs.colr, " (0x", hex<2>(regs.colr), ")")) item("Plot Transparent", (regs.por & 0x1) ? "Disabled" : "Enabled") item("Plot Dither", (regs.por & 0x2) ? "Enabled" : "Disabled") item("COLOR/GETC High Nibble", (regs.por & 0x4) ? "Enabled" : "Disabled") item("COLOR/GETC Freeze High", (regs.por & 0x8) ? "Enabled" : "Disabled") #undef item return false; }
void BucketsMaker::doWork() { int r = rand_r(&m_randSeed); r = r % (int)m_sleepMs(); bool buckets_empty; string first_bucket; { boost::lock_guard<boost::mutex> lock(g_data.m_mutex); buckets_empty = g_data.m_buckets.empty(); if (!buckets_empty) { first_bucket = g_data.m_buckets.begin()->first; } } if (r < m_multipliyer() * m_reconnectProbability()) { m_sock->disconnect(); sleepMs(20); m_sock->connect("localhost", m_port); } int prob = m_multipliyer() * m_addProbability(); if (r < prob || buckets_empty) { // Add bucket int nextId = g_data.m_maxBucketId + 1; string bucket = string("buck_") + boost::lexical_cast<string>(nextId); string cmd = string("add ") + bucket; execCommand(*m_sock, cmd, *m_buffer); if (strcmp(m_buffer->raw(), "ok") == 0) { boost::lock_guard<boost::mutex> lock(g_data.m_mutex); ItemsListPtr items(new list<int>); g_data.m_buckets[bucket] = items; g_data.m_maxBucketId = nextId; } else { cout << "Failed to add bucket: " << m_buffer->raw() << endl; } return; } prob += m_multipliyer() * m_deleteProbability(); if (r < prob && !buckets_empty) { // Delete bucket string cmd = string("drop ") + first_bucket; execCommand(*m_sock, cmd, *m_buffer); if (strcmp(m_buffer->raw(), "ok") == 0) { boost::lock_guard<boost::mutex> lock(g_data.m_mutex); g_data.m_buckets.erase(g_data.m_buckets.begin()); } else { cout << "Failed to delete bucket: " << m_buffer->raw() << endl; } return; } prob += m_multipliyer() * m_listProbability(); if (r < prob) { // List buckets string cmd = "list"; execCommand(*m_sock, cmd, *m_buffer); return; } prob += m_multipliyer() * m_invalidProbability(); if (r < prob) { // Invalid command string cmd = "invalid command"; execCommand(*m_sock, cmd, *m_buffer); return; } }