void InstanceSaveManager::_DelHelper(DatabaseType &db, const char *fields, const char *table, const char *queryTail,...) { Tokens fieldTokens = StrSplit(fields, ", "); ASSERT(fieldTokens.size() != 0); va_list ap; char szQueryTail [MAX_QUERY_LEN]; va_start(ap, queryTail); vsnprintf( szQueryTail, MAX_QUERY_LEN, queryTail, ap ); va_end(ap); QueryResult *result = db.PQuery("SELECT %s FROM %s %s", fields, table, szQueryTail); if(result) { do { Field *fields = result->Fetch(); std::ostringstream ss; for(size_t i = 0; i < fieldTokens.size(); i++) { std::string fieldValue = fields[i].GetCppString(); db.escape_string(fieldValue); ss << (i != 0 ? " AND " : "") << fieldTokens[i] << " = '" << fieldValue << "'"; } db.DirectPExecute("DELETE FROM %s WHERE %s", table, ss.str().c_str()); } while (result->NextRow()); delete result; } }
void ListDataspacesCommand::parse(Tokens& tokens) { if (tokens.size() > 2) { if ((tokens.size() != 4) || !checkString(tokens[2], "filter") || (tokens[3].m_angen != ANGEN_TITLE)) THROW("Invalid format of LIST DATASPACES command"); m_pattern = tokens[3].m_val.m_str; } }
void Player::_LoadArchaeology(QueryResult* result) { for (uint8 i = 0; i < MAX_RESEARCH_SITES; ++i) _digSites[i].count = 0; if (!sWorld.getConfig(CONFIG_BOOL_ARCHAEOLOGY_ENABLED)) { delete result; return; } if (!result) { GenerateResearchSites(); GenerateResearchProjects(); return; } Field* fields = result->Fetch(); // Loading current zones Tokens tokens = Tokens(fields[0].GetCppString(), ' '); if (tokens.size() != 0 && tokens.size() <= MAX_RESEARCH_SITES) { _researchSites.clear(); for (uint8 i = 0; i < tokens.size(); ++i) _researchSites.insert(uint32(atoi(tokens[i]))); } else GenerateResearchSites(); // Loading current zone info tokens = Tokens(fields[1].GetCppString(), ' '); if (tokens.size() == MAX_RESEARCH_SITES) { for (uint8 i = 0; i < MAX_RESEARCH_SITES; ++i) _digSites[i].count = uint32(atoi(tokens[i])); } // Loading current projects tokens = Tokens(fields[2].GetCppString(), ' '); if (tokens.size() == MAX_RESEARCH_PROJECTS) { for (uint8 i = 0; i < MAX_RESEARCH_PROJECTS; ++i) if (ResearchProjectEntry const* entry = sResearchProjectStore.LookupEntry(atoi(tokens[i]))) if (entry->IsVaid()) ReplaceResearchProject(0, entry->ID); } else GenerateResearchProjects(); delete result; }
/// Check if the string is a valid ip address representation bool IsIPAddress(char const* ipaddress) { if(!ipaddress) return false; // FG: support IP ranges to be valid IP addresses, e.g. 192.168.0.%, 127.%.%.%, 1.2.3.4 Tokens tok = StrSplit(ipaddress, "."); if(tok.size() != 4) return false; for(Tokens::iterator it = tok.begin(); it != tok.end(); it++) { // must not be empty and not more then 3 chars per part if(it->empty() || it->size() > 3) return false; // must contain digits only or % (mysql wildcard) for(uint32 pos = 0; pos < it->size(); ++pos) if( !(isdigit((*it)[pos]) ||(*it)[pos] == '%') ) return false; // if its a number, it must be < 255 to be valid ip part if(atoi(it->c_str()) >= 255) return false; } return true; // -end- // Let the big boys do it. // Drawback: all valid ip address formats are recognized e.g.: 12.23,121234,0xABCD) //return ACE_OS::inet_addr(ipaddress) != INADDR_NONE; }
float HttpContentNegociation::GetQuality(const Tokens& parameters) { for (size_t i = 1; i < parameters.size(); i++) { std::string key, value; if (SplitPair(key, value, parameters[i], '=') && key == "q") { float quality; bool ok = false; try { quality = boost::lexical_cast<float>(value); ok = (quality >= 0.0f && quality <= 1.0f); } catch (boost::bad_lexical_cast&) { } if (ok) { return quality; } else { LOG(ERROR) << "Quality parameter out of range in a HTTP request (must be between 0 and 1): " << value; throw OrthancException(ErrorCode_BadRequest); } } } return 1.0f; // Default quality }
virtual void init(Tokens& params) { if (params.size() == 0) return; if (params.size() != 1) THROW("Function MEAN() expects only one argument"); if (params[0].m_angen != ANGEN_LONG) THROW("Function MEAN() expects one integer argument"); if (params[0].m_val.m_long <= 0) THROW("Invalid argument for function MEAN()"); m_maxSize = (size_t) params[0].m_val.m_long; }
uint32 GetUInt32ValueFromArray(Tokens const& data, uint16 index) { if (index >= data.size()) return 0; return (uint32)atoi(data[index].c_str()); }
bool FileWorker::savePacket(const Token& name, const Tokens& formats, const Token& fileName) { xml_document doc; xml_parse_result result = doc.load_file(fileName.c_str()); if (result || result.status == pugi::status_file_not_found) { xml_node packetNode = doc.append_child("packet"); packetNode.append_attribute("name") = name.c_str(); for (size_t i = 0; i < formats.size(); ++i) { if (Utilities::startsWith(formats[i], ETH2PROTO)) packetNode.append_attribute(ETH2PROTO.c_str()) = formats[i].c_str(); else if (Utilities::startsWith(formats[i], IPV4PROTO)) packetNode.append_attribute(IPV4PROTO.c_str()) = formats[i].c_str(); else if (Utilities::startsWith(formats[i], UDPPROTO)) packetNode.append_attribute(UDPPROTO.c_str()) = formats[i].c_str(); else if (Utilities::startsWith(formats[i], TCPPROTO)) packetNode.append_attribute(TCPPROTO.c_str()) = formats[i].c_str(); else if (Utilities::startsWith(formats[i], ICMPPROTO)) packetNode.append_attribute(ICMPPROTO.c_str()) = formats[i].c_str(); //else //return false; } return doc.save_file(fileName.c_str()); } else { setGlobalError(string("Packets file: error while open XML").append(result.description())); DbgMsg(__FILE__, __LINE__, "Device::loadPacket() load_file() ERROR:\n"); DbgMsg(__FILE__, __LINE__, "Description: %s\n", result.description()); DbgMsg(__FILE__, __LINE__, "Error offset: %s\n", result.offset); return false; } }
Instructions Bytecode::parser(const Tokens& tokens) const { Tokens tokens_group; // Abstract syntax tree. Instructions ast; int funcs = 0, params = 0, specs = 0; for (int i = 0; i < tokens.size(); i++) { if (tokens[i].type == DELIMITER) { checkFunctions(tokens_group[0], funcs); checkById(tokens_group[0].function_id, params, specs); Instruction inst = makeInstruction(params, specs, tokens_group); ast.push_back(inst); funcs = 0, params = 0, specs = 0; tokens_group.clear(); } else { if (tokens[i].type == FUNCTION) { funcs++; } else if (tokens[i].type == PARAMETER) { params++; } else { specs++; } tokens_group.push_back(tokens[i]); } } return ast; }
static const Token tokenAtPosition(const Tokens &tokens, const unsigned pos) { for (int i = tokens.size() - 1; i >= 0; --i) { const Token tk = tokens.at(i); if (pos >= tk.utf16charsBegin() && pos < tk.utf16charsEnd()) return tk; } return Token(); }
//static void Command::parseDump( Tokens& tokens, bool helpMode, Command*& result ) { if (tokens.size() < 3 && !helpMode) THROW( CWDB_ERR_PARSER, "Bad syntax: missing options in \"dump\" command" ); switch( checkAngen( tokens, 1) ) { case ANGEN_COLLECTION: result = new DumpCollectionCommand; break; default: THROW( CWDB_ERR_PARSER, "Bad syntax: unrecognized option in \"dump\" command" ); } if (result != 0 && !helpMode) result->parse( tokens ); }
void RenameMetricCommand::parse(Tokens& tokens) { if (tokens.size() != 5) THROW("Invalid RENAME METRIC command"); if (tokens[2].m_angen != ANGEN_IDENT) THROW("Expected existing metric name"); m_oldName = tokens[2].m_val.m_str; if (!checkString(tokens[3], "to")) THROW("Expected key word TO"); if (tokens[4].m_angen != ANGEN_IDENT) THROW("Expected new metric name"); m_newName = tokens[4].m_val.m_str; }
void RenameDataspaceCommand::parse(Tokens& tokens) { if (tokens.size() != 5) THROW("Invalid RENAME DATASPACE command"); if (tokens[2].m_angen != ANGEN_IDENT) THROW("Expected existing dataspace name"); m_oldName = tokens[2].m_val.m_str; if (!checkString(tokens[3], "to")) THROW("Expected key word TO"); if (tokens[4].m_angen != ANGEN_IDENT) THROW("Expected new dataspace name"); m_newName = tokens[4].m_val.m_str; }
Token *TokenManager::getTokenByBase(Token *base, int offset) { Tokens *tks = this->tokens; size_t size = tks->size(); int wanted_idx = -1; for (size_t i = 0; i < size; i++) { if (tks->at(i) == base) { wanted_idx = i + offset; } } return (0 <= wanted_idx && (size_t)wanted_idx < size) ? tks->at(wanted_idx) : NULL; }
//static void Command::parseDrop( Tokens& tokens, bool helpMode, Command*& result ) { if (tokens.size() < 3 && !helpMode) THROW( CWDB_ERR_PARSER, "Bad syntax: missing options in \"drop\" command" ); switch( checkAngen( tokens, 1) ) { case ANGEN_DATASPACE: result = new DropDataspaceCommand; break; case ANGEN_COLLECTION: result = new DropCollectionCommand; break; case ANGEN_METRIC: result = new DropMetricCommand; break; default: THROW( CWDB_ERR_PARSER, "Bad syntax: unrecongized option in \"drop\" command" ); } if (result != 0 && !helpMode) result->parse( tokens ); }
void ShowMetricCommand::parse(Tokens& tokens) { if (tokens.size() < 3 || tokens[2].m_angen != ANGEN_IDENT) THROW("Invalid SHOW METRIC command"); m_name = tokens[2].m_val.m_str; if (tokens.size() <= 3) return; map< string, int > attrs; parseAttributesIndex(tokens, 3, attrs); map< string, int >::iterator iter = attrs.begin(); for ( ; iter != attrs.end(); ++iter) { int index = iter->second; if (boost::iequals(iter->first, "format")) { if (tokens[index].m_angen != ANGEN_IDENT) THROW("Expected time format identifier"); if (checkString(tokens[index], "epoch")) m_epochTime = 1; else if (checkString(tokens[index], "iso")) m_epochTime = -1; else THROW(string("Invalid value for format. Epxected epoch or iso")); } else if (boost::iequals(iter->first, "local")) { if (tokens[index].m_angen != ANGEN_IDENT) THROW("Expected time local true/false"); if (checkString(tokens[index], "true")) m_localTime = 1; else if (checkString(tokens[index], "false")) m_localTime = -1; else THROW(string("Invalid value for local. Expected true or false")); } else { THROW(string("Unexpected attribute ")+iter->first+" in show command"); } } }
//static void Command::parseDescr( Tokens& tokens, bool helpMode, Command*& result ) { if (tokens.size() == 1) { result = new DescrCommand(); return; } switch( checkAngen( tokens, 1) ) { case ANGEN_DATASPACE: result = new DescrDataspaceCommand; break; case ANGEN_COLLECTION: result = new DescrCollectionCommand; break; case ANGEN_METRIC: result = new DescrMetricCommand; break; default: THROW( CWDB_ERR_PARSER, "Bad syntax: unrecognized option in \"descr\" command" ); } if (result != 0 && !helpMode) result->parse( tokens ); }
bool HttpContentNegociation::Apply(const std::string& accept) { // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1 // https://en.wikipedia.org/wiki/Content_negotiation // http://www.newmediacampaigns.com/blog/browser-rest-http-accept-headers Tokens mediaRanges; Toolbox::TokenizeString(mediaRanges, accept, ','); std::auto_ptr<Reference> bestMatch; for (Tokens::const_iterator it = mediaRanges.begin(); it != mediaRanges.end(); ++it) { Tokens parameters; Toolbox::TokenizeString(parameters, *it, ';'); if (parameters.size() > 0) { float quality = GetQuality(parameters); std::string type, subtype; if (SplitPair(type, subtype, parameters[0], '/')) { for (Handlers::const_iterator it2 = handlers_.begin(); it2 != handlers_.end(); ++it2) { if (it2->IsMatch(type, subtype)) { SelectBestMatch(bestMatch, *it2, type, subtype, quality); } } } } } if (bestMatch.get() == NULL) // No match was found { return false; } else { bestMatch->handler_.Call(); return true; } }
//static void Command::parseCreate( Tokens& tokens, bool helpMode, Command*& result ) { if (tokens.size() < 3 && !helpMode) THROW( CWDB_ERR_PARSER, "Bad syntax: missing options in \"create\" command" ); switch( checkAngen(tokens, 1) ) { case ANGEN_DATASPACE: result = new CreateDataspaceCommand; break; case ANGEN_COLLECTION: result = new CreateCollectionCommand; break; case ANGEN_METRIC: result = new CreateMetricCommand; break; /****************** if (tokens.size() < 3 && !helpMode) THROW( CWDB_ERR_PARSER, "Bad syntax: missing options in \"create metric\" command" ); if (checkAngen( tokens, 3) == ANGEN_ASSIGN && !helpMode) result = new CreateAggregationCommand; else result = new CreateMetricCommand; break; *******************/ default: THROW( CWDB_ERR_PARSER, "Bad syntax: unrecognized option in \"create\" command" ); } if (result != 0 && !helpMode) result->parse( tokens ); }
//static void Command::parseUpdate( Tokens& tokens, bool helpMode, Command*& result ) { if (tokens.size() < 3 && !helpMode) THROW( CWDB_ERR_PARSER, "Bad syntax: missing options in \"update\" command" ); CreateUpdateMode mode; tokens.erase( tokens.begin() ); if ( checkString( tokens.front(), "or") ) { if (tokens[1].m_angen != ANGEN_CREATE) THROW( CWDB_ERR_PARSER, "Bad syntax: expected keyword \"create\"" ); tokens.erase( tokens.begin() ); mode = CRM_CREATE_UPDATE; } else { Token dummy; dummy.m_angen = ANGEN_CREATE; tokens.insert( tokens.begin(), dummy ); mode = CRM_UPDATE; } switch( checkAngen(tokens, 1) ) { case ANGEN_DATASPACE: result = new CreateDataspaceCommand( mode ); break; case ANGEN_COLLECTION: result = new CreateCollectionCommand( mode ); break; case ANGEN_METRIC: result = new CreateMetricCommand( mode ); break; /************************* if (tokens.size() < 3 && !helpMode) THROW( CWDB_ERR_PARSER, "Bad syntax: missing options in \"create metric\" command" ); if (checkAngen( tokens, 3) == ANGEN_ASSIGN && !helpMode) result = new CreateAggregationCommand( mode ); else result = new CreateMetricCommand( mode ); break; **************************/ default: THROW( CWDB_ERR_PARSER, "Bad syntax: unrecognized option in \"create\" command" ); } if (result != 0 && !helpMode) { result->parse( tokens ); } }
void Sentence::tokenize() { Tokens tokens; ::tokenize(sent_,tokens); int i,n = tokens.size(); Syllable sy; sy.span = 1; sy.sent_ = this; sy.start = 0; for (i = 0;i < n;i ++) { if (tokens[i].is_token) { /* char *viet_token = viet_to_viscii(tokens[i].value.c_str()); if (!viet_token) { sy.id = get_sarch()[tokens[i].value]; sy.cid = get_sarch()[string("6")+tokens[i].value]; syllables.push_back(sy); } else { */ const char *viet_token = tokens[i].value.c_str(); int jj,nn = strlen(viet_token); for (jj = 0;jj < nn;jj ++) if (viet_isalpha((unsigned char)viet_token[jj]) || viet_isdigit((unsigned char)viet_token[jj])) { string s = viet_token; sy.id = get_ngram()[s]; sy.cid = get_ngram()[get_std_syllable(s)]; syllables.push_back(sy); break; } /*}*/ } sy.start += tokens[i].value.size(); } }
void sentences_split(const string &_input,vector<string> &output) { Tokens tokens; ::tokenize(_input,tokens); int i,n = tokens.size(); string str; bool flush = false; for (i = 0;i < n;i ++) { if (tokens[i].is_token) { int jj,nn = tokens[i].value.size(); if (nn == 1 && strchr("?!()[];:.,",tokens[i].value[0])) flush = true; else if (flush) { output.push_back(str); str = ""; flush = false; } } str += tokens[i].value; } if (!str.empty()) output.push_back(str); /* // candidates are ? ! . // . is ambiguous string input = _input; int npos,pos = 0,len; bool run = true; bool split = false; while (run && !input.empty()) { if (split) { output.push_back(input.substr(0,npos+1)); input.erase(0,npos+1); pos = 0; split = false; } npos = input.find_first_of("?!.",pos); if (npos == string::npos) break; len = input.size(); if (!(npos + 1 < len)) break; if (input[npos+1] != ' ') continue; if (!(npos + 2 < len)) break; if (viet_isupper(input[npos+2])) { split = true; continue; } pos = npos+1; } if (!input.empty()) output.push_back(input); */ }
bool Item::LoadFromDB(uint32 guid, uint64 owner_guid, QueryResult_AutoPtr result, uint32 entry) { // 0 1 2 3 4 5 6 7 8 9 10 //result = CharacterDatabase.PQuery("SELECT creatorGuid, giftCreatorGuid, count, duration, charges, flags, enchantments, randomPropertyId, durability, playedTime, text FROM item_instance WHERE guid = '%u'", guid); // create item before any checks for store correct guid // and allow use "FSetState(ITEM_REMOVED); SaveToDB();" for deleting item from DB Object::_Create(guid, 0, HIGHGUID_ITEM); // Set entry, MUST be before proto check SetEntry(entry); SetFloatValue(OBJECT_FIELD_SCALE_X, 1.0f); ItemPrototype const* proto = GetProto(); if (!proto) return false; if (!result) { sLog.outError("Item (GUID: %u owner: %u) not found in table `item_instance`, can't load. ", guid, GUID_LOPART(owner_guid)); return false; } // set owner (not if item is only loaded for gbank/auction/mail if (owner_guid != 0) SetOwnerGUID(owner_guid); Field *fields = result->Fetch(); bool need_save = false; // need explicit save data at load fixes SetUInt64Value(ITEM_FIELD_CREATOR, MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER)); SetUInt64Value(ITEM_FIELD_GIFTCREATOR, MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_PLAYER)); SetCount(fields[2].GetUInt32()); uint32 duration = fields[3].GetUInt32(); SetUInt32Value(ITEM_FIELD_DURATION, duration); // update duration if need, and remove if not need if ((proto->Duration == 0) != (duration == 0)) { SetUInt32Value(ITEM_FIELD_DURATION, abs(proto->Duration)); need_save = true; } Tokens tokens = StrSplit(fields[4].GetCppString(), " "); if (tokens.size() == MAX_ITEM_PROTO_SPELLS) for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) SetSpellCharges(i, atoi(tokens[i].c_str())); SetUInt32Value(ITEM_FIELD_FLAGS, fields[5].GetUInt32()); // Remove bind flag for items vs NO_BIND set if (IsSoulBound() && proto->Bonding == NO_BIND) { ApplyModFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_BINDED, false); need_save = true; } _LoadIntoDataField(fields[6].GetString(), ITEM_FIELD_ENCHANTMENT_1_1, MAX_ENCHANTMENT_SLOT * MAX_ENCHANTMENT_OFFSET); SetInt32Value(ITEM_FIELD_RANDOM_PROPERTIES_ID, fields[7].GetInt32()); // recalculate suffix factor if (GetItemRandomPropertyId() < 0) UpdateItemSuffixFactor(); uint32 durability = fields[8].GetUInt32(); SetUInt32Value(ITEM_FIELD_DURABILITY, durability); // update max durability (and durability) if need SetUInt32Value(ITEM_FIELD_MAXDURABILITY, proto->MaxDurability); if (durability > proto->MaxDurability) { SetUInt32Value(ITEM_FIELD_DURABILITY, proto->MaxDurability); need_save = true; } SetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME, fields[9].GetUInt32()); SetText(fields[10].GetCppString()); if (need_save) // normal item changed state set not work at loading { std::ostringstream ss; ss << "UPDATE item_instance SET duration = " << GetUInt32Value(ITEM_FIELD_DURABILITY) << ", flags = " << GetUInt32Value(ITEM_FIELD_FLAGS) << ", durability = " << GetUInt32Value(ITEM_FIELD_DURABILITY) << " WHERE guid = " << guid; CharacterDatabase.Execute(ss.str().c_str()); } return true; }
void DropDataspaceCommand::parse(Tokens& tokens) { if (tokens.size() != 3 || tokens[2].m_angen != ANGEN_IDENT) THROW("Invalid DROP DATASPACE command"); m_name = tokens[2].m_val.m_str; }
void CreateDataspaceCommand::parse(Tokens& tokens) { if (tokens.size() < 3 || tokens[2].m_angen != ANGEN_IDENT) THROW("Invalid CREATE DATASPACE command"); m_name = tokens[2].m_val.m_str; if (tokens.size() > 3) parseAttributes(tokens, 3, m_attrs); }
virtual void init(Tokens& params) { if (params.size() != 1) THROW("Invalid number of parameters in SMOOTH()"); if (params[0].m_angen != ANGEN_LONG) THROW("Parameter of SMOOTH must be an integer"); if (params[0].m_val.m_long < 2) THROW("Invalid parameter value in SMOOTH()"); m_count = (size_t) params[0].m_val.m_long; }
\ REQUIRE(actualOutput.size() == 5); \ REQUIRE(expectedOutput == actualOutput); \ } TEST_CASE("InfixToPostfixConvertor", "[infixtopostfixconvertor]") { SECTION("simple infix to postfix conversion") { Token t1(5), t2(OpBinary::OP_ADD), t3(3); Tokens input = { t1, t2, t3 }; Tokens expectedOutput { t1, t3, t2 }; Tokens actualOutput = InfixToPostfixConvertor::convert(input); REQUIRE(actualOutput.size() == 3); REQUIRE(expectedOutput == actualOutput); } HAS_HIGHER_PRECENDENCE(OP_MULTIPLY, OP_ADD) HAS_HIGHER_PRECENDENCE(OP_MULTIPLY, OP_SUBSTRACT) HAS_HIGHER_PRECENDENCE(OP_DIVIDE, OP_ADD) HAS_HIGHER_PRECENDENCE(OP_DIVIDE, OP_SUBSTRACT) HAS_HIGHER_PRECENDENCE(OP_POWER, OP_ADD) HAS_HIGHER_PRECENDENCE(OP_POWER, OP_SUBSTRACT) HAS_HIGHER_PRECENDENCE(OP_POWER, OP_MULTIPLY) HAS_HIGHER_PRECENDENCE(OP_POWER, OP_DIVIDE) HAS_HIGHER_PRECENDENCE(OP_POWER, OP_MODULO)
Rows::Rows(std::string filename){ std::string line; std::ifstream file (filename.c_str()); if (file.is_open()){ Tokens names; Tokens types; // read column lines bool cont = true; if ( getline (file, line) ){ names = tokenize(line); }else{ cont = false; }; if ( cont && getline (file, line) ){ types = tokenize(line); ColInfo ci; // uninitialized memory int l = std::min(names.size(), types.size()); int i = 0; for (i = 0; i < l; ++i){ // some helpful debug msgs //std::cout << names[i] << ": " << types[i] << "\n"; ci.pos = i; ci.name = names[i]; ci.type = typeIdByName(types[i]); this->header.insert(ColsByName::value_type(ci.name, ci)); this->headerByPos.push_back(ci); }; }else{ cont = false; }; // read all the lines if ( cont ) { while ( getline (file, line) ) { Tokens values = tokenize(line); Row row; int l = std::min(values.size(), this->headerByPos.size()); int i = 0; for (i = 0; i < l; ++i){ // this could maybe move to types.h as well or better a seperate file // but for 2 types its alright here // still easy to maintain if (this->headerByPos[i].type == cTypeInt){ // int // convert string to int int value = atoi( values[i].c_str() ); row.push_back(value); // potentially a little slow }else{ // string // we do not wanna save strings in out data structure // they are slow and they are huge int value = getStringAlias(values[i]); row.push_back(value); // potentially a little slow }; }; this->rowData.push_back(row); // potentially very slow }; }; file.close(); } else { std::cout << "Unable to open file"; }; };
// read a file with queries // parse the queries // and output to file as well as stdout void analyze(Indexed* indexed, std::string queryFilename, std::string outputFilename){ std::string line; std::ifstream queryfile(queryFilename.c_str()); std::ofstream outputfile(outputFilename.c_str()); if (!outputfile.is_open()){ std::cout << "could not open output file\n"; return; }; const Rows* rows = indexed->rows; if (queryfile.is_open()){ // read all the lines while ( getline (queryfile, line) ) { Tokens t = tokenize(line); bool valid = true; if (t.size() < 3){ valid = false; }; int colNum1 = 0; int colType1 = 0; int colNum2 = 0; if (valid){ ColsByName::const_iterator colIt = rows->header.find(t[1]); if (colIt == rows->header.end()){ std::cout << "column: " << t[1] << " not found!\n"; valid = false; }else{ colNum2 = colIt->second.pos; if (!typeCanAggregate(colIt->second.type)){ std::cout << "can not perform: " << t[0] << " over " << t[1] << " of type " << typeName(colIt->second.type) << "\n"; valid = false; }; }; colIt = rows->header.find(t[2]); if (colIt == rows->header.end()){ std::cout << "column: " << t[2] << " not found!\n"; valid = false; }else{ colNum1 = colIt->second.pos; colType1 = colIt->second.type; }; }; if (valid){ // output to file and std out std::cout << t[0] << " " << t[1] << " GROUPED BY " << t[2] << "\n"; outputfile << t[0] << " " << t[1] << " GROUPED BY " << t[2] << "\n"; if (t[0] == "AVG"){ doAvg(indexed, colNum1, colNum2, colType1, outputfile); }else if (t[0] == "MIN"){ doMin(indexed, colNum1, colNum2, colType1, outputfile); }else if (t[0] == "MAX"){ doMax(indexed, colNum1, colNum2, colType1, outputfile); }else{ std::cout << "unknown aggregate function: " << t[0] << "\n"; }; // new line std::cout << "\n"; outputfile << "\n"; }; }; }; outputfile.close(); };
void DisableMgr::LoadDisables() { // reload case for (DisableMap::iterator itr = m_DisableMap.begin(); itr != m_DisableMap.end(); ++itr) itr->second.clear(); m_DisableMap.clear(); QueryResult_AutoPtr result = WorldDatabase.Query("SELECT sourceType,entry,flags,params_0,params_1 FROM disables"); uint32 total_count = 0; if (!result) { sLog.outString(">> Loaded %u disables", total_count); return; } Field* fields; do { fields = result->Fetch(); DisableType type = DisableType(fields[0].GetUInt32()); if (uint32(type) >= MAX_DISABLE_TYPES) { sLog.outErrorDb("Invalid type %u specified in `disables` table, skipped.", type); continue; } uint32 entry = fields[1].GetUInt32(); uint8 flags = fields[2].GetUInt8(); std::string params_0 = fields[3].GetString(); std::string params_1 = fields[4].GetString(); DisableData data; data.flags = flags; switch (type) { case DISABLE_TYPE_SPELL: { if (!(sSpellStore.LookupEntry(entry) || flags & SPELL_DISABLE_DEPRECATED_SPELL)) { sLog.outErrorDb("Spell entry %u from `disables` doesn't exist in dbc, skipped.", entry); continue; } if (!flags || flags > MAX_SPELL_DISABLE_TYPE) { sLog.outErrorDb("Disable flags for spell %u are invalid, skipped.", entry); continue; } if (flags & SPELL_DISABLE_MAP) { Tokens tokens = StrSplit(params_0, ","); for (uint8 i = 0; i < tokens.size(); ) data.params[0].insert(atoi(tokens[i++].c_str())); } if (flags & SPELL_DISABLE_AREA) { Tokens tokens = StrSplit(params_1, ","); for (uint8 i = 0; i < tokens.size(); ) data.params[1].insert(atoi(tokens[i++].c_str())); } } break; // checked later case DISABLE_TYPE_QUEST: break; case DISABLE_TYPE_MAP: { MapEntry const* mapEntry = sMapStore.LookupEntry(entry); if (!mapEntry) { sLog.outErrorDb("Map entry %u from `disables` doesn't exist in dbc, skipped.", entry); continue; } bool isFlagInvalid = false; switch (mapEntry->map_type) { case MAP_COMMON: if (flags) isFlagInvalid = true; break; case MAP_INSTANCE: case MAP_RAID: if (flags & DUNGEON_STATUSFLAG_NORMAL && !mapEntry->IsDungeon()) isFlagInvalid = true; if (flags & DUNGEON_STATUSFLAG_HEROIC && !mapEntry->SupportsHeroicMode()) isFlagInvalid = true; else if (flags & RAID_STATUSFLAG_10MAN && !mapEntry->IsRaid()) isFlagInvalid = true; else if (flags & RAID_STATUSFLAG_25MAN && !mapEntry->IsRaid()) isFlagInvalid = true; break; case MAP_BATTLEGROUND: case MAP_ARENA: sLog.outErrorDb("Battleground map %u specified to be disabled in map case, skipped.", entry); continue; } if (isFlagInvalid) { sLog.outErrorDb("Disable flags for map %u are invalid, skipped.", entry); continue; } break; } case DISABLE_TYPE_BATTLEGROUND: if (!sBattlemasterListStore.LookupEntry(entry)) { sLog.outErrorDb("Battleground entry %u from `disables` doesn't exist in dbc, skipped.", entry); continue; } if (flags) sLog.outErrorDb("Disable flags specified for battleground %u, useless data.", entry); break; } m_DisableMap[type].insert(DisableTypeMap::value_type(entry, data)); ++total_count; } while (result->NextRow()); sLog.outString(">> Loaded %u disables.", total_count); }