void CFileReplaceMap::LoadReplaceFile(const string& filename, bool bReplaceExistingOnes) { if (bReplaceExistingOnes) { if (!m_replace_map.empty()) { m_replace_map.clear(); OUTPUT_LOG("all replacement files are cleared.\n"); } } if(filename.empty()) return; string::size_type nCommaPos = filename.find(","); if( nCommaPos!= string::npos) { // if filename contains ",", we will simply replace the two specified file separated by comma. string sFromFile = filename.substr(0, nCommaPos); string sToFile = filename.substr(nCommaPos+1); bool bIsChanged = false; if(sToFile.empty()) { auto iterLastFile = m_replace_map.end(); if((iterLastFile = m_replace_map.find(sFromFile))!=m_replace_map.end()) { m_replace_map.erase(iterLastFile); bIsChanged = true; } } else { if (m_replace_map.find(sFromFile) == m_replace_map.end() || m_replace_map[sFromFile] != sToFile) { m_replace_map[sFromFile] = sToFile; bIsChanged = true; } } if(bIsChanged && CGlobals::GetAssetManager()->UnloadAssetByKeyName(sFromFile)) { #ifdef _DEBUG // OUTPUT_LOG("Replace asset file %s->%s\n", sFromFile.c_str(), sToFile.c_str()); #endif } return; } CParaFile file; if(file.OpenAssetFile(filename.c_str())) { regex re("([^,]+),([^,]+)"); int nCount = 0; char line[1024]; while(file.GetNextLine(line, 1023)) { string sLine = line; smatch result; if (regex_search(sLine, result, re) && result.size() > 2) { string fileFrom = result.str(1); string fileTo = result.str(2); Asset_Replace_Map_Type::iterator iter = m_replace_map.find(fileFrom); if( iter == m_replace_map.end()) { nCount ++; m_replace_map[fileFrom] = fileTo; } else { if(iter->second == fileTo) { // OUTPUT_LOG("warning: recursive file replace found: %s->%s\n", fileFrom.c_str(), fileTo.c_str()); } else { // overwrite old one with new mapping. iter->second = fileTo; if(CGlobals::GetAssetManager()->UnloadAssetByKeyName(fileFrom)) { #ifdef _DEBUG OUTPUT_LOG("warning: unload a replace asset file %s->%s\n", fileFrom.c_str(), fileTo.c_str()); #endif } } } } } OUTPUT_LOG("Asset Replace file %s is loaded, %d file replaced. Overwrite(%s)\n", filename.c_str(), nCount, bReplaceExistingOnes ? "true" : "false"); } }
void reverseWords(string &s) { reverse(s.begin(), s.end()); for(int start = 0, idx = (s.find(' ') == -1)?s.length():s.find(' '); start < s.length(); start = idx + 1, idx = (s.find(' ', start) == -1?s.length():s.find(' ', start))) reverse(s.begin() + start, s.begin() + idx); }
template<class T> vector<T> split(string s, string x=" ") {vector<T> res; for(int i=0;i<s.size();i++){string a; while(i<(int)s.size()&&x.find(s[i])==string::npos)a+=s[i++]; if(!a.empty())res.push_back(cast<T>(a));} return res;}
static inline bool good(const string& alphabet, const char& c) { if(alphabet.find(c) != string::npos) return true; return false; }
bool isSubstring(string newString, string rotatedString) { return newString.find(rotatedString); }
void AbstractMap::add_scheme(string &mapping_scheme_full) { int start = mapping_scheme_full.find("-->") + 3; while (isspace(mapping_scheme_full[start])) start++; this->mapping_scheme = mapping_scheme_full.substr(start, mapping_scheme_full.size() - start); }
void link_check::inspect( const string & library_name, const path & full_path, // example: c:/foo/boost/filesystem/path.hpp const string & contents ) // contents of file to be inspected { if (contents.find( "boostinspect:" "nounlinked" ) != string::npos) m_paths[ relative_to( full_path, search_root_path() ) ] |= m_nounlinked_errors; bool no_link_errors = (contents.find( "boostinspect:" "nolink" ) != string::npos); // build bookmarks databases bookmarks.clear(); bookmarks_lowercase.clear(); string::const_iterator a_start( contents.begin() ); string::const_iterator a_end( contents.end() ); boost::match_results< string::const_iterator > a_what; boost::match_flag_type a_flags = boost::match_default; if(!is_css(full_path)) { string previous_id; while( boost::regex_search( a_start, a_end, a_what, html_bookmark_regex, a_flags) ) { // a_what[0] contains the whole string iterators. // a_what[1] contains the tag iterators. // a_what[2] contains the attribute name. // a_what[4] contains the bookmark iterators. if (a_what[4].matched) { string tag( a_what[1].first, a_what[1].second ); boost::algorithm::to_lower(tag); string attribute( a_what[2].first, a_what[2].second ); boost::algorithm::to_lower(attribute); string bookmark( a_what[4].first, a_what[4].second ); bool name_following_id = ( attribute == "name" && previous_id == bookmark ); if ( tag != "meta" && attribute == "id" ) previous_id = bookmark; else previous_id.clear(); if ( tag != "meta" && !name_following_id ) { bookmarks.insert( bookmark ); // std::cout << "******************* " << bookmark << '\n'; // w3.org recommends case-insensitive checking for duplicate bookmarks // since some browsers do a case-insensitive match. string bookmark_lowercase( bookmark ); boost::algorithm::to_lower(bookmark_lowercase); std::pair<bookmark_set::iterator, bool> result = bookmarks_lowercase.insert( bookmark_lowercase ); if (!result.second) { ++m_duplicate_bookmark_errors; int ln = std::count( contents.begin(), a_what[3].first, '\n' ) + 1; error( library_name, full_path, "Duplicate bookmark: " + bookmark, ln ); } } } a_start = a_what[0].second; // update search position a_flags |= boost::match_prev_avail; // update flags a_flags |= boost::match_not_bob; } } // process urls string::const_iterator start( contents.begin() ); string::const_iterator end( contents.end() ); boost::match_results< string::const_iterator > what; boost::match_flag_type flags = boost::match_default; if(!is_css(full_path)) { while( boost::regex_search( start, end, what, html_url_regex, flags) ) { // what[0] contains the whole string iterators. // what[1] contains the element type iterators. // what[3] contains the URL iterators. if(what[3].matched) { string type( what[1].first, what[1].second ); boost::algorithm::to_lower(type); // TODO: Complain if 'link' tags use external stylesheets. do_url( string( what[3].first, what[3].second ), library_name, full_path, no_link_errors, type == "a" || type == "link", contents.begin(), what[3].first ); } start = what[0].second; // update search position flags |= boost::match_prev_avail; // update flags flags |= boost::match_not_bob; } } while( boost::regex_search( start, end, what, css_url_regex, flags) ) { // what[0] contains the whole string iterators. // what[2] contains the URL iterators. if(what[2].matched) { do_url( string( what[2].first, what[2].second ), library_name, full_path, no_link_errors, false, contents.begin(), what[3].first ); } start = what[0].second; // update search position flags |= boost::match_prev_avail; // update flags flags |= boost::match_not_bob; } }
void DotFormatter::findAndReplace(string &source, const string find, string replace) { size_t j; for ( ; (j = source.find( find )) != string::npos ; ) { source.replace( j, find.length(), replace ); } }
//Receive until error or \n bool Socket::ReadLine (string& line) { fd_set set_r, set_e; timeval timeout; int retries = 6; char buffer[2048]; if (!is_valid()) return false; while (true) { size_t pos1 = line.find("\r\n", 0); if (pos1 != std::string::npos) { line.erase(pos1, string::npos); return true; } timeout.tv_sec = RECEIVE_TIMEOUT; timeout.tv_usec = 0; // fill with new data FD_ZERO(&set_r); FD_ZERO(&set_e); FD_SET(_sd, &set_r); FD_SET(_sd, &set_e); int result = select(FD_SETSIZE, &set_r, NULL, &set_e, &timeout); if (result < 0) { XBMC->Log(LOG_DEBUG, "%s: select failed", __FUNCTION__); errormessage(getLastError(), __FUNCTION__); _sd = INVALID_SOCKET; return false; } if (result == 0) { if (retries != 0) { XBMC->Log(LOG_DEBUG, "%s: timeout waiting for response, retrying... (%i)", __FUNCTION__, retries); retries--; continue; } else { XBMC->Log(LOG_DEBUG, "%s: timeout waiting for response. Aborting after 10 retries.", __FUNCTION__); return false; } } result = recv(_sd, buffer, sizeof(buffer) - 1, 0); if (result < 0) { XBMC->Log(LOG_DEBUG, "%s: recv failed", __FUNCTION__); errormessage(getLastError(), __FUNCTION__); _sd = INVALID_SOCKET; return false; } buffer[result] = 0; line.append(buffer); } return true; }
string::size_type TfFindLongestAccessiblePrefix(string const &path, string* error) { typedef string::size_type size_type; static const size_type npos = string::npos; struct _Local { // Sentinel is greater than existing paths, less than non-existing ones. static bool Compare( string const &str, size_type lhs, size_type rhs, string* err) { if (lhs == rhs) return false; if (lhs == npos) return !Accessible(str, rhs, err); if (rhs == npos) return Accessible(str, lhs, err); return lhs < rhs; } static bool Accessible(string const &str, size_type index, string *err) { string checkPath(str, 0, index); // False if non-existent or if a symlink and the target is // non-existent. Also false on any error. _ClearError(); if (!TfPathExists(checkPath)) { _GetError(err); return false; } if (TfIsLink(checkPath) && !TfPathExists(checkPath, /* resolveSymlinks = */ true)) { _GetError(err); if (err->empty()) { *err = "encountered dangling symbolic link"; } } else { _GetError(err); } return err->empty(); } }; // Build a vector of split point indexes. vector<size_type> splitPoints; #if defined(ARCH_OS_WINDOWS) for (size_type p = path.find_first_of("/\\", path.find_first_not_of("/\\")); p != npos; p = path.find_first_of("/\\", p+1)) #else for (size_type p = path.find('/', path.find_first_not_of('/')); p != npos; p = path.find('/', p+1)) #endif splitPoints.push_back(p); splitPoints.push_back(path.size()); // Lower-bound to find first non-existent path. vector<size_type>::iterator result = std::lower_bound(splitPoints.begin(), splitPoints.end(), npos, boost::bind(_Local::Compare, path, _1, _2, error)); // begin means nothing existed, end means everything did, else prior is last // existing path. if (result == splitPoints.begin()) return 0; if (result == splitPoints.end()) return path.length(); return *(result - 1); }
void HttpConnection::on(BufferedSocketListener::Line, const string & aLine) noexcept { if (!ok) { dcdebug("%s\n", aLine.c_str()); if (aLine.find("200") == string::npos) { if (aLine.find("301") != string::npos || aLine.find("302") != string::npos) { moved302 = true; } else { socket_cleanup(false); #ifdef RIP_USE_CORAL if (SETTING(CORAL) && coralizeState != CST_NOCORALIZE) { fly_fire1(HttpConnectionListener::Retried(), this, coralizeState == CST_CONNECTED); coralizeState = CST_NOCORALIZE; dcdebug("HTTP error with Coral, retrying : %s\n", currentUrl.c_str()); downloadFile(currentUrl); return; } #endif fly_fire1(HttpConnectionListener::Failed(), this, aLine + " (" + currentUrl + ")"); #ifdef RIP_USE_CORAL coralizeState = CST_DEFAULT; #endif return; } } ok = true; } else if (moved302 && Util::findSubString(aLine, "Location") != string::npos) { dcassert(m_http_socket); socket_cleanup(false); string location302 = aLine.substr(10, aLine.length() - 11); // make sure we can also handle redirects with relative paths // if (Util::isHttpLink(location302)) [-] IRainman fix: support for part-time redirect URL. { if (location302[0] == '/') // [!] IRainman fix { string proto, query, fragment; Util::decodeUrl(currentUrl, proto, server, port, file, query, fragment); string tmp = "http://" + server; if (port != 80) tmp += ':' + Util::toString(port); location302 = tmp + location302; } else { string::size_type i = currentUrl.rfind('/'); dcassert(i != string::npos); location302 = currentUrl.substr(0, i + 1) + location302; } } if (location302 == currentUrl) { fly_fire1(HttpConnectionListener::Failed(), this, "Endless redirection loop: " + currentUrl); return; } fly_fire1(HttpConnectionListener::Redirected(), this, location302); #ifdef RIP_USE_CORAL coralizeState = CST_DEFAULT; #endif downloadFile(location302); } else if (aLine == "\x0d") { m_http_socket->setDataMode(size); } else if (Util::findSubString(aLine, "Content-Length") != string::npos) { size = Util::toInt(aLine.substr(16, aLine.length() - 17)); } else if (Util::findSubString(aLine, "Content-Encoding") != string::npos) { if (aLine.substr(18, aLine.length() - 19) == "x-bzip2") fly_fire1(HttpConnectionListener::TypeBZ2(), this); } }
string handle_NEXTQ(const string &rawtext) { int err; string ret; const char *handlefind = "NEXTQ "; const char *strfind = "\r\nCookie: "; size_t start = rawtext.find(handlefind) + strlen(handlefind); if (start == string::npos) { err = PC_INPUTFORMATERROR; ret = sys_error(err); ret += "\r\n\r\n"; return ret; } size_t stop = rawtext.find(strfind, start); if (stop == string::npos) { err = PC_INPUTFORMATERROR; ret = sys_error(err); ret += "\r\n\r\n"; return ret; } eid_t eid = rawtext.substr(start, stop - start); start = stop + strlen(strfind); stop = rawtext.find("\r\n", start); if (stop == string::npos) { err = PC_INPUTFORMATERROR; ret = sys_error(err); ret += "\r\n\r\n"; return ret; } string cookie = rawtext.substr(start, stop - start); DB db; PGconn *dbconn = db.getConn(); char sql_buf[MAXBUF]; uid_t uid = getUIDByCookie(cookie, err, dbconn); snprintf(sql_buf, sizeof(sql_buf), "SELECT question_id FROM question WHERE " "paper_id = ( " "SELECT currentp FROM users WHERE " "user_id = '%s'" ") ORDER BY question_id ", uid.c_str()); PGresult *res = PQexec(dbconn, sql_buf); if (PQresultStatus(res) != PGRES_TUPLES_OK) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); PQclear(res); return ret; } vector<qid_t> qlist; qlist.reserve(PQntuples(res)); for (int i = 0; i < PQntuples(res); ++i) { qlist.push_back(PQgetvalue(res, i, 0)); } PQclear(res); snprintf(sql_buf, sizeof(sql_buf), "SELECT scheme, qflag, currentp FROM users " "WHERE user_id = '%s' ", uid.c_str()); res = PQexec(dbconn, sql_buf); if (PQresultStatus(res) != PGRES_TUPLES_OK) // || PQgetisnull(res, 0, 0) // || PQgetisnull(res, 0, 1) // || PQgetisnull(res, 0, 2)) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); PQclear(res); return ret; } int scheme = atoi(PQgetvalue(res, 0, 0)); //qflag unsigned int current = atoi(PQgetvalue(res, 0, 1)); //current paper pid_t pid = PQgetvalue(res, 0, 2); PQclear(res); if (current >= qlist.size()) { //TODO: Call judge //TODO: Remove the flag From user; snprintf(sql_buf, sizeof(sql_buf), "UPDATE users SET scheme = null, qflag = null, currentp = null " "WHERE user_id = '%s'", uid.c_str()); res = PQexec(dbconn, sql_buf); if (PQresultStatus(res) != PGRES_COMMAND_OK) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); PQclear(res); return ret; } PQclear(res); getScore(uid, pid, err, dbconn); if (err != PC_SUCCESSFUL) { ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); return ret; } //Exam is over err = PC_EXAMOVER; ret = sys_error(err); ret += "\r\n\r\n"; return ret; } // now get the pid! qid_t qidnum = getNextQ(qlist, scheme, current); snprintf(sql_buf, sizeof(sql_buf), "SELECT content, choice_id, answer_content, timelimit FROM question, choice " "WHERE question.question_id = %s " "AND choice.question_id = question.question_id ", qidnum.c_str()); res = PQexec(dbconn, sql_buf); if (PQresultStatus(res) != PGRES_TUPLES_OK || PQntuples(res) == 0) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); PQclear(res); return ret; } // now that we've got the pid, generate the paper // TODO: generate the XML tree xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0"); xmlNodePtr root_node = xmlNewNode(NULL, BAD_CAST "NEXTQ"); xmlDocSetRootElement(doc, root_node); xmlNewChild(root_node, NULL, BAD_CAST "qid", BAD_CAST qidnum.c_str()); xmlNewChild(root_node, NULL, BAD_CAST "description", BAD_CAST PQgetvalue(res, 0, 0)); xmlNewChild(root_node, NULL, BAD_CAST "time", BAD_CAST PQgetvalue(res, 0, 3)); for (int i = 0; i < PQntuples(res); ++i) { xmlNodePtr c_node = xmlNewNode(NULL, BAD_CAST "choice"); xmlAddChild(root_node, c_node); xmlNewChild(c_node, NULL, BAD_CAST "cid", BAD_CAST PQgetvalue(res, i, 1)); xmlNewChild(c_node, NULL, BAD_CAST "description", BAD_CAST PQgetvalue(res, i, 2)); } snprintf(sql_buf, sizeof(sql_buf), "%d", current); xmlNewChild(root_node, NULL, BAD_CAST "fnum", BAD_CAST sql_buf); snprintf(sql_buf, sizeof(sql_buf), "%lu", qlist.size()); xmlNewChild(root_node, NULL, BAD_CAST "tnum", BAD_CAST sql_buf); xmlChar *xmlbuffer; int buffersize; xmlDocDumpFormatMemory(doc, &xmlbuffer, &buffersize, 1); err = PC_SUCCESSFUL; ret = sys_error(err); ret += "\r\n\r\n"; ret += (char *) xmlbuffer; xmlFreeDoc(doc); xmlFree(xmlbuffer); PQclear(res); return ret; }
string handle_STARTE(const string &rawtext) { int err; string ret; const char *handlefind = "STAERE "; const char *strfind = "\r\nCookie: "; size_t start = rawtext.find(handlefind) + strlen(handlefind); if (start == string::npos) { err = PC_INPUTFORMATERROR; ret = sys_error(err); ret += "\r\n\r\n"; return ret; } size_t stop = rawtext.find(strfind, start); if (stop == string::npos) { err = PC_INPUTFORMATERROR; ret = sys_error(err); ret += "\r\n\r\n"; return ret; } eid_t eid = rawtext.substr(start, stop - start); start = stop + strlen(strfind); stop = rawtext.find("\r\n", start); if (stop == string::npos) { err = PC_INPUTFORMATERROR; ret = sys_error(err); ret += "\r\n\r\n"; return ret; } string cookie = rawtext.substr(start, stop - start); DB db; PGconn *dbconn = db.getConn(); uid_t uid = getUIDByCookie(cookie, err, dbconn); gid_t gid = getGIDByUID(uid, err, dbconn); if (GID_STUDENT == gid || gid == GID_ADMIN || gid == GID_TEACHER) { char ceid[MAXBUF]; PQescapeString(ceid, eid.c_str(), eid.size() + 1); char sql_buf[MAXBUF]; PGresult *res_exam; snprintf(sql_buf, sizeof(sql_buf), "SELECT start_time as start, end_time, status as end " " FROM exam WHERE exam_id=%s " "AND status = 'started'", ceid); res_exam = PQexec(dbconn, sql_buf); if (PQresultStatus(res_exam) != PGRES_TUPLES_OK) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; PQclear(res_exam); return ret; } if (PQntuples(res_exam) == 0) { err = PC_NOTFOUND; ret = sys_error(err); ret += "\r\n\r\n"; PQclear(res_exam); return ret; } // Is exam started time_t start = strtoul(PQgetvalue(res_exam, 0, 0), NULL, 10); time_t end = strtoul(PQgetvalue(res_exam, 0, 1), NULL, 10); #if DBG fprintf(stderr, "%s:%d::start: %ul, end: %ul", __FUNCTION__, __LINE__, start, end) #endif time_t now = time(NULL); if ( ! (now >=start && now <= end && strcmp("started", PQgetvalue(res_exam, 0, 2) ) == 0) ) { err = PC_NOPERMISSION; ret = sys_error(err); ret += "\r\n\r\n"; PQclear(res_exam); return ret; } PQclear(res_exam); snprintf(sql_buf, sizeof(sql_buf), "SELECT * FROM student_exam WHERE user_id = '%s' AND paper_id IN ( " "SELECT paper_id FROM paper WHERE exam_id = %s " ") AND final_score IS NOT NULL ", uid.c_str(), ceid); res_exam = PQexec(dbconn, sql_buf); if (PQresultStatus(res_exam) != PGRES_TUPLES_OK) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; std::cerr << PQerrorMessage(dbconn) << std::endl; std::cerr.flush(); PQclear(res_exam); return ret; } if (PQntuples(res_exam) >= 1) { err = PC_NOPERMISSION; ret = sys_error(err); ret += "\r\n\r\n"; std::cerr << "Student can't take part in the same exam twice. " << std::endl; std::cerr.flush(); PQclear(res_exam); return ret; } PQclear(res_exam); // time is valid, start the exam // check if we are crashed // TODO: check resume action // SELECT paper_id FROM paper WHERE exam_id=eid and paper_id=( // SELECT currentpaper FROM users WHERE user_id=uid // ); // snprintf(sql_buf, sizeof(sql_buf), "SELECT paper_id FROM paper " "WHERE exam_id = %s " "AND paper_id = ( " "SELECT currentp FROM users WHERE user_id = '%s' " ")", ceid, uid.c_str()); res_exam = PQexec(dbconn, sql_buf); if (PQresultStatus(res_exam) != PGRES_TUPLES_OK) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); PQclear(res_exam); return ret; } if (PQntuples(res_exam) > 0) { //This is a resume action, do nothing return "200 OK\r\n\r\n"; } PQclear(res_exam); // TODO: brand new paper, do init // It's SO ugly! Use std::vector to // store all the PGresult and free it // before return int number_of_paper = 0; snprintf(sql_buf, sizeof(sql_buf), "SELECT paper_id FROM paper " "WHERE exam_id = '%s' ", ceid); PGresult *res = PQexec(dbconn, sql_buf); if (PQresultStatus(res) != PGRES_TUPLES_OK) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); //ret += PQerrorMessage(dbconn); PQclear(res); // PQclear(res_paper); return ret; } vector<pid_t> plist; for (int i = 0; i < PQntuples(res); i++) { plist.push_back(PQgetvalue(res, i, 0)); } number_of_paper = plist.size(); PQclear(res); srand(now); pid_t currentp = plist[rand() % number_of_paper]; //TODO: choose a paper differ from the nearby // SELECT paper_id as pid FROM paper WHERE // pid NOT IN ( // SELECT currentp FROM users WHERE userid = uid+1 // OR userid=uid-1 // ); // choose a sequence scheme snprintf(sql_buf, sizeof(sql_buf), "SELECT count(*) FROM question WHERE paper_id = %s", currentp.c_str()); res = PQexec(dbconn, sql_buf); if (PQresultStatus(res) != PGRES_TUPLES_OK && PQntuples(res) == 0) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); PQclear(res); return ret; } int number_of_question = atoi(PQgetvalue(res, 0, 0)); srand(now); int scheme = rand() % number_of_question; PQclear(res); //TODO: put scheme into DB // TODO: put the paper_id into DB // UPDATE users SET currentp=pid, scheme=scheme // WHERE userid=uid; snprintf(sql_buf, sizeof(sql_buf), "UPDATE users SET currentp = %s, scheme = %d, qflag = 0" "WHERE user_id = '%s'", currentp.c_str(), scheme, uid.c_str()); res = PQexec(dbconn, sql_buf); if (PQresultStatus(res) != PGRES_COMMAND_OK) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); PQclear(res); return ret; } PQclear(res); snprintf(sql_buf, sizeof(sql_buf), "INSERT INTO student_exam VALUES (" "'%s', %s, false, null)", uid.c_str(), currentp.c_str()); res = PQexec(dbconn, sql_buf); if (PQresultStatus(res) != PGRES_COMMAND_OK) { err = PC_DBERROR; ret = sys_error(err); ret += "\r\n\r\n"; ret += PQerrorMessage(dbconn); PQclear(res); return ret; } err = PC_SUCCESSFUL; ret = sys_error(err); ret += "\r\n\r\n"; return ret; } else { err = PC_NOPERMISSION; ret = sys_error(err); ret += "\r\n\r\n"; return ret; } }
// string utils inline bool found(const string& s, const string& ss) { return s.find(ss) != string::npos; }
static inline bool startsWith(const string& source, const string& pattern) { return ( source.find(pattern) == 0 ); }
string StringUtils::replaceMultiple(const string &subject,const std::vector<std::pair<std::string,std::string> > & rules,int max) { typedef std::pair<std::string,std::string> keyValuePair_t; const size_t ruleCount=rules.size(); std::vector<size_t> findLen(ruleCount); std::vector<size_t> pos(ruleCount); size_t i=0; for(const auto & keyValuePair : rules) { // length of the search pattern findLen[i] = keyValuePair.first.length(); // first position pos[i] = subject.find(keyValuePair.first, 0); ++i; } int nr=0; std::ostringstream s; size_t cursor=0; const size_t len=subject.length(); while(cursor<len&& nr!=max) { // select next match size_t nextPos=string::npos; size_t nextFindLength=0; std::vector<keyValuePair_t>::const_iterator nextReplace=rules.begin(); std::vector<keyValuePair_t>::const_iterator ruleIt=rules.begin(); for(i=0; i<ruleCount; ++i,++ruleIt) { // search not found -> continue if(pos[i]==string::npos) { continue; } // stepped over position (overlapping foundings) -> search again if(cursor>pos[i]) { pos[i]=subject.find((*ruleIt).first,cursor); } // nearest founding? if (pos[i]<nextPos) { nextReplace=ruleIt; nextPos=pos[i]; nextFindLength=findLen[i]; } } // found nothing? -> finished if (nextPos==string::npos) break; // append string s<<subject.substr(cursor,nextPos-cursor); s<<(*nextReplace).second; cursor=nextPos+nextFindLength; ++nr; } // add ending if (cursor<len) s<<subject.substr(cursor,len-cursor); return s.str(); }
dstring TextConverter::convert(const dstring &text, string &fromCharset, const string &toCharset) { dstring outputText; char outputBuffer[8192]; char *pInput = const_cast<char *>(text.c_str()); gsize inputSize = (gsize)text.length(); bool invalidSequence = false; outputText.clear(); try { IConv converter(toCharset, fromCharset); while (inputSize > 0) { char *pOutput = outputBuffer; gsize outputSize = 8192; size_t conversions = converter.iconv(&pInput, &inputSize, &pOutput, &outputSize); int errorCode = errno; if (conversions == static_cast<size_t>(-1)) { if (errorCode == EILSEQ) { // Conversion was only partially successful ++m_conversionErrors; #ifdef DEBUG clog << "TextConverter::convert: invalid sequence" << endl; #endif if (m_conversionErrors >= m_maxErrors) { // Give up return text; } converter.reset(); outputText.append(outputBuffer, 8192 - outputSize); if (invalidSequence == false) { outputText += "?"; invalidSequence = true; } // Skip that ++pInput; --inputSize; continue; } else if (errorCode != E2BIG) { #ifdef DEBUG clog << "TextConverter::convert: unknown error " << errorCode << endl; #endif return text; } } else { invalidSequence = false; } // Append what was successfully converted outputText.append(outputBuffer, 8192 - outputSize); } #ifdef DEBUG clog << "TextConverter::convert: " << m_conversionErrors << " conversion errors" << endl; #endif } catch (Error &ce) { #ifdef DEBUG clog << "TextConverter::convert: " << ce.what() << endl; #endif outputText.clear(); string::size_type pos = fromCharset.find('_'); if (pos != string::npos) { string fixedCharset(StringManip::replaceSubString(fromCharset, "_", "-")); #ifdef DEBUG clog << "TextConverter::convert: trying with charset " << fixedCharset << endl; #endif fromCharset = fixedCharset; outputText = convert(text, fromCharset, toCharset); } } catch (...) { #ifdef DEBUG clog << "TextConverter::convert: unknown exception" << endl; #endif outputText.clear(); } return outputText; }
string Namenskern(string s) { char *temp = new char[s.size() + 1]; strcpy(temp, s.c_str()); s = basename(temp); return s.substr(0, s.find('.')); }
/* * This sample helps to evaluate odometry on TUM datasets and benchmark http://vision.in.tum.de/data/datasets/rgbd-dataset. * At this link you can find instructions for evaluation. The sample runs some opencv odometry and saves a camera trajectory * to file of format that the benchmark requires. Saved file can be used for online evaluation. */ int main(int argc, char** argv) { if(argc != 4) { cout << "Format: file_with_rgb_depth_pairs trajectory_file odometry_name [Rgbd or ICP or RgbdICP]" << endl; return -1; } vector<string> timestamps; vector<Mat> Rts; const string filename = argv[1]; ifstream file( filename.c_str() ); if( !file.is_open() ) return -1; char dlmrt = '/'; size_t pos = filename.rfind(dlmrt); string dirname = pos == string::npos ? "" : filename.substr(0, pos) + dlmrt; const int timestampLength = 17; const int rgbPathLehgth = 17+8; const int depthPathLehgth = 17+10; float fx = 525.0f, // default fy = 525.0f, cx = 319.5f, cy = 239.5f; if(filename.find("freiburg1") != string::npos) setCameraMatrixFreiburg1(fx, fy, cx, cy); if(filename.find("freiburg2") != string::npos) setCameraMatrixFreiburg2(fx, fy, cx, cy); Mat cameraMatrix = Mat::eye(3,3,CV_32FC1); { cameraMatrix.at<float>(0,0) = fx; cameraMatrix.at<float>(1,1) = fy; cameraMatrix.at<float>(0,2) = cx; cameraMatrix.at<float>(1,2) = cy; } Ptr<OdometryFrame> frame_prev = Ptr<OdometryFrame>(new OdometryFrame()), frame_curr = Ptr<OdometryFrame>(new OdometryFrame()); Ptr<Odometry> odometry = Algorithm::create<Odometry>("RGBD." + string(argv[3]) + "Odometry"); if(odometry.empty()) { cout << "Can not create Odometry algorithm. Check the passed odometry name." << endl; return -1; } odometry->set("cameraMatrix", cameraMatrix); MyTickMeter gtm; int count = 0; for(int i = 0; !file.eof(); i++) { string str; std::getline(file, str); if(str.empty()) break; if(str.at(0) == '#') continue; /* comment */ Mat image, depth; // Read one pair (rgb and depth) // example: 1305031453.359684 rgb/1305031453.359684.png 1305031453.374112 depth/1305031453.374112.png #if BILATERAL_FILTER MyTickMeter tm_bilateral_filter; #endif { string rgbFilename = str.substr(timestampLength + 1, rgbPathLehgth ); string timestap = str.substr(0, timestampLength); string depthFilename = str.substr(2*timestampLength + rgbPathLehgth + 3, depthPathLehgth ); image = imread(dirname + rgbFilename); depth = imread(dirname + depthFilename, -1); CV_Assert(!image.empty()); CV_Assert(!depth.empty()); CV_Assert(depth.type() == CV_16UC1); cout << i << " " << rgbFilename << " " << depthFilename << endl; // scale depth Mat depth_flt; depth.convertTo(depth_flt, CV_32FC1, 1.f/5000.f); #if !BILATERAL_FILTER depth_flt.setTo(std::numeric_limits<float>::quiet_NaN(), depth == 0); depth = depth_flt; #else tm_bilateral_filter.start(); depth = Mat(depth_flt.size(), CV_32FC1, Scalar(0)); const double depth_sigma = 0.03; const double space_sigma = 4.5; // in pixels Mat invalidDepthMask = depth_flt == 0.f; depth_flt.setTo(-5*depth_sigma, invalidDepthMask); bilateralFilter(depth_flt, depth, -1, depth_sigma, space_sigma); depth.setTo(std::numeric_limits<float>::quiet_NaN(), invalidDepthMask); tm_bilateral_filter.stop(); cout << "Time filter " << tm_bilateral_filter.getTimeSec() << endl; #endif timestamps.push_back( timestap ); } { Mat gray; cvtColor(image, gray, COLOR_BGR2GRAY); frame_curr->image = gray; frame_curr->depth = depth; Mat Rt; if(!Rts.empty()) { MyTickMeter tm; tm.start(); gtm.start(); bool res = odometry->compute(frame_curr, frame_prev, Rt); gtm.stop(); tm.stop(); count++; cout << "Time " << tm.getTimeSec() << endl; #if BILATERAL_FILTER cout << "Time ratio " << tm_bilateral_filter.getTimeSec() / tm.getTimeSec() << endl; #endif if(!res) Rt = Mat::eye(4,4,CV_64FC1); } if( Rts.empty() ) Rts.push_back(Mat::eye(4,4,CV_64FC1)); else { Mat& prevRt = *Rts.rbegin(); cout << "Rt " << Rt << endl; Rts.push_back( prevRt * Rt ); } if(!frame_prev.empty()) frame_prev->release(); std::swap(frame_prev, frame_curr); } } std::cout << "Average time " << gtm.getTimeSec()/count << std::endl; writeResults(argv[2], timestamps, Rts); return 0; }
int G4Setup(const int absorberactive = 0, const string &field ="1.5", #if ROOT_VERSION_CODE >= ROOT_VERSION(6,00,0) const EDecayType decayType = EDecayType::kAll, #else const EDecayType decayType = TPythia6Decayer::kAll, #endif const bool do_tracking = true, const bool do_pstof = true, const bool do_cemc = true, const bool do_hcalin = true, const bool do_magnet = true, const bool do_hcalout = true, const bool do_pipe = true, const bool do_plugdoor = false, // const bool do_plugdoor = true, const float magfield_rescale = 1.0) { //--------------- // Load libraries //--------------- gSystem->Load("libg4detectors.so"); gSystem->Load("libg4testbench.so"); //--------------- // Fun4All server //--------------- Fun4AllServer *se = Fun4AllServer::instance(); // read-in HepMC events to Geant4 if there is any HepMCNodeReader *hr = new HepMCNodeReader(); se->registerSubsystem(hr); PHG4Reco* g4Reco = new PHG4Reco(); g4Reco->set_rapidity_coverage(1.1); // according to drawings // uncomment to set QGSP_BERT_HP physics list for productions // (default is QGSP_BERT for speed) // g4Reco->SetPhysicsList("QGSP_BERT_HP"); #if ROOT_VERSION_CODE >= ROOT_VERSION(6,00,0) if (decayType != EDecayType::kAll) #else if (decayType != TPythia6Decayer::kAll) #endif { g4Reco->set_force_decay(decayType); } double fieldstrength; istringstream stringline(field); stringline >> fieldstrength; if (stringline.fail()) { // conversion to double fails -> we have a string if (field.find("sPHENIX.root") != string::npos) { g4Reco->set_field_map(field, PHFieldConfig::Field3DCartesian); } else { g4Reco->set_field_map(field, PHFieldConfig::kField2D); } } else { g4Reco->set_field(fieldstrength); // use const soleniodal field } g4Reco->set_field_rescale(magfield_rescale); double radius = 0.; //---------------------------------------- // PIPE if (do_pipe) radius = Pipe(g4Reco, radius, absorberactive); //---------------------------------------- // TRACKING if (do_tracking) radius = Tracking(g4Reco, radius, absorberactive); //---------------------------------------- // PSTOF if (do_pstof) radius = PSTOF(g4Reco, radius, absorberactive); //---------------------------------------- // CEMC // if (do_cemc) radius = CEmc(g4Reco, radius, 8, absorberactive); // if (do_cemc) radius = CEmc_Vis(g4Reco, radius, 8, absorberactive);// for visualization substructure of SPACAL, slow to render //---------------------------------------- // HCALIN if (do_hcalin) radius = HCalInner(g4Reco, radius, 4, absorberactive); //---------------------------------------- // MAGNET if (do_magnet) radius = Magnet(g4Reco, radius, 0, absorberactive); //---------------------------------------- // HCALOUT if (do_hcalout) radius = HCalOuter(g4Reco, radius, 4, absorberactive); //---------------------------------------- // sPHENIX forward flux return door if (do_plugdoor) PlugDoor(g4Reco, absorberactive); //---------------------------------------- // BLACKHOLE // swallow all particles coming out of the backend of sPHENIX PHG4CylinderSubsystem *blackhole = new PHG4CylinderSubsystem("BH", 1); blackhole->set_double_param("radius",radius + 10); // add 10 cm blackhole->set_int_param("lengthviarapidity",0); blackhole->set_double_param("length",g4Reco->GetWorldSizeZ() - no_overlapp); // make it cover the world in length blackhole->BlackHole(); blackhole->set_double_param("thickness",0.1); // it needs some thickness blackhole->SetActive(); // always see what leaks out blackhole->OverlapCheck(overlapcheck); g4Reco->registerSubsystem(blackhole); //---------------------------------------- // FORWARD BLACKHOLEs // +Z blackhole = new PHG4CylinderSubsystem("BH_FORWARD_PLUS", 1); blackhole->SuperDetector("BH_FORWARD_PLUS"); blackhole->set_double_param("radius",0); // add 10 cm blackhole->set_int_param("lengthviarapidity",0); blackhole->set_double_param("length",0.1); // make it cover the world in length blackhole->set_double_param("place_z",g4Reco->GetWorldSizeZ()/2. - 0.1 - no_overlapp); blackhole->BlackHole(); blackhole->set_double_param("thickness",radius - no_overlapp); // it needs some thickness blackhole->SetActive(); // always see what leaks out blackhole->OverlapCheck(overlapcheck); g4Reco->registerSubsystem(blackhole); blackhole = new PHG4CylinderSubsystem("BH_FORWARD_NEG", 1); blackhole->SuperDetector("BH_FORWARD_NEG"); blackhole->set_double_param("radius",0); // add 10 cm blackhole->set_int_param("lengthviarapidity",0); blackhole->set_double_param("length",0.1); // make it cover the world in length blackhole->set_double_param("place_z", - g4Reco->GetWorldSizeZ()/2. +0.1 + no_overlapp); blackhole->BlackHole(); blackhole->set_double_param("thickness",radius - no_overlapp); // it needs some thickness blackhole->SetActive(); // always see what leaks out blackhole->OverlapCheck(overlapcheck); g4Reco->registerSubsystem(blackhole); PHG4TruthSubsystem *truth = new PHG4TruthSubsystem(); g4Reco->registerSubsystem(truth); se->registerSubsystem( g4Reco ); return 0; }
bool packet::parse(const string& payload_ptr) { assert(!is_binary_message(payload_ptr)); //this is ensured by outside _frame = (packet::frame_type) (payload_ptr[0] - '0'); _message.reset(); _pack_id = -1; _buffers.clear(); _pending_buffers = 0; size_t pos = 1; if (_frame == frame_message) { _type = (packet::type)(payload_ptr[pos] - '0'); if(_type < type_min || _type > type_max) { return false; } pos++; if (_type == type_binary_event || _type == type_binary_ack) { size_t score_pos = payload_ptr.find('-'); _pending_buffers = boost::lexical_cast<unsigned>(payload_ptr.substr(pos,score_pos)); pos = score_pos+1; } } size_t nsp_json_pos = payload_ptr.find_first_of("{[\"/",pos,4); if(nsp_json_pos==string::npos)//no namespace and no message,the end. { _nsp = "/"; return false; } size_t json_pos = nsp_json_pos; if(payload_ptr[nsp_json_pos] == '/')//nsp_json_pos is start of nsp { size_t comma_pos = payload_ptr.find_first_of(",");//end of nsp if(comma_pos == string::npos)//packet end with nsp { _nsp = payload_ptr.substr(nsp_json_pos); return false; } else//we have a message, maybe the message have an id. { _nsp = payload_ptr.substr(nsp_json_pos,comma_pos - nsp_json_pos); pos = comma_pos+1;//start of the message json_pos = payload_ptr.find_first_of("\"[{", pos, 3);//start of the json part of message if(json_pos == string::npos) { //no message,the end //assume if there's no message, there's no message id. return false; } } } else { _nsp = "/"; } if(pos<json_pos)//we've got pack id. { _pack_id = boost::lexical_cast<int>(payload_ptr.substr(pos,json_pos - pos)); } if (_frame == frame_message && (_type == type_binary_event || _type == type_binary_ack)) { //parse later when all buffers are arrived. _buffers.push_back(make_shared<string>(payload_ptr.data() + json_pos, payload_ptr.length() - json_pos)); return true; } else { Document doc; doc.Parse<0>(payload_ptr.data()+json_pos); _message = from_json(doc, vector<shared_ptr<const string> >()); return false; } }
bool contains(string& toCheck, char target) { return !(toCheck.find(target) == string::npos); }
bool isFileNameEndWithStr(string fileName,string endStr) { return (int)fileName.find(endStr.c_str()) == MAX(0,(int)(fileName.length()-string(endStr.c_str()).length())); }
BEGIN_NCBI_SCOPE ////////////////////////////////////////////////////////////////////////////// static TSvrRef make_server(const string& specification, double& preference) { vector<string> server_attr; string server; // string host; Uint4 host = 0; Uint2 port = 0; string::size_type pos = 0; pos = specification.find_first_of("@(", pos); if (pos != string::npos) { server = specification.substr(0, pos); if (specification[pos] == '@') { // string::size_type old_pos = pos + 1; pos = specification.find_first_of(":(", pos + 1); if (pos != string::npos) { // string host_str = specification.substr(old_pos, pos - old_pos); // Ignore host in order to avoid dependebcy on libconnect. // SOCK_StringToHostPort(specification.c_str() + old_pos, &host, &port); if (specification[pos] == ':') { port = NStr::StringToUInt(specification.c_str() + pos + 1, NStr::fAllowLeadingSpaces | NStr::fAllowTrailingSymbols | NStr::fConvErr_NoThrow); pos = specification.find("(", pos + 1); if (pos != string::npos) { // preference = NStr::StringToDouble( preference = NStr::StringToUInt( specification.c_str() + pos + 1, NStr::fAllowLeadingSpaces | NStr::fAllowTrailingSymbols | NStr::fConvErr_NoThrow); } } else { // preference = NStr::StringToDouble( preference = NStr::StringToUInt( specification.c_str() + pos + 1, NStr::fAllowLeadingSpaces | NStr::fAllowTrailingSymbols | NStr::fConvErr_NoThrow); } } else { // host = specification.substr(old_pos); // Ignore host in order to avoid dependebcy on libconnect. // SOCK_StringToHostPort(specification.c_str() + old_pos, &host, &port); } } else { // preference = NStr::StringToDouble( preference = NStr::StringToUInt( specification.c_str() + pos + 1, NStr::fAllowLeadingSpaces | NStr::fAllowTrailingSymbols | NStr::fConvErr_NoThrow); } } else { server = specification; } if (server.empty() && host == 0) { DATABASE_DRIVER_ERROR("Either server name or host name expected.", 110100 ); } return TSvrRef(new CDBServer(server, host, port)); }
/// convert infix string into postfix token list postfix_t infix2postfix(string in) { postfix_t out; stack<token_t> s; token_t lasttok; for (auto it = in.cbegin(); it != in.cend();) { const unsigned int i = it - in.cbegin(); // index of current character for parse_error purposes static const string spaces = " \t\r\n"; if (spaces.find(*it) != string::npos) { ++it; continue; } /*cout << string(it, in.cend()) << endl; cout << lasttok.first << "/" << lasttok.second << endl; if (!s.empty()) cout << s.top().first << "/" << s.top().second << endl;*/ // try to parse number static const string numbers = "0123456789."; auto it2 = it; for (; it2 != in.cend() && numbers.find(*it2) != string::npos; ++it2); // TODO: find_first_not_of if (it2 != it) { if (lasttok.first == ")" || (opers.find(lasttok.first) == opers.end() && funcs.find(lasttok.first) != funcs.end()) || lasttok.second == -1) throw parse_error("Missing operator", i); out.push_back(lasttok = token_t(string(it, it2), -1)); it = it2; continue; } // try to parse operator auto lastoper = opers.find(lasttok.first); bool lunary = lasttok.first == "" || lasttok.first == "(" || lasttok.first == "," || (lastoper != opers.end() && !(lastoper->second.unary && lastoper->second.right)); // true if operator at current location would be left unary /*cout << unary << endl; cout << endl;*/ auto oit = opers.begin(); for (; oit != opers.end(); ++oit) { if (equal(oit->first.begin(), oit->first.end(), it) && (oit->second.unary == lunary || (oit->second.unary && oit->second.right))) break; } if (oit != opers.end()) { if (lunary) { s.push(lasttok = token_t(oit->first, 1)); } else if (oit->second.unary && oit->second.right) // right unary operator { // allow right unary operators to be used on constants and apply higher prec operators before while (!s.empty()) { token_t tok = s.top(); auto oit2 = find_oper(tok.first, true); if ((oit2 != opers.end() && oit2->second.prec > oit->second.prec) || (oit2 == opers.end() && funcs.find(tok.first) != funcs.end())) out.push_back(pop(s)); else break; } out.push_back(lasttok = token_t(oit->first, 1)); // needs stack popping before? } else { insert_binaryoper(out, s, oit); lasttok = token_t(oit->first, 2); } it += oit->first.size(); continue; } // try to parse function auto fit = funcs.begin(); for (; fit != funcs.end(); ++fit) { if (opers.find(fit->first) == opers.end() && equal(fit->first.begin(), fit->first.end(), it)) break; } if (fit != funcs.end()) { if (lasttok.first == ")" || (opers.find(lasttok.first) == opers.end() && funcs.find(lasttok.first) != funcs.end())) throw parse_error("Missing operator", i); else if (lasttok.second == -1) insert_implicitmult(out, s); s.push(lasttok = token_t(fit->first, 0)); it += fit->first.size(); continue; } // try to parse function argument separator if (*it == ',') { if (lasttok.first == "(" || lasttok.first == ",") throw parse_error("Missing argument", i); bool found = false; while (!s.empty()) { token_t tok = s.top(); if (tok.first == "(") { found = true; break; } else { out.push_back(tok); s.pop(); } } if (!found) throw parse_error("Found ',' not inside function arguments", i); s.top().second++; // increase number of arguments in current parenthesis lasttok = token_t(",", 0); ++it; continue; } if (*it == '(') { if (lasttok.second == -1 || lasttok.first == ")") insert_implicitmult(out, s); s.push(lasttok = token_t("(", 1)); ++it; continue; } if (*it == ')') { if (lasttok.first == "(" || lasttok.first == ",") throw parse_error("Missing argument", i); bool found = false; while (!s.empty()) { token_t tok = s.top(); if (tok.first == "(") { found = true; break; } else { out.push_back(tok); s.pop(); } } if (!found) throw parse_error("Found excess '('", i); token_t tok = pop(s); // pop '(' if (!s.empty() && opers.find(s.top().first) == opers.end() && funcs.find(s.top().first) != funcs.end()) // if parenthesis part of function arguments out.push_back(token_t(pop(s).first, tok.second)); lasttok = token_t(")", 0); ++it; continue; } throw parse_error("Unknown token found", i); } while (!s.empty()) { token_t tok = pop(s); if (tok.first == "(") throw parse_error("Found unclosed '('", in.size()); out.push_back(tok); } return out; }
/* Prepare to build an index. Does not actually build it (except for a special _id case). - We validate that the params are good - That the index does not already exist - Creates the source collection if it DNE example of 'io': { ns : 'test.foo', name : 'z', key : { z : 1 } } throws DBException @param sourceNS - source NS we are indexing @param sourceCollection - its details ptr @return true if ok to continue. when false we stop/fail silently (index already exists) */ bool prepareToBuildIndex(const BSONObj& io, bool god, string& sourceNS, NamespaceDetails *&sourceCollection, BSONObj& fixedIndexObject ) { sourceCollection = 0; // logical name of the index. todo: get rid of the name, we don't need it! const char *name = io.getStringField("name"); uassert(12523, "no index name specified", *name); // the collection for which we are building an index sourceNS = io.getStringField("ns"); uassert(10096, "invalid ns to index", sourceNS.find( '.' ) != string::npos); massert(10097, str::stream() << "bad table to index name on add index attempt current db: " << cc().database()->name << " source: " << sourceNS , cc().database()->name == nsToDatabase(sourceNS.c_str())); BSONObj key = io.getObjectField("key"); uassert(12524, "index key pattern too large", key.objsize() <= 2048); if( !validKeyPattern(key) ) { string s = string("bad index key pattern ") + key.toString(); uasserted(10098 , s.c_str()); } if ( sourceNS.empty() || key.isEmpty() ) { log(2) << "bad add index attempt name:" << (name?name:"") << "\n ns:" << sourceNS << "\n idxobj:" << io.toString() << endl; string s = "bad add index attempt " + sourceNS + " key:" + key.toString(); uasserted(12504, s); } sourceCollection = nsdetails(sourceNS.c_str()); if( sourceCollection == 0 ) { // try to create it string err; if ( !userCreateNS(sourceNS.c_str(), BSONObj(), err, false) ) { problem() << "ERROR: failed to create collection while adding its index. " << sourceNS << endl; return false; } sourceCollection = nsdetails(sourceNS.c_str()); tlog() << "info: creating collection " << sourceNS << " on add index" << endl; verify( sourceCollection ); } if ( sourceCollection->findIndexByName(name) >= 0 ) { // index already exists. return false; } if( sourceCollection->findIndexByKeyPattern(key) >= 0 ) { log(2) << "index already exists with diff name " << name << ' ' << key.toString() << endl; return false; } if ( sourceCollection->nIndexes >= NamespaceDetails::NIndexesMax ) { stringstream ss; ss << "add index fails, too many indexes for " << sourceNS << " key:" << key.toString(); string s = ss.str(); log() << s << '\n'; uasserted(12505,s); } /* we can't build a new index for the ns if a build is already in progress in the background - EVEN IF this is a foreground build. */ uassert(12588, "cannot add index with a background operation in progress", !BackgroundOperation::inProgForNs(sourceNS.c_str())); /* this is because we want key patterns like { _id : 1 } and { _id : <someobjid> } to all be treated as the same pattern. */ if ( IndexDetails::isIdIndexPattern(key) ) { if( !god ) { ensureHaveIdIndex( sourceNS.c_str() ); return false; } } else { /* is buildIndexes:false set for this replica set member? if so we don't build any indexes except _id */ if( theReplSet && !theReplSet->buildIndexes() ) return false; } string pluginName = IndexPlugin::findPluginName( key ); IndexPlugin * plugin = pluginName.size() ? IndexPlugin::get( pluginName ) : 0; { BSONObj o = io; if ( plugin ) { o = plugin->adjustIndexSpec(o); } BSONObjBuilder b; int v = DefaultIndexVersionNumber; if( !o["v"].eoo() ) { double vv = o["v"].Number(); // note (one day) we may be able to fresh build less versions than we can use // isASupportedIndexVersionNumber() is what we can use uassert(14803, str::stream() << "this version of mongod cannot build new indexes of version number " << vv, vv == 0 || vv == 1); v = (int) vv; } // idea is to put things we use a lot earlier b.append("v", v); b.append(o["key"]); if( o["unique"].trueValue() ) b.appendBool("unique", true); // normalize to bool true in case was int 1 or something... b.append(o["ns"]); { // stripping _id BSONObjIterator i(o); while ( i.more() ) { BSONElement e = i.next(); string s = e.fieldName(); if( s != "_id" && s != "v" && s != "ns" && s != "unique" && s != "key" ) b.append(e); } } fixedIndexObject = b.obj(); } return true; }
void CalcFakeRate(string infile, bool useData=true, bool doSystematics=false){ cout<<" UseData="<<useData<<" dosystematics="<<doSystematics<<endl; TFile *f = TFile::Open(infile.c_str(), "read"); assert(f); TH2F* hFakeRateNum = NULL; TH2F* hFakeRateAll = NULL; gStyle->SetOptStat(0); gStyle->SetPalette(1); gStyle->SetTextFont(132); gStyle->SetTextSize(1.2); //gROOT->ForceStyle(); bool useElectrons = infile.find("Muon") == string::npos; bool doWLep = infile.find("-TT") == string::npos; vector<string> allsamples; if(!useData){ allsamples.push_back("WJetsToLNu"); if(!doSystematics){ allsamples.push_back("TTJets"); allsamples.push_back("ZZ"); allsamples.push_back("GVJets"); allsamples.push_back("WWTo2L2Nu"); allsamples.push_back("WZJetsTo3LNu"); allsamples.push_back("DYJetsToLL"); } }else{ allsamples.push_back("data"); } float offset = 0.01; float eta[] = {0., 1.5, 2.5}; int neta = 3; if(!useElectrons){ eta[1] = 2.4; neta = 2;//eta[2] = 2.4; } //float pt [] = {0., 20., 40., 1000}; const int npt = 4; //float pt [] = {0., 10., 20., 30., 1000}; const int npt = 5; //float pt [] = {0., 10., 15., 25., 1000}; const int npt = 5; //float pt [] = {0., 10., 15., 20., 30., 1000}; const int npt = 6; float pt [] = {10., 15., 20., 30., 40., 100}; const int npt = 6; //float pt [] = {0., 20., 25., 30., 50., 1000}; const int npt = 6; hFakeRateNum = new TH2F("hFakeRateNum", "hFakeRateNum;p_{T} (GeV);#eta", npt-1, pt, neta-1, eta); hFakeRateAll = new TH2F("hFakeRateAll", "hFakeRateAll;p_{T} (GeV);#eta", npt-1, pt, neta-1, eta); string title = useElectrons ? "Electron Fake Rate" : "Muon Fake Rate"; title += useData ? " from Data" : " from MC"; title += !useData && doSystematics ? " Systematics" : ""; title += " using W+Jets method"; title += doWLep ? " on W lepton" : " on Z lepton"; hFakeRateNum->SetTitle(title.c_str()); /////////This is for eta, pt agnotistic Fake Rate Calc float in_tot(0), out_tot(0); for(unsigned i=0; i<allsamples.size(); ++i){ string hist_name = allsamples[i] + "/hNumEvts"; TH1F* hist = (TH1F*) f->Get(hist_name.c_str()); assert(hist); int lastbin = hist->GetNbinsX(); float in(0), out(0); in = hist->GetBinContent(lastbin); out = hist->GetBinContent(lastbin-1); in_tot += in; out_tot += out; //cout<<"Sample: "<<allsamples[i]<<" = "<<in/out<<" = pass/total = "<<in<<"/"<<out<<endl; printf(" Sample: %s = %.2f%% : pass/total = %.2f / %.2f \n",allsamples[i].c_str(), in/out*100, in, out); } float eff = in_tot/out_tot; float deff = TMath::Sqrt(eff * (1-eff)/out_tot); //cout<<"Total: "<<eff*100<<"% +/- "<<deff*100<<"% = in_tot/out_tot*100% = "<<in_tot<<"/"<<out_tot<<"*100%\n"; printf("Total: %.2f%% +/- %.2f%% = in_tot/out_tot*100%% = %.2f/%.2f\n", eff*100, deff*100, in_tot, out_tot); /////////This is for 2D Fake Rate Calc for(unsigned i=0; i<allsamples.size(); ++i){ string hist_name = allsamples[i] + "/hNumEvts"; TH1F* hist = (TH1F*) f->Get(hist_name.c_str()); assert(hist); int lastbin = hist->GetNbinsX(); float in(0), out(0); string binNameNum = hist->GetXaxis()->GetBinLabel(lastbin); string binNameDenom = hist->GetXaxis()->GetBinLabel(lastbin-1); string hist_nameNum = allsamples[i] + "/hEtaVsPt_" + binNameNum; TH2F* histNum = (TH2F*) f->Get(hist_nameNum.c_str()); assert(histNum); string hist_nameDenom = allsamples[i] + "/hEtaVsPt_" + binNameDenom; TH2F* histDenom = (TH2F*) f->Get(hist_nameDenom.c_str()); assert(histDenom); /* cout<<" Total from 2D Plot is "<<histNum->Integral()<<" / "<<histDenom->Integral()<<endl; //By default, integral doesn't count over/underflow cout<<" Total from 2D Plot is "<<histNum->GetEntries()<<" / "<<histDenom->GetEntries()<<endl; float sUnder(0), sOver(0); for(int ybin = 0; ybin<= histDenom->GetYaxis()->GetNbins() + 1; ++ybin){ for(int xbin = 0; xbin<= histDenom->GetXaxis()->GetNbins() +1; ++xbin){ int bin = histDenom->GetBin(xbin, ybin); if(histDenom->IsBinOverflow(bin)) sOver += histDenom->GetBinContent(bin); if(histDenom->IsBinUnderflow(bin)) sUnder += histDenom->GetBinContent(bin); } } printf("Total overflow, underflow in denom histo is %.2f , %.2f\n", sOver, sUnder); */ for(int ieta=0; ieta<neta-1; ++ieta){ float ymin = eta[ieta]; float ymax = eta[ieta+1]-offset; for(int ipt=0; ipt<npt-1; ++ipt){ float xmin = pt[ipt]; float xmax = pt[ipt+1]; int xminbin,xmaxbin,yminbin,ymaxbin; xminbin = histNum->GetXaxis()->FindBin(xmin); //+ (ipt!=0);//Avoid overlap except for first bin xmaxbin = histNum->GetXaxis()->FindBin(xmax)-1 + (ipt == npt-1-1); yminbin = histNum->GetYaxis()->FindBin(ymin); ymaxbin = histNum->GetYaxis()->FindBin(ymax); /* cout<<"("<<pt[ipt]<<", "<<eta[ieta]<<")\t" <<xmin<<"-"<<xmax<<":" <<ymin<<"-"<<ymax<<":" <<"\t"; cout<<"("<<ipt<<", "<<ieta<<")\t" <<xminbin<<"-"<<xmaxbin<<":" <<yminbin<<"-"<<ymaxbin <<endl; */ in = histNum ->Integral(xminbin, xmaxbin, yminbin, ymaxbin); out = histDenom->Integral(xminbin, xmaxbin, yminbin, ymaxbin); //Cory: Deal with negative eta (Y axis) yminbin = histNum->GetYaxis()->FindBin(-1*ymax); ymaxbin = histNum->GetYaxis()->FindBin(-1*ymin)-1;//avoid overlap /* cout<<"("<<pt[ipt]<<", "<<eta[ieta]<<")\t" <<xmin<<"-"<<xmax<<":" <<ymin<<"-"<<ymax<<":" <<"\t"; cout<<"("<<ipt<<", "<<ieta<<")\t" <<xminbin<<"-"<<xmaxbin<<":" <<yminbin<<"-"<<ymaxbin <<endl; */ in += histNum ->Integral(xminbin, xmaxbin, yminbin, ymaxbin); out += histDenom->Integral(xminbin, xmaxbin, yminbin, ymaxbin); //cout<<"("<<pt[ipt]<<","<<eta[ieta]<<") "<<in<<"/"<<out<<endl; //cout<<"("<<(pt[ipt]+pt[ipt+1])/2<<","<<(eta[ieta]+eta[ieta+1])/2<<") "<<in<<"/"<<out<<endl; hFakeRateNum ->Fill( (pt[ipt]+pt[ipt+1])/2, (eta[ieta]+eta[ieta+1])/2, in); hFakeRateAll->Fill( (pt[ipt]+pt[ipt+1])/2, (eta[ieta]+eta[ieta+1])/2, out); } } } if(hFakeRateNum){ //TGraphAsymmErrors* hFakeRateEff = new TGraphAsymmErrors(hFakeRateNum->GetArray(), hFakeRateAll->GetArray(), ""); //TGraphAsymmErrors* hFakeRateEff = new TGraphAsymmErrors(hFakeRateNum, hFakeRateAll, ""); TH2F* hFakeRate = (TH2F*) hFakeRateNum->Clone("hFakeRate"); //hFakeRate->Divide(hFakeRateAll); //hFakeRate->Scale(100.); //make is a percent TCanvas c1; c1.SetLogx(1); //gStyle->SetTextFont(132); //gStyle->SetTextSize(1.2); hFakeRate->SetMarkerSize(3); //gStyle->SetPaintTextFormat("3.0f m"); gStyle->SetPaintTextFormat("4.0f"); hFakeRate->Draw("colz"); TLatex latexLabel; latexLabel.SetNDC(); latexLabel.SetTextSize(0.04); latexLabel.SetTextFont(42); latexLabel.SetTextAngle(90); latexLabel.SetTextAlign(22); for(int ybin = 1; ybin<= hFakeRate->GetYaxis()->GetNbins(); ++ybin){ int nx = hFakeRate->GetXaxis()->GetNbins(); TGraphAsymmErrors* gFakeRatePt = new TGraphAsymmErrors(nx); gFakeRatePt->SetMaximum(1.1); gFakeRatePt->SetMinimum(0.); gFakeRatePt->SetTitle((title + ";p_{T} (GeV);Rate").c_str()); for(int xbin = nx; xbin >= 1; --xbin){ float xcen = hFakeRate->GetXaxis()->GetBinCenter(xbin); float ycen = hFakeRate->GetYaxis()->GetBinCenter(ybin); double xpos, ypos; GetNDC(c1, xcen, ycen, xpos, ypos); int bin = hFakeRate->GetBin(xbin, ybin); float pass = hFakeRateNum->GetBinContent(bin); float tot = hFakeRateAll->GetBinContent(bin); float mean = tot>0 ? pass / tot : 0.; float errUp = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1); float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1); errDown = max(errDown, (float) 0.); hFakeRate->SetBinContent(bin, mean); //hFakeRate->SetBinError(bin, err); float err = (errUp + errDown)/2; printf("if(pt > %.0f) return Value(%.4f, %.4f); //pt %3.0f eta %.1f, bin %2i, (mean, err)= (%.4f, %.4f) (%.2f / %.2f) +%.4f -%.4f\n", hFakeRate->GetXaxis()->GetBinLowEdge(xbin), mean, err, hFakeRate->GetXaxis()->GetBinLowEdge(xbin), hFakeRate->GetYaxis()->GetBinLowEdge(ybin), bin, mean, err, pass, tot, errUp, errDown); if(xbin != 1) latexLabel.DrawLatex(xpos, ypos, Form("%.0f^{+%.0f}_{-%.0f}%% (%.0f/%.0f)(%.f-%.f)GeV",mean*100, errUp*100, errDown*100, pass, tot, pt[xbin-1],pt[xbin])); gFakeRatePt->SetPoint (xbin-1, xcen, mean); gFakeRatePt->SetPointEYhigh(xbin-1, errUp); gFakeRatePt->SetPointEYlow (xbin-1, errDown); gFakeRatePt->SetPointEXhigh(xbin-1, hFakeRate->GetXaxis()->GetBinLowEdge(xbin+1) - xcen); gFakeRatePt->SetPointEXlow (xbin-1, xcen - hFakeRate->GetXaxis()->GetBinLowEdge(xbin)); }//pt loop c1.Clear(); c1.SetLogx(1); //c1.SetGrid(); gFakeRatePt->Draw("ap*"); string outName = Form("WJetsFakeRatePt-Eta%.1fto%.1f-", hFakeRate->GetYaxis()->GetBinLowEdge(ybin), hFakeRate->GetYaxis()->GetBinLowEdge(ybin+1)); replace(outName.begin(), outName.end(), '.', 'p'); outName += useElectrons ? "Elec" : "Muon"; outName += useData ? "Data" : "MC"; outName += !useData && doSystematics ? "Sys" : ""; outName += doWLep ? "WLep" : "ZLep"; outName += ".pdf"; c1.Print(outName.c_str()); }//eta loop c1.Clear(); c1.SetLogx(1); string outName = "FakeRate"; outName += useElectrons ? "Elec" : "Muon"; outName += useData ? "Data" : "MC"; outName += !useData && doSystematics ? "Sys" : ""; outName += doWLep ? "WLep" : "ZLep"; outName += ".pdf"; c1.Print(outName.c_str()); //Now make profiles c1.Clear(); c1.SetLogx(0); //c1.SetGrid(); TH1D* hFakeRateNumEta = hFakeRateNum->ProjectionY("hFakeRateNumEta", 0, -1, "e"); TH1D* hFakeRateAllEta = hFakeRateAll->ProjectionY("hFakeRateAllEta", 0, -1, "e"); //TH1D* hFakeRateEta = (TH1D*) hFakeRateNumEta->Clone("hFakeRateEta"); int n = hFakeRateAllEta->GetXaxis()->GetNbins(); TGraphAsymmErrors* hFakeRateEta = new TGraphAsymmErrors(n);//hFakeRateNumEta, hFakeRateAllEta); hFakeRateEta->SetMaximum(1.); hFakeRateEta->SetMinimum(0.); hFakeRateEta->SetTitle((title + ";#eta;Rate").c_str()); //hFakeRateEta->SetMarkerStyle(21); for(int xbin = 1; xbin <= n; ++xbin){ float x = hFakeRateAllEta->GetXaxis()->GetBinCenter(xbin); float pass = hFakeRateNumEta->GetBinContent(xbin); float tot = hFakeRateAllEta->GetBinContent(xbin); float mean = tot>0 ? pass / tot : 0.; float errUp = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1); float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1); errDown = max(errDown, (float) 0.); hFakeRateEta->SetPoint (xbin, x, mean); hFakeRateEta->SetPointEYhigh(xbin, errUp); hFakeRateEta->SetPointEYlow (xbin, errDown); //printf("bin: %i, x=%.0f, %.0f/%.0f = %.0f +%.0f -%.0f\n", xbin, x, pass, tot, mean*100, errUp*100, errDown*100); } //hFakeRateEta->Divide(hFakeRateAllEta); //hFakeRateEta->Scale(100.); hFakeRateEta->Draw("ap*"); outName = "FakeRateEta"; outName += useElectrons ? "Elec" : "Muon"; outName += useData ? "Data" : "MC"; outName += !useData && doSystematics ? "Sys" : ""; outName += doWLep ? "WLep" : "ZLep"; outName += ".pdf"; c1.Print(outName.c_str()); //Pt projections (split these by eta?) c1.Clear(); c1.SetLogx(1); //c1.SetGrid(); TH1D* hFakeRateNumPt = hFakeRateNum->ProjectionX("hFakeRateNumPt", 0, -1, "e"); TH1D* hFakeRateAllPt = hFakeRateAll->ProjectionX("hFakeRateAllPt", 0, -1, "e"); //TH1D* hFakeRatePt = (TH1D*) hFakeRateNumPt->Clone("hFakeRatePt"); n = hFakeRateAllPt->GetXaxis()->GetNbins(); TGraphAsymmErrors* hFakeRatePt = new TGraphAsymmErrors(n);//hFakeRateNumPt, hFakeRateAllPt); hFakeRatePt->SetMaximum(1.); hFakeRatePt->SetMinimum(0.); hFakeRatePt->SetTitle((title + ";p_{T} (GeV);Rate").c_str()); for(int xbin = 1; xbin <= n; ++xbin){ float x = hFakeRateAllPt->GetXaxis()->GetBinCenter(xbin); float pass = hFakeRateNumPt->GetBinContent(xbin); float tot = hFakeRateAllPt->GetBinContent(xbin); float mean = tot>0 ? pass / tot : 0.; float errUp = TEfficiency::ClopperPearson(tot, pass, 0.68, true) - mean;//hFakeRateEff->GetErrorYhigh(bin-1); float errDown = mean - TEfficiency::ClopperPearson(tot, pass, 0.68, false);//hFakeRateEff->GetErrorYlow(bin-1); errDown = max(errDown, (float) 0.); hFakeRatePt->SetPoint (xbin, x, mean); hFakeRatePt->SetPointEYhigh(xbin, errUp); hFakeRatePt->SetPointEYlow (xbin, errDown); //cout<<"low edge is "<<hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin)<<" up edge is " // <<hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin+1)<<endl; hFakeRatePt->SetPointEXhigh(xbin, hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin+1) - x); hFakeRatePt->SetPointEXlow (xbin, x - hFakeRateAllPt->GetXaxis()->GetBinLowEdge(xbin)); printf("bin: %i, x=%.0f, %.0f/%.0f = %.0f +%.0f -%.0f\n", xbin, x, pass, tot, mean*100, errUp*100, errDown*100); } //hFakeRatePt->Divide(hFakeRateAllPt); //hFakeRatePt->Scale(100.); hFakeRatePt->Draw("ap*"); outName = "FakeRatePt"; outName += useElectrons ? "Elec" : "Muon"; outName += useData ? "Data" : "MC"; outName += !useData && doSystematics ? "Sys" : ""; outName += doWLep ? "WLep" : "ZLep"; outName += ".pdf"; c1.Print(outName.c_str()); } }
bool is_vowel(char c) { const string vowels { "aeiou" }; return vowels.find(tolower(c)) != string::npos; }
bool Player::parseLine(const string& s) { if(((Damageable*)this)->parseLine(s)) return true; size_t limiter = s.find("="); if (limiter == string::npos) limiter = s.find(":"); string areaS; if (limiter != string::npos) { areaS = s.substr(0, limiter); if (areaS.compare("manapool") == 0) { SAFE_DELETE(manaPool); manaPool = new ManaPool(this); ManaCost::parseManaCost(s.substr(limiter + 1), manaPool); return true; } else if (areaS.compare("mode") == 0) { this->playMode = (Player::Mode)atoi(s.substr(limiter + 1).c_str()); return true; } else if (areaS.compare("avatar") == 0) { mAvatarName = s.substr(limiter + 1); loadAvatar(mAvatarName, "bakaAvatar"); return true; } else if (areaS.compare("customphasering") == 0) { phaseRing = s.substr(limiter + 1); return true; } else if (areaS.compare("premade") == 0) { premade = (atoi(s.substr(limiter + 1).c_str())==1); return true; } else if (areaS.compare("deckfile") == 0) { deckFile = s.substr(limiter + 1); if(playMode == Player::MODE_AI) { sscanf(deckFile.c_str(), "ai/baka/deck%i.txt", &deckId); int deckSetting = EASY; if ( opponent() ) { bool isOpponentAI = opponent()->isAI() == 1; DeckMetaData *meta = observer->getDeckManager()->getDeckMetaDataByFilename( opponent()->deckFile, isOpponentAI); if ( meta && meta->getVictoryPercentage() >= 65) deckSetting = HARD; } SAFE_DELETE(mDeck); SAFE_DELETE(game); mDeck = NEW MTGDeck(deckFile.c_str(), MTGCollection(),0, deckSetting); game = NEW MTGPlayerCards(mDeck); // This automatically sets the observer pointer on all the deck cards game->setOwner(this); deckName = mDeck->meta_name; } return true; } else if (areaS.compare("deckfilesmall") == 0) { deckFileSmall = s.substr(limiter + 1); return true; } else if (areaS.compare("offerinterruptonphase") == 0) { for (int i = 0; i < NB_MTG_PHASES; i++) { string phaseStr = Constants::MTGPhaseCodeNames[i]; if (s.find(phaseStr) != string::npos) { offerInterruptOnPhase = PhaseRing::phaseStrToInt(phaseStr); return true; } } } } if(!game) { game = new MTGPlayerCards(); game->setOwner(this); } if(game->parseLine(s)) return true; return false; }
void setPosition(string &input, std::vector<string> &inputVector, Board &board) { string pos; if (input.find("startpos") != string::npos) pos = STARTPOS; if (input.find("fen") != string::npos) { if (inputVector.size() < 7 || inputVector.at(6) == "moves") { pos = inputVector.at(2) + ' ' + inputVector.at(3) + ' ' + inputVector.at(4) + ' ' + inputVector.at(5); } else { pos = inputVector.at(2) + ' ' + inputVector.at(3) + ' ' + inputVector.at(4) + ' ' + inputVector.at(5) + ' ' + inputVector.at(6) + ' ' + inputVector.at(7); } } board = fenToBoard(pos); twoFoldPositions[0].clear(); if (input.find("moves") != string::npos) { string moveList = input.substr(input.find("moves") + 6); std::vector<string> moveVector = split(moveList, ' '); for (unsigned i = 0; i < moveVector.size(); i++) { // moveStr contains the move in long algebraic notation string moveStr = moveVector.at(i); int startSq = 8 * (moveStr.at(1) - '1') + (moveStr.at(0) - 'a'); int endSq = 8 * (moveStr.at(3) - '1') + (moveStr.at(2) - 'a'); int color = board.getPlayerToMove(); bool isCapture = (bool)(INDEX_TO_BIT[endSq] & board.getAllPieces(color ^ 1)); bool isPawnMove = (bool)(INDEX_TO_BIT[startSq] & board.getPieces(color, PAWNS)); bool isKingMove = (bool)(INDEX_TO_BIT[startSq] & board.getPieces(color, KINGS)); bool isEP = (isPawnMove && !isCapture && ((endSq - startSq) & 1)); bool isDoublePawn = (isPawnMove && abs(endSq - startSq) == 16); bool isCastle = (isKingMove && abs(endSq - startSq) == 2); string promotionString = " nbrq"; int promotion = (moveStr.length() == 5) ? promotionString.find(moveStr.at(4)) : 0; Move m = encodeMove(startSq, endSq); m = setCapture(m, isCapture); m = setCastle(m, isCastle); if (isEP) m = setFlags(m, MOVE_EP); else if (promotion) { m = setFlags(m, MOVE_PROMO_N + promotion - 1); } else if (isDoublePawn) m = setFlags(m, MOVE_DOUBLE_PAWN); // Record positions on two fold stack. twoFoldPositions[0].push(board.getZobristKey()); // The stack is cleared for captures, pawn moves, and castles, which are all // irreversible if (isCapture || isPawnMove || isCastle) twoFoldPositions[0].clear(); board.doMove(m, color); } } }