void SelGenSchemaPage::refreshSchemas(pgConn *connection) { schemasHM.clear(); schemasNames.Clear(); schemasNames.Add(wxT("Not schema selected")); // Search schemas and insert them wxString restr = wxT(" WHERE ") wxT("NOT ") wxT("((nspname = 'pg_catalog' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'pg_class' AND relnamespace = nsp.oid LIMIT 1)) OR\n") wxT("(nspname = 'pgagent' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'pga_job' AND relnamespace = nsp.oid LIMIT 1)) OR\n") wxT("(nspname = 'information_schema' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'tables' AND relnamespace = nsp.oid LIMIT 1)) OR\n") wxT("(nspname LIKE '_%' AND EXISTS (SELECT 1 FROM pg_proc WHERE proname='slonyversion' AND pronamespace = nsp.oid LIMIT 1)) OR\n") wxT("(nspname = 'dbo' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'systables' AND relnamespace = nsp.oid LIMIT 1)) OR\n") wxT("(nspname = 'sys' AND EXISTS (SELECT 1 FROM pg_class WHERE relname = 'all_tables' AND relnamespace = nsp.oid LIMIT 1)))\n"); if (connection->EdbMinimumVersion(8, 2)) { restr += wxT(" AND nsp.nspparent = 0\n"); // Do not show dbms_job_procedure in schemas if (!settings->GetShowSystemObjects()) restr += wxT("AND NOT (nspname = 'dbms_job_procedure' AND EXISTS(SELECT 1 FROM pg_proc WHERE pronamespace = nsp.oid and proname = 'run_job' LIMIT 1))\n"); } wxString sql; if (connection->BackendMinimumVersion(8, 1)) { sql = wxT("SELECT CASE WHEN nspname LIKE E'pg\\\\_temp\\\\_%' THEN 1\n") wxT(" WHEN (nspname LIKE E'pg\\\\_%') THEN 0\n"); } else { sql = wxT("SELECT CASE WHEN nspname LIKE 'pg\\\\_temp\\\\_%' THEN 1\n") wxT(" WHEN (nspname LIKE 'pg\\\\_%') THEN 0\n"); } sql += wxT(" ELSE 3 END AS nsptyp, nspname, nsp.oid\n") wxT(" FROM pg_namespace nsp\n") + restr + wxT(" ORDER BY 1, nspname"); pgSet *schemas = connection->ExecuteSet(sql); wxTreeItemId parent; if (schemas) { while (!schemas->Eof()) { wxString name = schemas->GetVal(wxT("nspname")); long nsptyp = schemas->GetLong(wxT("nsptyp")); wxStringTokenizer tokens(settings->GetSystemSchemas(), wxT(",")); while (tokens.HasMoreTokens()) { wxRegEx regex(tokens.GetNextToken()); if (regex.Matches(name)) { nsptyp = SCHEMATYP_USERSYS; break; } } if (nsptyp <= SCHEMATYP_USERSYS && !settings->GetShowSystemObjects()) { schemas->MoveNext(); continue; } schemasNames.Add(name); schemasHM[name] = schemas->GetOid(wxT("oid")); schemas->MoveNext(); } delete schemas; } }
#include "parser.h" regex hex_reg = regex("(0x)([0-9A-Fa-f]+)"); regex dec_reg = regex("(0d){0,1}([0-9\-]+)"); immediateType resolveImmediate(const string& strImmediate, bool signExtend) { smatch results; unsigned __int16 imm16; if (regex_match(strImmediate, hex_reg)) { regex_search(strImmediate, results, hex_reg); stringstream ss(results[2]); ss >> hex >> imm16; } else if (regex_match(strImmediate, dec_reg)) { regex_search(strImmediate, results, dec_reg); stringstream ss(results[2]); ss >> imm16; } else { throw invalid_argument("Invalid immediate: Unable to parse the immediate field"); } if (signExtend) { int value = (0x0000FFFF & imm16); int mask = 0x00008000; if (mask & imm16) { value += 0xFFFF0000; } return value;
bool ChecksumImpl::is_valid( const string& value ) { return regex_match( value, regex( "^[0-9a-fA-F]+$" ) ); }
void SRTMProvider::createFileList() { QStringList continents; continents << "Africa" << "Australia" << "Eurasia" << "Islands" << "North_America" << "South_America"; QString url = _url.toString(); QStringList dateiListe; int capCount = 0; int lat; int lon; int pos = 0; foreach (QString continent, continents) { // für jeden Kontinent, die vorhandenen Ziparchive in die Liste eintragen QString urlTemp = QString(url+continent+"/").toAscii().constData(); // Kontinent zur url hinzufügen QUrl srtmUrl(urlTemp); // urlTemp zu QUrl casten, für spätere Verwendung. QString replyString; // Hierein wird später die NetworkReply aus downloadUrl gespeichert. downloadUrl(srtmUrl, replyString); if(!replyString.isEmpty()) // Erstellen der Liste, falls Download erfolgreich. { QRegExp regex("<li>\\s*<a\\s+href=\"([^\"]+)"); regex.indexIn(replyString); pos = 0; capCount = 0; dateiListe.clear(); while ((pos = regex.indexIn(replyString, pos)) != -1) { dateiListe << regex.cap(1); pos += regex.matchedLength(); capCount++; } QRegExp innerRx("([NS])(\\d{2})([EW])(\\d{3})"); for (int i = 0; i < capCount; i++){ int po = innerRx.indexIn(dateiListe[i]); if (po > -1){ lat = innerRx.cap(2).toInt(); lon = innerRx.cap(4).toInt(); if (innerRx.cap(1) == "S") { lat = -lat; } if (innerRx.cap(3) == "W") { lon = - lon; } //S00E000.hgt.zip //123456789012345 => 15 bytes long fileList[latLonToIndex(lat, lon)] = continent+"/"+dateiListe[i].right(15); } } } else { std::cout << "Fehler beim laden der Daten für " << continent << "." << std::endl; } } // end: foreach(QString continent, continents)
void PointViewerMainWindow::handleMessage(QByteArray message) { QList<QByteArray> commandTokens = message.split('\n'); if (commandTokens.empty()) return; if (commandTokens[0] == "OPEN_FILES") { QList<QByteArray> flags = commandTokens[1].split('\0'); bool replaceLabel = flags.contains("REPLACE_LABEL"); bool deleteAfterLoad = flags.contains("DELETE_AFTER_LOAD"); for (int i = 2; i < commandTokens.size(); ++i) { QList<QByteArray> pathAndLabel = commandTokens[i].split('\0'); if (pathAndLabel.size() != 2) { g_logger.error("Unrecognized OPEN_FILES token: %s", QString(commandTokens[i])); continue; } FileLoadInfo loadInfo(pathAndLabel[0], pathAndLabel[1], replaceLabel); loadInfo.deleteAfterLoad = deleteAfterLoad; m_fileLoader->loadFile(loadInfo); } } else if (commandTokens[0] == "CLEAR_FILES") { m_geometries->clear(); } else if (commandTokens[0] == "UNLOAD_FILES") { QString regex_str = commandTokens[1]; QRegExp regex(regex_str, Qt::CaseSensitive, QRegExp::WildcardUnix); if (!regex.isValid()) { g_logger.error("Invalid pattern in -unload command: '%s': %s", regex_str, regex.errorString()); return; } m_geometries->unloadFiles(regex); } else if (commandTokens[0] == "SET_VIEW_POSITION") { if (commandTokens.size()-1 != 3) { tfm::format(std::cerr, "Expected three coordinates, got %d\n", commandTokens.size()-1); return; } bool xOk = false, yOk = false, zOk = false; double x = commandTokens[1].toDouble(&xOk); double y = commandTokens[2].toDouble(&yOk); double z = commandTokens[3].toDouble(&zOk); if (!zOk || !yOk || !zOk) { std::cerr << "Could not parse XYZ coordinates for position\n"; return; } m_pointView->setExplicitCursorPos(Imath::V3d(x, y, z)); } else if (commandTokens[0] == "SET_VIEW_ANGLES") { if (commandTokens.size()-1 != 3) { tfm::format(std::cerr, "Expected three view angles, got %d\n", commandTokens.size()-1); return; } bool yawOk = false, pitchOk = false, rollOk = false; double yaw = commandTokens[1].toDouble(&yawOk); double pitch = commandTokens[2].toDouble(&pitchOk); double roll = commandTokens[3].toDouble(&rollOk); if (!yawOk || !pitchOk || !rollOk) { std::cerr << "Could not parse Euler angles for view\n"; return; } m_pointView->camera().setRotation( QQuaternion::fromAxisAndAngle(0,0,1, roll) * QQuaternion::fromAxisAndAngle(1,0,0, pitch-90) * QQuaternion::fromAxisAndAngle(0,0,1, yaw) ); } else if (commandTokens[0] == "SET_VIEW_RADIUS") { bool ok = false; double viewRadius = commandTokens[1].toDouble(&ok); if (!ok) { std::cerr << "Could not parse view radius"; return; } m_pointView->camera().setEyeToCenterDistance(viewRadius); } else if (commandTokens[0] == "QUERY_CURSOR") { // Yuck! IpcChannel* channel = dynamic_cast<IpcChannel*>(sender()); if (!channel) { qWarning() << "Signalling object not a IpcChannel!\n"; return; } V3d p = m_pointView->cursorPos(); std::string response = tfm::format("%.15g %.15g %.15g", p.x, p.y, p.z); channel->sendMessage(QByteArray(response.data(), (int)response.size())); } else if (commandTokens[0] == "QUIT") { close(); } else if (commandTokens[0] == "SET_MAX_POINT_COUNT") { m_maxPointCount = commandTokens[1].toLongLong(); } else if (commandTokens[0] == "OPEN_SHADER") { openShaderFile(commandTokens[1]); } else if(commandTokens[0] == "HOOK") { IpcChannel* channel = dynamic_cast<IpcChannel*>(sender()); if (!channel) { qWarning() << "Signalling object not a IpcChannel!\n"; return; } for(int i=1; i<commandTokens.count(); i+=2) { HookFormatter* formatter = new HookFormatter(this, commandTokens[i], commandTokens[i+1], channel); m_hookManager->connectHook(commandTokens[i], formatter); } } else { g_logger.error("Unkown remote message:\n%s", QString::fromUtf8(message)); } }
static void process_message(wchar_t *MSNTitle) { char *s = wchar_to_utf8(MSNTitle); static char player[STRLEN] = ""; char enabled[STRLEN], format[STRLEN], title[STRLEN], artist[STRLEN], album[STRLEN], uuid[STRLEN]; enabled[0] = '0'; // this has to be escaped quite carefully to prevent literals being interpreted as metacharacters by the compiler or in the pcre pattern // so yes, four \ before a 0 is required to match a literal \0 in the regex :-) // and marking the regex as ungreedy is a lot easier than writing \\\\0([^\\\\0]*)\\\\0 :) pcre *re1 = regex("^(.*)\\\\0Music\\\\0(.*)\\\\0(.*)\\\\0(.*)\\\\0(.*)\\\\0(.*)\\\\0(.*)\\\\0", PCRE_UNGREEDY); pcre *re2 = regex("^(.*)\\\\0Music\\\\0(.*)\\\\0(.*)\\\\0(.*)\\\\0(.*)\\\\0(.*)\\\\0", PCRE_UNGREEDY); pcre *re3 = regex("^(.*)\\\\0Music\\\\0(.*)\\\\0(.*) - (.*)\\\\0$", 0); if (capture(re1, s, strlen(s), player, enabled, format, title, artist, album, uuid) > 0) { trace("player '%s', enabled '%s', format '%s', title '%s', artist '%s', album '%s', uuid '%s'", player, enabled, format, title, artist, album, uuid); msnti.player = player; strncpy(msnti.artist, artist, STRLEN); msnti.artist[STRLEN-1] = 0; strncpy(msnti.album, album, STRLEN); msnti.album[STRLEN-1] = 0; strncpy(msnti.track, title, STRLEN); msnti.track[STRLEN-1] = 0; } else if (capture(re2, s, strlen(s), player, enabled, format, artist, title) > 0) { trace("player '%s', enabled '%s', format '%s', title '%s', artist '%s'", player, enabled, format, title, artist); msnti.player = player; strncpy(msnti.artist, artist, STRLEN); msnti.artist[STRLEN-1] = 0; strncpy(msnti.album, album, STRLEN); msnti.album[STRLEN-1] = 0; strncpy(msnti.track, title, STRLEN); msnti.track[STRLEN-1] = 0; } else if (capture(re3, s, strlen(s), player, enabled, artist, title) > 0) { trace("player '%s', enabled '%s', artist '%s', title '%s'", player, enabled, artist, title); msnti.player = player; strncpy(msnti.artist, artist, STRLEN); msnti.artist[STRLEN-1] = 0; msnti.album[0] = 0; strncpy(msnti.track, title, STRLEN); msnti.track[STRLEN-1] = 0; } else { msnti.status = STATUS_OFF; } pcre_free(re1); pcre_free(re2); pcre_free(re3); // // Winamp seems to generate messages with enabled=1 but all the fields empty when it stops, so we need to // check if any fields have non-empty values as well as looking at that flag // if ((strncmp(enabled, "1", 1) == 0) && ((strlen(msnti.artist) > 0) || (strlen(msnti.track) > 0) || (strlen(msnti.album) > 0))) { msnti.status = STATUS_NORMAL; } else { msnti.status = STATUS_OFF; } // // Some players have artist and title the other way around // (As "{0} - {1}","artist","title" and "{1} - {0}","title","artist" are equivalent, // but which field is actually artist and title isn't described by the message) // if (purple_prefs_get_bool(PREF_MSN_SWAP_ARTIST_TITLE)) { char swap[STRLEN]; strncpy(swap, msnti.artist, STRLEN); swap[STRLEN-1] = 0; strncpy(msnti.artist, msnti.track, STRLEN); msnti.artist[STRLEN-1] = 0; strncpy(msnti.track, swap, STRLEN); msnti.track[STRLEN-1] = 0; } // // Usually we don't find out the actual player name, so report it as unknown... // if ((msnti.player == 0) || (strlen(msnti.player) == 0)) { msnti.player = "Unknown"; } free(s); }
//from stack overflow string do_replace( string const & in, string const & from, string const & to ) { return regex_replace( in, regex(from), to ); }
void Wall::modwallCmd(const QString &from, const QStringList &list) { octAssert(list.size() < 3); int num = list[0].toInt(); QString replacement = QString::null; if (list[1] != "") replacement = list[1]; // Read the current wall and store it in a list QFile fwall(manager()->dataDir() + "/wall"); if (!fwall.open(QIODevice::ReadOnly)) { octInfo("Could not read wall file\n"); return; } QTextStream stream(&fwall); QString line; QStringList l; while ((line = stream.readLine()) != QString::null) l << line; fwall.close(); if (!l.count()) { manager()->connectionPlugin()->serverSend(from, "Wall is empty"); return; } if (!num || (num > l.count())) { manager()->connectionPlugin()->serverSend(from, "Invalid wall line number"); return; } // Remove the element and save the file QStringList::Iterator it = l.end(); for (;num > 0; --num) it--; QString message = *it; if(replacement.isNull()) l.erase(it); else { QRegExp regex("(([\\d/]+) ([\\d:]+) ([\\w ]{8}) )(.*)"); //@attention Wall format dependant if(regex.exactMatch(message)) { // should always be the case, we just want to get the datas replacement = regex.cap(1) + replacement; *it = replacement; } } QFile fout(manager()->dataDir() + "/wall"); if (!fout.open(QIODevice::WriteOnly)) { octInfo("Could not write wall file\n"); return; } QTextStream streamOut(&fout); for (it = l.begin(); it != l.end(); it++) streamOut << *it + "\n"; fout.close(); loadWall(); // Send messages manager()->connectionPlugin()->serverSend(from, "You modify the wall "); manager()->connectionPlugin()->serverBroadcastOthers(from, from + " modifies the wall "); manager()->logPlugin()->write("modwall", from + " modifies the wall :\n - " + message + "\n + " + replacement); }
int main(int argument_count, char** argument_values) { try { opt::options_description description( "Solves circuit500 levels.\n\n" "All operations are performed in the 'data/' directory relative to the current\n" "working directory, which should already exist and contain some reference images\n" "for the solver inside 'data/reference/'.\n\n" "Screenshots of the levels should be placed inside the 'data/raw/' directory.\n\n" "During the preparation phase the program extracts the level number from the\n" "screenshots and places a normalized version of the level area in an\n" "appropriately named file inside the 'data/levels/' directory.\n\n" "During the solving phase the program attempts to solve the levels and\n" "puts solutions in the 'data/solutions/' directory.\n\n" "Options"); description.add_options() ("help", "Prints this help message.\n") ("log,l", "Logs statistics about the solving phase into a log file inside 'data/logs/'.\n") ("dry,d", "Does not save solutions during the solving phase.\n") ("unsolved,u", "Solves only those levels for which it cannot already find a solution inside " "'data/solutions/'.\n") ("taps,t", opt::value<std::string>()->default_value("3"), ("Specifies the maximum number of taps to check for solutions.\n" "Must be between " + std::to_string(Solver::tap_minimum()) + " and " + std::to_string(Solver::tap_maximum()) + " (both inclusive).\n").c_str()) ("prepare,p", opt::value<std::vector<std::string>>()->multitoken(), "Prepares the specified files.\n" "Must be followed by one or more filenames.\n" "Filenames must not include 'data/raw/'.\n") ("prepare-all,P", "Prepares all files in 'data/raw/'.\n") ("solve,s", opt::value<std::vector<std::string>>()->multitoken(), "Solves the specified levels.\n" "Must be followed by one or more level descriptions in the form of:\n" " X: \twhere X is a level number between 1 and 500. " "Solves the specified level.\n" " X-Y: \twhere X and Y are level numbers between 1 and 500 and X is less than or " "equal to Y. Solves all levels between X and Y (both inclusive).\n") ("solve-all,S", "Solves all levels.\n") ("handle,h", opt::value<std::vector<std::string>>()->multitoken(), "Prepares the specified files and solves the levels they contain.\n") ("handle-all,H", "Handles all files in 'data/raw/'.\n") ; opt::options_description helper_description; helper_description.add_options() ("__unrecognized__", opt::value<std::vector<std::string>>()) ; opt::options_description cmdline_options; cmdline_options.add(description).add(helper_description); opt::positional_options_description positional_description; positional_description.add("__unrecognized__", -1); opt::variables_map variables; opt::store(opt::command_line_parser(argument_count, argument_values) .options(cmdline_options).positional(positional_description).run(), variables); opt::notify(variables); if (variables.count("__unrecognized__")) throw std::runtime_error("unexpected argument: '" + variables["__unrecognized__"].as<std::vector<std::string>>()[0] + "'"); check_conflicting_options(variables, "handle-all", "handle"); check_conflicting_options(variables, "solve-all", "solve"); check_conflicting_options(variables, "prepare-all", "prepare"); if (variables.count("help")) { std::cout << description << std::endl; } fs::path reference_dir("data/reference/"); if (!fs::is_directory(reference_dir)) { std::string error("could not find directory '" + reference_dir.string() + "'"); if (!variables.count("help")) error.append("; use '--help' to get more information"); throw std::runtime_error(error); } if (argument_count == 1) { // No options std::cout << "use '--help' to get usage information" << std::endl; } create_directory_if_not_exists("data/levels/"); create_directory_if_not_exists("data/raw/"); create_directory_if_not_exists("data/solutions/"); create_directory_if_not_exists("data/logs/"); std::vector<fs::path> files_to_prepare; std::vector<fs::path> files_to_handle; Level_Set levels_to_solve; if (variables.count("prepare-all")) { for (auto&& entry : fs::directory_iterator("data/raw/")) { files_to_prepare.push_back(entry.path()); } } if (variables.count("prepare")) { fs::path dir = "data/raw"; std::vector<std::string> input_list = variables["prepare"].as<std::vector<std::string>>(); for (auto&& entry : input_list) { files_to_prepare.push_back(dir / entry); } } if (variables.count("handle-all")) { for (auto&& entry : fs::directory_iterator("data/raw/")) { files_to_handle.push_back(entry.path()); } } if (variables.count("handle")) { fs::path dir = "data/raw"; std::vector<std::string> input_list = variables["handle"].as<std::vector<std::string>>(); for (auto&& entry : input_list) { files_to_handle.push_back(dir / entry); } } if (variables.count("solve-all")) { levels_to_solve.set_all(); } if (variables.count("solve")) { std::vector<std::string> input_list = variables["solve"].as<std::vector<std::string>>(); Level_Set_Parser(input_list, levels_to_solve).parse(); } int max_taps; { std::string text = variables["taps"].as<std::string>(); std::regex regex("\\d{1,3}"); std::smatch match; if (!regex_match(text, match, regex)) throw std::runtime_error("expected tap count, but found: '" + text + "'"); max_taps = std::stoi(match[0]); if (max_taps < Solver::tap_minimum()) throw std::runtime_error("tap count must be " + std::to_string(Solver::tap_minimum()) + " or more, but was: '" + text + "'"); if (max_taps > Solver::tap_maximum()) throw std::runtime_error("tap count must be " + std::to_string(Solver::tap_maximum()) + " or less, but was: '" + text + "'"); } std::string header; // create header for log // contains normalized list of arguments // normalized means not all arguments are mentioned, // the long form is always used and the order is fixed { if (variables.count("log")) header += " --log"; if (levels_to_solve.is_full()) { header += " --solve-all"; } else if (!levels_to_solve.is_empty()) { header += " --solve"; size_t low = level_begin, high; while (true) { while (low != level_end && !levels_to_solve.is_set(low)) ++low; high = low; while (high != level_end && levels_to_solve.is_set(high)) ++high; if (low == level_end) break; header += " " + std::to_string(low); if (high - low > 1) header += "-" + std::to_string(high - 1); low = high; } } if (variables.count("unsolved")) header += " --unsolved"; header += " --taps " + std::to_string(max_taps); if (!header.empty()) header.erase(0, 1); } Logger* logger = variables.count("log") ? Logger::create_file_logger(header) : Logger::create_fake_logger(header); if (!logger) throw std::runtime_error("out of memory: failed to create logger"); prepare_and_handle_files(files_to_prepare, files_to_handle, levels_to_solve); solve_levels(levels_to_solve, variables, max_taps, *logger); delete logger; return EXIT_SUCCESS; } catch(std::exception& e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } }
bool Request::match(string pattern) { key = method + ":" + url; return regex_match(key, matches, regex(pattern)); }
project_info& project_state::load(const std::string& id) { std::string file = get_config_path() + "/" + id + ".prj"; std::ifstream f(file); if(!f) throw std::runtime_error("Can't open project file"); project_info& pi = *new project_info(edispatch); pi.id = id; pi.movie_rtc_second = 1000000000; pi.movie_rtc_subsecond = 0; pi.active_branch = 0; pi.next_branch = 0; pi.filename = file; //First line is always project name. std::getline(f, pi.name); if(!f || pi.name == "") { delete π throw std::runtime_error("Can't read project file"); } while(f) { std::string tmp; std::getline(f, tmp); regex_results r; if(r = regex("rom=(.+)", tmp)) pi.rom = r[1]; else if(r = regex("last-save=(.+)", tmp)) pi.last_save = r[1]; else if(r = regex("directory=(.+)", tmp)) pi.directory = r[1]; else if(r = regex("prefix=(.+)", tmp)) pi.prefix = r[1]; else if(r = regex("luascript=(.+)", tmp)) pi.luascripts.push_back(r[1]); else if(r = regex("gametype=(.+)", tmp)) pi.gametype = r[1]; else if(r = regex("coreversion=(.+)", tmp)) pi.coreversion = r[1]; else if(r = regex("gamename=(.+)", tmp)) pi.gamename = r[1]; else if(r = regex("projectid=(.+)", tmp)) pi.projectid = r[1]; else if(r = regex("projectid=([0-9]+):([0-9]+)", tmp)) { pi.movie_rtc_second = parse_value<int64_t>(r[1]); pi.movie_rtc_subsecond = parse_value<int64_t>(r[2]); } else if(r = regex("author=(.*)\\|(.*)", tmp)) pi.authors.push_back(std::make_pair(r[1], r[2])); else if(r = regex("author=(.+)", tmp)) pi.authors.push_back(std::make_pair(r[1], "")); else if(r = regex("romsha=([0-9a-f]+)", tmp)) pi.romimg_sha256[0] = r[1]; else if(r = regex("slotsha([a-z])=([0-9a-f]+)", tmp)) pi.romimg_sha256[r[1][0] - 96] = r[2]; else if(r = regex("romxml=([0-9a-f]+)", tmp)) pi.romxml_sha256[0] = r[1]; else if(r = regex("slotxml([a-z])=([0-9a-f]+)", tmp)) pi.romxml_sha256[r[1][0] - 96] = r[2]; else if(r = regex("romhint=(.*)", tmp)) pi.namehint[0] = r[1]; else if(r = regex("slothint([a-z])=(.*)", tmp)) pi.namehint[r[1][0] - 96] = r[2]; else if(r = regex("romrom=(.*)", tmp)) pi.roms[0] = r[1]; else if(r = regex("slotrom([a-z])=(.*)", tmp)) pi.roms[r[1][0] - 96] = r[2]; else if(r = regex("setting.([^=]+)=(.*)", tmp)) pi.settings[r[1]] = r[2]; else if(r = regex("watch.([^=]+)=(.*)", tmp)) pi.watches[eq_unescape(r[1])] = r[2]; else if(r = regex("sram.([^=]+)=(.*)", tmp)) concatenate(pi.movie_sram[r[1]], base_decode(r[2])); else if(r = regex("macro.([^=]+)=(.*)", tmp)) try { pi.macros[r[1]] = JSON::node(r[2]); } catch(std::exception& e) { messages << "Unable to load macro '" << r[1] << "': " << e.what() << std::endl; } else if(r = regex("anchor=(.*)", tmp)) concatenate(pi.anchor_savestate, base_decode(r[1])); else if(r = regex("time=([0-9]+):([0-9]+)", tmp)) { pi.movie_rtc_second = parse_value<int64_t>(r[1]); pi.movie_rtc_subsecond = parse_value<int64_t>(r[2]); } else if(r = regex("branch([1-9][0-9]*)parent=([0-9]+)", tmp)) { uint64_t bid = parse_value<int64_t>(r[1]); uint64_t pbid = parse_value<int64_t>(r[2]); if(!pi.branches.count(bid)) pi.branches[bid].name = "(Unnamed branch)"; pi.branches[bid].pbid = pbid; } else if(r = regex("branch([1-9][0-9]*)name=(.*)", tmp)) { uint64_t bid = parse_value<int64_t>(r[1]); if(!pi.branches.count(bid)) pi.branches[bid].pbid = 0; pi.branches[bid].name = r[2]; } else if(r = regex("branchcurrent=([0-9]+)", tmp)) { pi.active_branch = parse_value<int64_t>(r[1]); } else if(r = regex("branchnext=([0-9]+)", tmp)) { pi.next_branch = parse_value<int64_t>(r[1]); } } for(auto& i : pi.branches) { uint64_t j = i.first; uint64_t m = j; while(j) { j = pi.branches[j].pbid; m = min(m, j); if(j == i.first) { //Cyclic dependency! messages << "Warning: Cyclic slot branch dependency, reparenting '" << pi.branches[m].name << "' to be child of root..." << std::endl; pi.branches[j].pbid = 0; break; } } } if(pi.active_branch && !pi.branches.count(pi.active_branch)) { messages << "Warning: Current slot branch does not exist, using root..." << std::endl; pi.active_branch = 0; } return pi; }
PrefsDialog::PrefsDialog(QWidget *parent): QDialog(parent),ui(new Ui::PrefsDialog) { // map dropdown values to indices listMetadataWrite << METADATA_WRITE_NONE; listMetadataWrite << METADATA_WRITE_PREPEND; listMetadataWrite << METADATA_WRITE_APPEND; listMetadataWrite << METADATA_WRITE_OVERWRITE; // out of range for some fields listMetadataWriteKey << METADATA_WRITE_NONE; listMetadataWriteKey << METADATA_WRITE_OVERWRITE; listMetadataFormat << METADATA_FORMAT_KEYS; listMetadataFormat << METADATA_FORMAT_CUSTOM; listMetadataFormat << METADATA_FORMAT_BOTH; // UI ui->setupUi(this); this->setWindowFlags(Qt::WindowTitleHint | Qt::CustomizeWindowHint); // get values from preferences Preferences p; ui->writeToFilesAutomatically->setChecked(p.getWriteToFilesAutomatically()); ui->parallelBatchJobs->setChecked(p.getParallelBatchJobs()); ui->skipFilesWithExistingTags->setChecked(p.getSkipFilesWithExistingTags()); ui->applyFileExtensionFilter->setChecked(p.getApplyFileExtensionFilter()); ui->maxDuration->setValue(p.getMaxDuration()); ui->tagFormat->setCurrentIndex(listMetadataFormat.indexOf(p.getMetadataFormat())); ui->metadataWriteTitle->setCurrentIndex(listMetadataWrite.indexOf(p.getMetadataWriteTitle())); ui->metadataWriteArtist->setCurrentIndex(listMetadataWrite.indexOf(p.getMetadataWriteArtist())); ui->metadataWriteAlbum->setCurrentIndex(listMetadataWrite.indexOf(p.getMetadataWriteAlbum())); ui->metadataWriteComment->setCurrentIndex(listMetadataWrite.indexOf(p.getMetadataWriteComment())); ui->metadataWriteGrouping->setCurrentIndex(listMetadataWrite.indexOf(p.getMetadataWriteGrouping())); ui->metadataWriteKey->setCurrentIndex(listMetadataWriteKey.indexOf(p.getMetadataWriteKey())); ui->metadataWriteFilename->setCurrentIndex(listMetadataWrite.indexOf(p.getMetadataWriteFilename())); ui->metadataDelimiter->setText(p.getMetadataDelimiter()); ui->iTunesLibraryPath->setText(p.getITunesLibraryPath()); ui->traktorLibraryPath->setText(p.getTraktorLibraryPath()); ui->seratoLibraryPath->setText(p.getSeratoLibraryPath()); QStringList ckc = p.getCustomKeyCodes(); ui->majKey0->setText(ckc[0]); ui->minKey0->setText(ckc[1]); ui->majKey1->setText(ckc[2]); ui->minKey1->setText(ckc[3]); ui->majKey2->setText(ckc[4]); ui->minKey2->setText(ckc[5]); ui->majKey3->setText(ckc[6]); ui->minKey3->setText(ckc[7]); ui->majKey4->setText(ckc[8]); ui->minKey4->setText(ckc[9]); ui->majKey5->setText(ckc[10]); ui->minKey5->setText(ckc[11]); ui->majKey6->setText(ckc[12]); ui->minKey6->setText(ckc[13]); ui->majKey7->setText(ckc[14]); ui->minKey7->setText(ckc[15]); ui->majKey8->setText(ckc[16]); ui->minKey8->setText(ckc[17]); ui->majKey9->setText(ckc[18]); ui->minKey9->setText(ckc[19]); ui->majKey10->setText(ckc[20]); ui->minKey10->setText(ckc[21]); ui->majKey11->setText(ckc[22]); ui->minKey11->setText(ckc[23]); ui->silence->setText(ckc[24]); ui->filterFileExtensions->setText(p.getFilterFileExtensions().join(",")); // enable/disable fields as necessary metadataDelimiterEnabled(); applyFileExtensionFilterEnabled(); //relative sizing on Mac/Linux only #ifndef Q_OS_WIN QFont smallerFont; smallerFont.setPointSize(smallerFont.pointSize() - 2); for (int i=0; i<ui->gridLayoutKeyCodes->count(); i++) { if (!ui->gridLayoutKeyCodes->itemAt(i)->isEmpty() && ui->gridLayoutKeyCodes->itemAt(i)->widget()->inherits("QLabel")) { ui->gridLayoutKeyCodes->itemAt(i)->widget()->setFont(smallerFont); } } #endif // validation of file extension filtering QRegExp regex("^([a-z0-9]+,?)*$"); QValidator *validator = new QRegExpValidator(regex, this); ui->filterFileExtensions->setValidator(validator); }
void Mailbox::searchEditChanged(QString search_string) { QSortFilterProxyModel* model = dynamic_cast<QSortFilterProxyModel*>(ui->inbox_table->model()); QRegExp regex(search_string, Qt::CaseInsensitive, QRegExp::FixedString); model->setFilterRegExp(regex); }
int main(int argc, char* argv[]) { po::options_description options("Options"); // Don't use default values because the help print it ugly and too wide options.add_options() ("move,m", "move files rather than copy") ("symlink,s", "symlink files rather than copy (posix only)") ("order,o", po::value<std::string>(), "order and types of metadata to read\ne=exif, i=iptc, f=file (default: eif)") ("unsorted,u", po::value<std::string>(), "special directory to store unsorted files (default: unsorted)") ("dups,d", po::value<std::string>(), "special directory to store files with duplicate names (default: duplicates)") ("force,f", "overwrite duplicate files instead of using special directory") ("rename,r", "rename duplicate files instead of using special directory") ("ignore,i", "ignore both unsorted and duplicate files instead of using special directories") ("ignore-unsorted", "ignore unsorted files instead of using special directory") ("ignore-dups", "ignore duplicate files instead of using special directory") ("verify", "verify copied or moved files and exit if incorrect") ("exclude,x", po::value< std::vector<std::string> >(), "exclude directories and files that contain arg (case sensitive on all platforms)") ("limit-depth,l", po::value<long>(), "limit recursion to specified depth (0 disables recursion)") ("verbose,v", "prints operations as they happen") ("dry-run,n", "do not make actual changes (implies verbose)") ("help,h", "show this help message then exit") ("version,V", "show program version then exit") ; po::options_description hidden("Hidden Options"); hidden.add_options() ("source-dir", po::value< std::string >(), "directory of files to organize, may end in file wildcard") ("dest-dir", po::value< std::string >(), "desination directory for files, may not be within source-dir") ("pattern", po::value< std::string >(), "subdirectory pattern for grouping files within dest-dir") ; po::options_description cmdline; cmdline.add(options).add(hidden); po::positional_options_description positional; positional.add("source-dir", 1); positional.add("dest-dir", 1); positional.add("pattern", 1); try { po::variables_map vm; po::store(po::command_line_parser(argc, argv). options(cmdline).positional(positional).run(), vm); po::notify(vm); if (vm.count("help")) { usage_full(options, argv[0]); return 0; } if (vm.count("version")) { version(); return 0; } conflicting(vm, "verify", "symlink"); conflicting(vm, "move", "symlink"); conflicting(vm, "unsorted", "ignore"); conflicting(vm, "unsorted", "ignore-unsorted"); conflicting(vm, "dups", "ignore"); conflicting(vm, "dups", "ignore-dups"); conflicting(vm, "force", "ignore"); conflicting(vm, "force", "ignore-dups"); conflicting(vm, "force", "rename"); conflicting(vm, "rename", "ignore"); conflicting(vm, "rename", "ignore-dups"); required(vm, "source-dir"); required(vm, "dest-dir"); required(vm, "pattern"); const bool dry_run = vm.count("dry-run") != 0; g_verbose = (vm.count("verbose") != 0 || dry_run); std::string order = "eif"; if(vm.count("order")) { order = vm["order"].as<std::string>(); boost::to_lower(order); if(order.length() > 3) { throw std::logic_error(std::string("order is longer than 4 characters")); } } unsigned i = 0; std::string::iterator end = order.end(); for(std::string::iterator iter = order.begin(); iter != end && i < 4; ++iter, ++i) { switch(*iter) { case 'e': g_run_order[i] = EXIF_SLOT; break; case 'i': g_run_order[i] = IPTC_SLOT; break; case 'x': throw std::logic_error(std::string("xmp not implemented yet '") + *iter + "'"); break; case 'f': g_run_order[i] = FILE_SLOT; break; default: throw std::logic_error(std::string("unknown order character '") + *iter + "'"); } } const fs::path source_dir( vm["source-dir"].as<std::string>() ); if( !exists(source_dir) || !is_directory(source_dir) ) { throw std::logic_error(std::string("source '") + source_dir.string() + "' must exist and be a directory"); } const fs::path dest_dir( vm["dest-dir"].as<std::string>() ); if( exists(dest_dir) && !is_directory(dest_dir) ) { throw std::logic_error(std::string("destination '") + dest_dir.string() + "' must be a directory"); } // Boost doesn't seem to have a way to get a canonical path, so this // simple test is easy to confuse with some ../../'s in the paths. Oh // well, this is good enough for now. fs::path test_dest(dest_dir); for(; !test_dest.empty(); test_dest = test_dest.parent_path()) { if(fs::equivalent(source_dir, test_dest)) { throw std::logic_error(std::string("dest-dir must not be within source-dir")); } } // Disect the pattern std::string pattern = vm["pattern"].as<std::string>(); boost::regex regex( "([^@]*)(@[[:alpha:]]+)([^@]*)"); boost::sregex_iterator m_iter = make_regex_iterator(pattern, regex); boost::sregex_iterator m_end; for( ; m_iter != m_end; ++m_iter) { const boost::smatch &match = *m_iter; const std::string &pre = match[1]; const std::string &pat = match[2]; const std::string &post = match[3]; // Should put this in a map, but there aren't that many options now bool found = false; for( const Pattern *pattern = g_patterns; pattern->pat.length(); ++pattern) { if(pattern->pat == pat) { PathPart part(pre, pattern, post); g_path_parts.push_back(part); found = true; break; } } if(!found) { throw std::logic_error(std::string("unknown pattern '") + pat + "'"); } } // Assign defaults to params that need them const bool ignore = vm.count("ignore") != 0; std::vector<std::string> excludes; if(vm.count("exclude")) excludes = vm["exclude"].as< std::vector<std::string> >(); long limit_depth = LONG_MAX; if(vm.count("limit-depth")) { limit_depth = vm["limit-depth"].as<long>(); // Boost program_options doesn't work with unsigned, so do it manually if( limit_depth < 0 ) throw std::logic_error(std::string("recursion depth limit must be positive")); } std::string dups = "duplicates"; if(vm.count("dups")) dups = vm["dups"].as<std::string>(); const fs::path dups_dir = dest_dir / dups; std::string unsorted = "unsorted"; if(vm.count("unsorted")) unsorted = vm["unsorted"].as<std::string>(); const fs::path unsorted_dir = dest_dir / unsorted; ProcessParams params = { dest_dir, dry_run, (vm.count("ignore-dups") != 0 || ignore), (vm.count("ignore-unsorted") != 0 || ignore), vm.count("force") != 0, vm.count("rename") != 0, vm.count("symlink") != 0, vm.count("verify") != 0, vm.count("move") != 0, limit_depth, dups_dir, unsorted_dir, excludes, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; process_directory(source_dir, 0, params); std::string op = "copied"; if(params.symlink) op = "linked"; else if(params.move) op = "moved"; if(dry_run) op = std::string("would be ") + op; if(g_neednewline) std::cout << "\n"; std::cout << "\n" << params.ok_count << " files " << op << "\n"; std::cout << " " << params.dups_count << " duplicates\n"; std::cout << " " << params.unsorted_count << " unsorted\n"; if(params.dups_ignored_count) std::cout << params.dups_ignored_count << " duplicates ignored\n"; if(params.unsorted_ignored_count) std::cout << params.unsorted_ignored_count << " unsorted ignored\n"; if(params.dir_ex_count) std::cout << params.dir_ex_count << " directories excluded\n"; if(params.file_ex_count) std::cout << params.file_ex_count << " files excluded\n"; if(params.dir_err_count) std::cout << params.dir_err_count << " directory errors\n"; if(params.file_err_count) std::cout << params.file_err_count << " file errors\n"; return 0; } catch (Exiv2::AnyError& e) { error(e, std::string("Aborting")); return -1; } catch(std::logic_error& e) { error(e, ""); usage_header(argv[0]); std::cout << argv[0] << " -h for more help" << std::endl; return -2; } catch(std::exception& e) { error(e, "Aborting"); return -3; } }
void DumpXMLAnnotationVisitor::examine_edge(LinguisticGraphEdge e, const LinguisticGraph& g) { COREFSOLVERLOGINIT; LDEBUG << "DumpXMLAnnotationVisitor::examine_edge"; LinguisticGraphVertex v = target(e, g); // let process sentences like (...) have automatically tuned (...) where the graph has one token "have_tuned" with one branch "automatically" "tuned" and another one with the following of the sentence LinguisticGraphOutEdgeIt it, it_end; boost::tie(it, it_end) = boost::out_edges(v,g); if (it == it_end) return; // let process sentences where one tag has not been fully determined and there is still two (or more) tag options LinguisticGraphVertex v2 = target(m_lastEdge, g); if (v2==v) return; if (m_lastEdge!=LinguisticGraphEdge() && are_equivalent(e, v2, v, g)) return; // begin // store this edge for the future tests if (get(vertex_token, g,v)!=0) m_lastEdge = e; // const FsaStringsPool& stringsPool= Common::MediaticData::MediaticData::single().stringsPool(m_language); Token* token = get(vertex_token, g, v); // processing of cases like "s'y introduire", tokenized as "y s'introduire" if (token != 0 && (token->stringForm() == "en" || token->stringForm() =="y")) { LinguisticGraphOutEdgeIt it, it_end; boost::tie(it, it_end) = boost::out_edges(v,g); if (it != it_end) { Token* t = get(vertex_token, g,target(*it, g)); if (t!=0 && Common::Misc::limastring2utf8stdstring(t->stringForm()).substr(0,2)=="s'") { m_ostream << "s'"; } } } // process std::set< AnnotationGraphVertex > matches = m_ad->matches("PosGraph",v,"annot"); if (matches.empty()) { COREFSOLVERLOGINIT; LERROR << "DumpXMLAnnotationVisitor::examine_edge No annotation graph vertex matches PoS graph vertex " << v << ". This should not happen."; return; } AnnotationGraphVertex av = *matches.begin(); if (m_ad->hasAnnotation(av, Common::Misc::utf8stdstring2limastring("Coreferent"))) { GenericAnnotation ga = (m_ad->annotation(av,utf8stdstring2limastring("Coreferent"))); Lima::LinguisticProcessing::Coreferences::CoreferentAnnotation ca; try { ca = ga.value<Lima::LinguisticProcessing::Coreferences::CoreferentAnnotation>(); ca.outputXml(m_ostream,g,m_ad); } catch (const boost::bad_any_cast& ) { COREFSOLVERLOGINIT; LERROR << "non coreferent annotation"<< LENDL; } } else { Token* token = get(vertex_token, g, v); if (token != 0) { std::string s = Common::Misc::limastring2utf8stdstring(token->stringForm()); // processing of cases like "s'y introduire", tokenized as "y s'introduire" if (s.substr(0,2) == "s'") { Token* t = get(vertex_token,g,source(e, g)); if (t!=0 && (Common::Misc::limastring2utf8stdstring(t->stringForm()).substr(0,2)=="en" || Common::Misc::limastring2utf8stdstring(t->stringForm()).substr(0,2)=="y")) { s = s.substr(2,s.size()); } } // processing of cases like "le Canada a-t-il envisagé...", où le mot entre "a" et "envisagé" se retrouverait rejeté après "a_envisagé". Nécessaire de traiter car problématique pour l'évaluation quand il s'agit d'un pronom clitique comme dans ce cas-ci. std::string formerMemo = m_memo; match_results<std::string::const_iterator> what; string::const_iterator start = s.begin(); string::const_iterator end = s.end(); if (regex_search(s, what, regex("_"))) { m_memo = std::string(what[0].second,end) + " "; s = std::string(start,what[0].first); } else m_memo = ""; m_ostream << formerMemo << s; if (token->status().isAlphaPossessive()) { m_ostream << "'s "; } } } m_ostream << " "; }
unsigned int searchProject(Output* output_, const char* file, const char* string, unsigned int options, unsigned int limit, const char* include, const char* exclude) { SearchOutput output(output_, options, limit); std::unique_ptr<Regex> regex(createRegex(string, getRegexOptions(options))); std::unique_ptr<Regex> includeRe(include ? createRegex(include, RO_IGNORECASE) : 0); std::unique_ptr<Regex> excludeRe(exclude ? createRegex(exclude, RO_IGNORECASE) : 0); NgramRegex ngregex((options & SO_BRUTEFORCE) ? nullptr : regex.get()); std::string dataPath = replaceExtension(file, ".qgd"); FileStream in(dataPath.c_str(), "rb"); if (!in) { output_->error("Error reading data file %s\n", dataPath.c_str()); return 0; } DataFileHeader header; if (!read(in, header) || memcmp(header.magic, kDataFileHeaderMagic, strlen(kDataFileHeaderMagic)) != 0) { output_->error("Error reading data file %s: malformed header\n", dataPath.c_str()); return 0; } { unsigned int chunkIndex = 0; // Assume 50% compression ratio (it's usually much better) BlockPool chunkPool(kChunkSize * 3 / 2); std::vector<unsigned char> index; DataChunkHeader chunk; WorkQueue queue(WorkQueue::getIdealWorkerCount(), kMaxQueuedChunkData); while (!output.isLimitReached() && read(in, chunk)) { if (ngregex.empty() || chunk.indexSize == 0) { in.skip(chunk.indexSize); } else { try { index.resize(chunk.indexSize); } catch (const std::bad_alloc&) { output_->error("Error reading data file %s: malformed chunk\n", dataPath.c_str()); return 0; } if (chunk.indexSize && !read(in, &index[0], chunk.indexSize)) { output_->error("Error reading data file %s: malformed chunk\n", dataPath.c_str()); return 0; } if (!ngregex.match(index, chunk.indexHashIterations)) { in.skip(chunk.compressedSize); continue; } } std::shared_ptr<char> data = chunkPool.allocate(chunk.compressedSize + chunk.uncompressedSize, std::nothrow); if (!data || !read(in, data.get(), chunk.compressedSize)) { output_->error("Error reading data file %s: malformed chunk\n", dataPath.c_str()); return 0; } queue.push([=, ®ex, &output, &includeRe, &excludeRe]() { char* compressed = data.get(); char* uncompressed = data.get() + chunk.compressedSize; decompress(uncompressed, chunk.uncompressedSize, compressed, chunk.compressedSize); processChunk(regex.get(), &output, chunkIndex, uncompressed, chunk.fileCount, includeRe.get(), excludeRe.get()); }, chunk.compressedSize + chunk.uncompressedSize); chunkIndex++; } } return output.output.getLineCount(); }
bool ExcludeMessageFilter::FilterLog(const rosgraph_msgs::Log &log) { return boost::regex_match(log.msg, regex()); }
// Use LocalXyzPointer types that are not covered elsewhere in the intltest suite. void LocalPointerTest::TestLocalXyzPointer() { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointer"); static const char *const encoding="ISO-8859-1"; LocalUConverterSelectorPointer sel( ucnvsel_open(&encoding, 1, NULL, UCNV_ROUNDTRIP_SET, errorCode)); if(errorCode.logIfFailureAndReset("ucnvsel_open()")) { return; } if(sel.isNull()) { errln("LocalUConverterSelectorPointer failure"); return; } #if !UCONFIG_NO_FORMATTING LocalUCalendarPointer cal(ucal_open(NULL, 0, "root", UCAL_GREGORIAN, errorCode)); if(errorCode.logDataIfFailureAndReset("ucal_open()")) { return; } if(cal.isNull()) { errln("LocalUCalendarPointer failure"); return; } LocalUDateTimePatternGeneratorPointer patgen(udatpg_open("root", errorCode)); if(errorCode.logDataIfFailureAndReset("udatpg_open()")) { return; } if(patgen.isNull()) { errln("LocalUDateTimePatternGeneratorPointer failure"); return; } LocalULocaleDisplayNamesPointer ldn(uldn_open("de-CH", ULDN_STANDARD_NAMES, errorCode)); if(errorCode.logIfFailureAndReset("uldn_open()")) { return; } if(ldn.isNull()) { errln("LocalULocaleDisplayNamesPointer failure"); return; } UnicodeString hello=UNICODE_STRING_SIMPLE("Hello {0}!"); LocalUMessageFormatPointer msg( umsg_open(hello.getBuffer(), hello.length(), "root", NULL, errorCode)); if(errorCode.logIfFailureAndReset("umsg_open()")) { return; } if(msg.isNull()) { errln("LocalUMessageFormatPointer failure"); return; } #endif /* UCONFIG_NO_FORMATTING */ #if !UCONFIG_NO_NORMALIZATION const UNormalizer2 *nfc=unorm2_getInstance(NULL, "nfc", UNORM2_COMPOSE, errorCode); UnicodeSet emptySet; LocalUNormalizer2Pointer fn2(unorm2_openFiltered(nfc, emptySet.toUSet(), errorCode)); if(errorCode.logIfFailureAndReset("unorm2_openFiltered()")) { return; } if(fn2.isNull()) { errln("LocalUNormalizer2Pointer failure"); return; } #endif /* !UCONFIG_NO_NORMALIZATION */ #if !UCONFIG_NO_IDNA LocalUIDNAPointer idna(uidna_openUTS46(0, errorCode)); if(errorCode.logIfFailureAndReset("uidna_openUTS46()")) { return; } if(idna.isNull()) { errln("LocalUIDNAPointer failure"); return; } #endif /* !UCONFIG_NO_IDNA */ #if !UCONFIG_NO_REGULAR_EXPRESSIONS UnicodeString pattern=UNICODE_STRING_SIMPLE("abc|xy+z"); LocalURegularExpressionPointer regex( uregex_open(pattern.getBuffer(), pattern.length(), 0, NULL, errorCode)); if(errorCode.logIfFailureAndReset("uregex_open()")) { return; } if(regex.isNull()) { errln("LocalURegularExpressionPointer failure"); return; } #endif /* UCONFIG_NO_REGULAR_EXPRESSIONS */ #if !UCONFIG_NO_TRANSLITERATION UnicodeString id=UNICODE_STRING_SIMPLE("Grek-Latn"); LocalUTransliteratorPointer trans( utrans_openU(id.getBuffer(), id.length(), UTRANS_FORWARD, NULL, 0, NULL, errorCode)); if(errorCode.logIfFailureAndReset("utrans_open()")) { return; } if(trans.isNull()) { errln("LocalUTransliteratorPointer failure"); return; } #endif /* !UCONFIG_NO_TRANSLITERATION */ // destructors }
void SearchReplaceEngine::ReplaceNext(bool DoReplace) { if (!CanContinue) { OpenDialog(DoReplace); return; } wxArrayInt sels = context->subsGrid->GetSelection(); int firstLine = 0; if (sels.Count() > 0) firstLine = sels[0]; // if selection has changed reset values if (firstLine != curLine) { curLine = firstLine; Modified = false; LastWasFind = true; pos = 0; matchLen = 0; replaceLen = 0; } // Setup int start = curLine; int nrows = context->subsGrid->GetRows(); bool found = false; size_t tempPos; int regFlags = wxRE_ADVANCED; if (!matchCase) { if (isReg) regFlags |= wxRE_ICASE; else LookFor.MakeLower(); } // Search for it boost::flyweight<wxString> *Text = nullptr; while (!found) { Text = get_text(context->subsGrid->GetDialogue(curLine), field); if (DoReplace && LastWasFind) tempPos = pos; else tempPos = pos+replaceLen; // RegExp if (isReg) { wxRegEx regex (LookFor,regFlags); if (regex.IsValid()) { if (regex.Matches(Text->get().Mid(tempPos))) { size_t match_start; regex.GetMatch(&match_start,&matchLen,0); pos = match_start + tempPos; found = true; } } } // Normal else { wxString src = Text->get().Mid(tempPos); if (!matchCase) src.MakeLower(); int textPos = src.Find(LookFor); if (textPos != -1) { pos = tempPos+textPos; found = true; matchLen = LookFor.Length(); } } // Didn't find, go to next line if (!found) { curLine++; pos = 0; matchLen = 0; replaceLen = 0; if (curLine == nrows) curLine = 0; if (curLine == start) break; } } // Found if (found) { // If replacing if (DoReplace) { // Replace with regular expressions if (isReg) { wxString toReplace = Text->get().Mid(pos,matchLen); wxRegEx regex(LookFor,regFlags); regex.ReplaceFirst(&toReplace,ReplaceWith); *Text = Text->get().Left(pos) + toReplace + Text->get().Mid(pos+matchLen); replaceLen = toReplace.Length(); } // Normal replace else { *Text = Text->get().Left(pos) + ReplaceWith + Text->get().Mid(pos+matchLen); replaceLen = ReplaceWith.Length(); } // Commit context->ass->Commit(_("replace"), AssFile::COMMIT_DIAG_TEXT); } else { replaceLen = matchLen; } // Select context->subsGrid->SelectRow(curLine,false); context->subsGrid->MakeCellVisible(curLine,0); if (field == 0) { context->selectionController->SetActiveLine(context->subsGrid->GetDialogue(curLine)); context->textSelectionController->SetSelection(pos, pos + replaceLen); } // Update video if (updateVideo) { cmd::call("video/jump/start", context); } else if (DoReplace) Modified = true; // hAx to prevent double match on style/actor if (field != 0) replaceLen = 99999; } LastWasFind = !DoReplace; }
// Try LocalXyzPointer types with NULL pointers. void LocalPointerTest::TestLocalXyzPointerNull() { { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUConverterSelectorPointer"); static const char *const encoding="ISO-8859-1"; LocalUConverterSelectorPointer null; LocalUConverterSelectorPointer sel( ucnvsel_open(&encoding, 1, NULL, UCNV_ROUNDTRIP_SET, errorCode)); sel.adoptInstead(NULL); } #if !UCONFIG_NO_FORMATTING { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUCalendarPointer"); LocalUCalendarPointer null; LocalUCalendarPointer cal(ucal_open(NULL, 0, "root", UCAL_GREGORIAN, errorCode)); if(!errorCode.logDataIfFailureAndReset("ucal_open()")) { cal.adoptInstead(NULL); } } { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUDateTimePatternGeneratorPointer"); LocalUDateTimePatternGeneratorPointer null; LocalUDateTimePatternGeneratorPointer patgen(udatpg_open("root", errorCode)); patgen.adoptInstead(NULL); } { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUMessageFormatPointer"); UnicodeString hello=UNICODE_STRING_SIMPLE("Hello {0}!"); LocalUMessageFormatPointer null; LocalUMessageFormatPointer msg( umsg_open(hello.getBuffer(), hello.length(), "root", NULL, errorCode)); msg.adoptInstead(NULL); } #endif /* !UCONFIG_NO_FORMATTING */ #if !UCONFIG_NO_REGULAR_EXPRESSIONS { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalURegularExpressionPointer"); UnicodeString pattern=UNICODE_STRING_SIMPLE("abc|xy+z"); LocalURegularExpressionPointer null; LocalURegularExpressionPointer regex( uregex_open(pattern.getBuffer(), pattern.length(), 0, NULL, errorCode)); if(!errorCode.logDataIfFailureAndReset("urege_open()")) { regex.adoptInstead(NULL); } } #endif /* !UCONFIG_NO_REGULAR_EXPRESSIONS */ #if !UCONFIG_NO_TRANSLITERATION { IcuTestErrorCode errorCode(*this, "TestLocalXyzPointerNull/LocalUTransliteratorPointer"); UnicodeString id=UNICODE_STRING_SIMPLE("Grek-Latn"); LocalUTransliteratorPointer null; LocalUTransliteratorPointer trans( utrans_openU(id.getBuffer(), id.length(), UTRANS_FORWARD, NULL, 0, NULL, errorCode)); if(!errorCode.logDataIfFailureAndReset("utrans_openU()")) { trans.adoptInstead(NULL); } } #endif /* !UCONFIG_NO_TRANSLITERATION */ }
FacilityShadingGridView::FacilityShadingGridView(bool isIP, const model::Model & model, QWidget * parent) : GridViewSubTab(isIP, model, parent) { auto modelObjects = subsetCastVector<model::ModelObject>(model.getModelObjects<model::ShadingSurfaceGroup>()); std::sort(modelObjects.begin(), modelObjects.end(), ModelObjectNameSorter()); m_gridController = new FacilityShadingGridController(isIP, "Shading Surface Group", IddObjectType::OS_ShadingSurfaceGroup, model, modelObjects); m_gridView = new OSGridView(m_gridController, "Shading Surface Group", "Drop\nShading Surface Group", false, parent); setGridController(m_gridController); setGridView(m_gridView); // Filters QLabel * label = nullptr; QVBoxLayout * layout = nullptr; auto filterGridLayout = new QGridLayout(); filterGridLayout->setContentsMargins(7, 4, 0, 8); filterGridLayout->setSpacing(5); label = new QLabel(); label->setText("Filters:"); label->setObjectName("H2"); filterGridLayout->addWidget(label, filterGridLayout->rowCount(), filterGridLayout->columnCount(), Qt::AlignTop | Qt::AlignLeft); // SHADINGSURFACEGROUPNAME layout = new QVBoxLayout(); label = new QLabel(); label->setText(SHADINGSURFACENAME); label->setObjectName("H3"); layout->addWidget(label, Qt::AlignTop | Qt::AlignLeft); m_nameFilter = new QLineEdit(); m_nameFilter->setFixedWidth(OSItem::ITEM_WIDTH); // Evan note: there are issues with using the signal textChanged or textEdited, related to the design and updating of the gridview (loss of focus, and updates per key stroke) connect(m_nameFilter, &QLineEdit::editingFinished, this, &openstudio::FacilityShadingGridView::nameFilterChanged); QRegExp nameRegex("^\\S.*"); auto nameValidator = new QRegExpValidator(nameRegex, this); m_nameFilter->setValidator(nameValidator); layout->addWidget(m_nameFilter, Qt::AlignTop | Qt::AlignLeft); layout->addStretch(); filterGridLayout->addLayout(layout, filterGridLayout->rowCount() - 1, filterGridLayout->columnCount()); // SHADINGSURFACETYPE layout = new QVBoxLayout(); label = new QLabel(); label->setText(SHADINGSURFACETYPE); label->setObjectName("H3"); layout->addWidget(label, Qt::AlignTop | Qt::AlignLeft); m_typeFilter = new QComboBox(); m_typeFilter->addItem("Site"); m_typeFilter->addItem("Building"); m_typeFilter->addItem("Space"); m_typeFilter->setFixedWidth(OSItem::ITEM_WIDTH); connect(m_typeFilter, &QComboBox::currentTextChanged, this, &openstudio::FacilityShadingGridView::typeFilterChanged); layout->addWidget(m_typeFilter, Qt::AlignTop | Qt::AlignLeft); layout->addStretch(); filterGridLayout->addLayout(layout, filterGridLayout->rowCount() - 1, filterGridLayout->columnCount()); // TILTGREATERTHAN layout = new QVBoxLayout(); label = new QLabel(); label->setText(TILTGREATERTHAN); label->setObjectName("H3"); layout->addWidget(label, Qt::AlignTop | Qt::AlignLeft); m_tiltGreaterThanFilter = new QLineEdit(); m_tiltGreaterThanFilter->setFixedWidth(OSItem::ITEM_WIDTH); connect(m_tiltGreaterThanFilter, &QLineEdit::editingFinished, this, &openstudio::FacilityShadingGridView::tiltFilterChanged); QRegExp regex("^(-?\\d*\\.?\\d+)?$"); auto validator = new QRegExpValidator(regex, this); m_tiltGreaterThanFilter->setValidator(validator); layout->addWidget(m_tiltGreaterThanFilter, Qt::AlignTop | Qt::AlignLeft); layout->addStretch(); filterGridLayout->addLayout(layout, filterGridLayout->rowCount() - 1, filterGridLayout->columnCount()); //TILTLESSTHAN layout = new QVBoxLayout(); label = new QLabel(); label->setText(TILTLESSTHAN); label->setObjectName("H3"); layout->addWidget(label, Qt::AlignTop | Qt::AlignLeft); m_tiltLessThanFilter = new QLineEdit(); m_tiltLessThanFilter->setFixedWidth(OSItem::ITEM_WIDTH); // Evan note: there are issues with using the signal textChanged or textEdited, related to the design and updating of the gridview (loss of focus, and updates per key stroke) connect(m_tiltLessThanFilter, &QLineEdit::editingFinished, this, &openstudio::FacilityShadingGridView::tiltFilterChanged); validator = new QRegExpValidator(regex, this); m_tiltLessThanFilter->setValidator(validator); layout->addWidget(m_tiltLessThanFilter, Qt::AlignTop | Qt::AlignLeft); layout->addStretch(); filterGridLayout->addLayout(layout, filterGridLayout->rowCount() - 1, filterGridLayout->columnCount()); // ORIENTATIONGREATERTHAN layout = new QVBoxLayout(); label = new QLabel(); label->setText(ORIENTATIONGREATERTHAN); label->setObjectName("H3"); layout->addWidget(label, Qt::AlignTop | Qt::AlignLeft); m_orientationGreaterThanFilter = new QLineEdit(); m_orientationGreaterThanFilter->setFixedWidth(OSItem::ITEM_WIDTH); connect(m_orientationGreaterThanFilter, &QLineEdit::editingFinished, this, &openstudio::FacilityShadingGridView::orientationFilterChanged); validator = new QRegExpValidator(regex, this); m_orientationGreaterThanFilter->setValidator(validator); layout->addWidget(m_orientationGreaterThanFilter, Qt::AlignTop | Qt::AlignLeft); layout->addStretch(); filterGridLayout->addLayout(layout, filterGridLayout->rowCount() - 1, filterGridLayout->columnCount()); // ORIENTATIONLESSTHAN layout = new QVBoxLayout(); label = new QLabel(); label->setText(ORIENTATIONLESSTHAN); label->setObjectName("H3"); layout->addWidget(label, Qt::AlignTop | Qt::AlignLeft); m_orientationLessThanFilter = new QLineEdit(); m_orientationLessThanFilter->setFixedWidth(OSItem::ITEM_WIDTH); // Evan note: there are issues with using the signal textChanged or textEdited, related to the design and updating of the gridview (loss of focus, and updates per key stroke) connect(m_orientationLessThanFilter, &QLineEdit::editingFinished, this, &openstudio::FacilityShadingGridView::orientationFilterChanged); validator = new QRegExpValidator(regex, this); m_orientationLessThanFilter->setValidator(validator); layout->addWidget(m_orientationLessThanFilter, Qt::AlignTop | Qt::AlignLeft); layout->addStretch(); filterGridLayout->addLayout(layout, filterGridLayout->rowCount() - 1, filterGridLayout->columnCount()); filterGridLayout->setRowStretch(filterGridLayout->rowCount(), 100); filterGridLayout->setColumnStretch(filterGridLayout->columnCount(), 100); m_gridView->m_contentLayout->addLayout(filterGridLayout); m_gridView->m_contentLayout->addSpacing(7); }
Query Parser::parse(std::string query_str) { regex regex("(SELECT .*)(FROM .*)(WHERE .*)", regex_constants::icase); smatch match; regex_match(query_str, match, regex); if(match.size() != 4) { throw std::invalid_argument("Query does match SELECT .* FROM .* WHERE .* syntax"); } string select_str = match[1]; string from_str = match[2]; string where_str = match[3]; Query query; // evaluate SELECT if(std::regex_match(select_str, std::regex("SELECT\\s*\\*\\s*", regex::ECMAScript))) { // leave query.selections empty to indicate that all should be // selected } else { // remove SELECT and any whitespaces from the input boost::algorithm::erase_all(select_str, "SELECT"); boost::algorithm::erase_all(select_str, " "); // split the remainder by "," and check with regex // if it confirms to our input format std::regex attribute_regex("(?:([\'\"a-zA-Z0-9-_]+)\\.){0,1}([\'\"a-zA-Z0-9-_]+)", regex::ECMAScript); vector<string> tokens; boost::algorithm::split(tokens, select_str, boost::is_any_of(",")); for(uint64_t i=0; i<tokens.size(); i++) { std::smatch match; std::regex_search(tokens[i], match, attribute_regex); if(match.size() != 3) { throw std::invalid_argument("Attribute in SELECT is not of the form binding.attribute"); } // if the group before the dot was matched, we have a binding // like "binding.attribute" if(match[1].length() > 0) { Selection selection(match[1], match[2]); query.selections.push_back(selection); } else { string attribute = match[2]; // check if we have a constant string like 'foo' or "bar" if(std::regex_match(attribute, std::regex("(\".*\")|(\'.*\')"))) { boost::algorithm::erase_all(attribute, "\""); boost::algorithm::erase_all(attribute, "\'"); Constant constant(attribute); Selection selection(constant); query.selections.push_back(selection); } else { Selection selection(string(""), attribute); query.selections.push_back(selection); } /* TODO Check for numeric constants here*/ } } } // parse FROM boost::algorithm::erase_all(from_str, "FROM"); vector<string> tokens; boost::algorithm::split(tokens, from_str, boost::is_any_of(",")); for(uint64_t i=0; i<tokens.size(); i++) { smatch match; if(regex_search((string)tokens[i], match, std::regex("\\s*([a-zA-Z-_]+)\\s+([a-zA-Z-_]+)\\s*"))) { Relation relation(match[1], match[2]); query.relations.push_back(relation); } else { throw std::invalid_argument("relation in FROM clause does not match format"); } } // parse WHERE boost::erase_all(where_str, "WHERE"); boost::replace_all(where_str, " and ", ","); boost::replace_all(where_str, " AND ", ","); boost::erase_all(where_str, " "); std::regex join_condition_attribute_regex("([a-zA-Z0-9-_]+)\\.([a-zA-Z0-9-_]+)=(?:([a-zA-Z0-9-_]+)\\.([a-zA-Z0-9-_]+))", regex::ECMAScript); std::regex join_condition_constant_regex("([a-zA-Z0-9-_]+)\\.([a-zA-Z0-9-_]+)=([\'\"a-zA-Z0-9-_]+)", regex::ECMAScript); boost::algorithm::split(tokens, where_str, boost::is_any_of(",")); for(uint64_t i=0; i<tokens.size(); i++) { std::smatch match; std::regex_search(tokens[i], match, join_condition_attribute_regex); if(match.size() > 0) { Attribute left(match[1], match[2]); Attribute right(match[3], match[4]); JoinCondition join_condition(left, right); query.join_conditions.push_back(join_condition); } else { // TODO we cannot parse numeric constants std::regex_search(tokens[i], match, join_condition_constant_regex); string constant_str = match[3]; boost::algorithm::erase_all(constant_str, "\""); boost::algorithm::erase_all(constant_str, "\'"); Attribute left(match[1], match[2]); Constant right(constant_str); JoinCondition join_condition(left, right); query.join_conditions.push_back(join_condition); } } return query; }
Graph *EDIF_Parser::get_graph() { cmatch re_result; int parser_state = 0; int ff_initvalue = 0; char line[2048]; //vector <Node*> node_vector; //vector <string> wire_vector; string instance = ""; string library = ""; string celltype = ""; string net = ""; regex re_main = regex("\\s*\\(\\s*library (.*)_lib(.*)", regex_constants::perl); regex re_port = regex("\\s*\\(\\s*port\\s+(.*)", regex_constants::perl); regex re_is_input = regex("\\s*\\(\\s*direction\\s+INPUT\\s*\\).*", regex_constants::perl); regex re_array = regex("\\s*\\(\\s*array\\s*\\(\\s*rename\\s+(.+)\\s+([^\\)]+)\\)\\s*(\\d+)\\s*\\).*", regex_constants::perl); //(array (rename memco_ramsn "memco_ramsn<4:0>") 5)' regex re_instance = regex("\\s*\\(\\s*instance\\s+(.*)", regex_constants::perl); regex re_net = regex("\\s*\\(\\s*net\\s+(.*)", regex_constants::perl); regex re_rename = regex("\\(\\s*rename\\s+([^\\s]+)\\s+.*\\)", regex_constants::perl); // regex re_viewref = regex("\\s*\\(\\s*viewRef\\s+[^\\s]+\\s+\\(\\s*cellRef\\s+([^\\s]+)\\s+\\(\\s*libraryRef\\s+([^\\s\\)]+)\\s*\\).*", regex_constants::perl); regex re_property = regex("\\s*\\(\\s*property\\s+([^\\s]+)\\s+\\(\\s*([^\\s]+)\\s+\"?([^\"\\s]+)\"?\\s*\\).*", regex_constants::perl); regex re_joined = regex("\\s*\\(\\s*joined.*",regex_constants::perl); //regex re_portref = regex("\\s*\\(\\s*portRef\\s+([^\\)]+)\\s*\\).*", regex_constants::perl); //regex re_portref_member = regex("\\s*\\(\\s*portRef\\s+\\(\\s*member\\s+(.+)\\s+(.+)\\s*\\)\\s+([^\\)]+)\\s*\\).*", regex_constants::perl); //regex re_portref = regex("\\s*\\(\\s*portRef\\s+(.+)\\s+\\(([^\\)]+)\\s*\\).*", regex_constants::perl); regex re_portref = regex("\\s*\\(\\s*portRef\\s+(.+)\\s*\\).*", regex_constants::perl); regex re_instanceref = regex("\\s*([^\\(]+)\\s+\\(\\s*instanceRef\\s+([^\\s\\)]+)\\s*.*", regex_constants::perl); regex re_member_instanceref = regex("\\s*\\(member\\s+(.+)\\s+(.+)\\s*\\)\\s+\\(\\s*instanceRef\\s+([^\\s\\)]+)\\s*.*", regex_constants::perl); regex re_member_io = regex("\\s*\\(member\\s+(.+)\\s+(.+)\\s*\\)\\s*.*", regex_constants::perl); regex re_member = regex("\\s*\\(member\\s+(.+)\\s+(.+)\\s*\\).*", regex_constants::perl); //regex re_instanceref = regex("\\s*([^\\(]+)\\s+\\(\\s*instanceRef\\s+([^\\s\\)]+)\\s*", regex_constants::perl); regex re_eof_obj = regex("^\\s*\\)\\s*$", regex_constants::perl); Graph *graph = new Graph(); //add XST default nodes for GND and VCC: Node *gnd = new Node_UNISIM_GND("XST_GND"); graph->add_node(gnd); Node *vcc = new Node_UNISIM_VCC("XST_VCC"); graph->add_node(vcc); int count = 0; //get filesize input_stream.seekg(0, ios_base::end); int maxlen = input_stream.tellg(); input_stream.seekg(0, ios_base::beg); while( input_stream.good()){ if (count++ == 200){ printf(" \r> parsing edif %3d%% done : ",input_stream.tellg()*100/maxlen); cout.flush(); count=0; } input_stream.getline(line, 2048); //printf("%d -%s-\n",parser_state,line); //parse the edif switch(parser_state){ ///initial state case(0): if (regex_match(line, re_result, re_main)){ parser_state = 1; } break; case(1): if (regex_match(line, re_result, re_port)){ //port definition, check next line if its input: string port_name = re_result[1].str(); input_stream.getline(line, 2048); //input, create input node //printf("'%s'\n\n",port_name.c_str()); Node *newnode; if (regex_match(port_name.c_str(), re_result, re_array)){ //multiple ios int max = atoi(re_result[3].str().c_str()); port_name = re_result[1].str(); for(int i=0; i<max; i++){ char buf[255]; sprintf(buf, "%s__%d", port_name.c_str(), i); if (regex_match(line, re_result, re_is_input)){ newnode = new Node_INPUT(buf); }else{ newnode = new Node_OUTPUT(buf); } graph->add_node(newnode); //printf("A '%s'\n",buf); } }else{ if (regex_match(line, re_result, re_is_input)){ newnode = new Node_INPUT(port_name.c_str()); }else{ newnode = new Node_OUTPUT(port_name.c_str()); } graph->add_node(newnode); //printf("S '%s'\n",port_name.c_str()); } }else if(regex_match(line, re_result, re_instance)){ //this is an instance definition instance = re_result[1].str(); if (regex_match(instance.c_str(), re_result, re_rename)){ //this is a rename, keep the new name instance = re_result[1].str(); } //ok, we have an instance, change parser state parser_state = 2; ff_initvalue = 0; //printf(" instance [%s] ", instance.c_str()); }else if(regex_match(line, re_result, re_net)){ //this is an net definition net = re_result[1].str(); if (regex_match(net.c_str(), re_result, re_rename)){ //this is a rename, keep the new name net = re_result[1].str(); } //ok we have a net, change parser state parser_state = 3; //printf("NET %s\n",net.c_str()); }else{ //TODO: add other info parser here //printf("FIX PARSER [%s]\n",line); } break; ///parse instance details /** instance example: ** (instance (rename dout_renamed_0 "dout") (viewRef view_1 (cellRef FD (libraryRef UNISIMS))) (property XSTLIB (boolean (true)) (owner "Xilinx")) ) */ case(2): if (regex_match(line, re_result, re_viewref)){ //viewRef celltype = re_result[1].str(); library = re_result[2].str(); //printf(" celltype [%s] using lib <%s>\n", celltype.c_str(), library.c_str()); }else if (regex_match(line, re_result, re_property)){ //property string property = re_result[1].str(); string value_type = re_result[2].str(); string value_value = re_result[3].str(); if (property == "INIT"){ //get type of init: if (value_type == "boolean"){ sscanf(value_value.c_str(), "%d", &ff_initvalue); }else if (value_type == "string"){ sscanf(value_value.c_str(), "%x", &ff_initvalue); }else{ debug_printf("> dont know how to handle value type <%s>\n",value_type.c_str()); } }else if (property == "XSTLIB"){ //no info for us... }else if (property == "BUS_INFO"){ //no info for us... }else{ debug_printf("> ignoring property <%s>\n",property.c_str()); } }else if(regex_match(line, re_result, re_eof_obj)){ //instance block finished -> create object Node *newnode = graph->create_node(library.c_str(), instance.c_str(), celltype.c_str(), ff_initvalue); graph->add_node(newnode); //go back to initial state parser_state = 1; }else{ debug_printf("\n%d UKN -%s-\n",parser_state,line); } break; ///parse net definition /** net example ** (net (rename triplet_3_ok_ff_2__ "triplet_3_ok/ff<2>") (joined (portRef Q (instanceRef triplet_3_ok_ff_2)) (portRef I1 (instanceRef triplet_3_ok_dout1)) ) ) */ case(3): if (regex_match(line, re_result, re_portref)){ //printf("[%s]\n",line); //prepare graph to connect //string portref = "Q"; //string instanceref = re_result[1].str(); wire wire; wire.port = "Q"; wire.instance = re_result[1].str(); if (regex_match(wire.instance.c_str(), re_result, re_member_instanceref)){ //if this is not an input we will get a correct instancename now: //(member DOUT 0) instancebla // $1 $2 $3 wire.instance = re_result[3].str() + "__" + re_result[1].str() + "__" + re_result[2].str(); wire.port = get_port_by_node_name(graph, wire.instance); }else if (regex_match(wire.instance.c_str(), re_result, re_instanceref)){ //if this is not an input we will get a correct instancename now: wire.port = re_result[1].str(); wire.instance = re_result[2].str(); }else if (regex_match(wire.instance.c_str(), re_result, re_member_io)){ wire.instance = re_result[1].str() + "__" + re_result[2].str(); wire.port = get_port_by_node_name(graph, wire.instance); }else{ wire.port = get_port_by_node_name(graph, wire.instance); } /* no, need to check if this is in or output in order to set Q/D }else if (regex_match(wire.instance.c_str(), re_result, re_member)){ //if this is not an input we will get a correct instancename now: //(member aaaa 0) // $1 $2 wire.port = "Q"; wire.instance = re_result[1].str() + "__" + re_result[2].str(); }*/ graph->prepare_connection(wire); }else if(regex_match(line, re_result, re_eof_obj)){ //eof this net, do all the connections graph->execute_connections(); parser_state =1; }else if(regex_match(line, re_result, re_joined)){ //ignore this line }else{ printf("invalid net info: %s\n",line); exit(-1); } break; default: parser_state = 1; } } printf(" \r> parsing edif %3d%% done : ",input_stream.tellg()*100/maxlen); printf("\n> parsing done.\n"); input_stream.close(); return graph; }
bool TextBox::checkFormat(const std::string &input, const std::string &format) { if (format.empty()) return true; std::regex regex(format); return regex_match(input, regex); }
const QIcon ConsoleChannel::colorIcon(const QString& name) { /* Return immediately with a rainbow icon -- if appropriate */ if (name.toLower().contains("rainbow") || name.toLower().contains("cw") == true) { return QIcon(":/rainbow.png"); } else if (name.toLower().contains("cto") == true) { QColor color(255, 201, 0); QPixmap pm(32, 32); pm.fill(color); return QIcon(pm); } else if (name.toLower().contains("ctb") == true) { QColor color(0, 128, 190); QPixmap pm(32, 32); pm.fill(color); return QIcon(pm); } else if (name.toLower().contains("uv") == true) { QColor color(37, 0, 136); QPixmap pm(32, 32); pm.fill(color); return QIcon(pm); } #ifdef Q_WS_X11 QColor::setAllowX11ColorNames(true); #endif QStringList colorList(QColor::colorNames()); QString colname; QColor color; int index; colname = name.toLower().remove(QRegExp("[0-9]")).remove(' '); index = colorList.indexOf(colname); if (index != -1) { color.setNamedColor(colname); } else { QString re("("); QListIterator <QString> it(name.toLower().split(" ")); while (it.hasNext() == true) { re += it.next(); if (it.hasNext() == true) re += "|"; } re += ")"; QRegExp regex(re, Qt::CaseInsensitive); index = colorList.indexOf(regex); if (index != -1) color.setNamedColor(colorList.at(index)); } if (color.isValid() == true) { QPixmap pm(32, 32); pm.fill(color); return QIcon(pm); } else { return QIcon(); } }
void BSONElement::jsonStringStream(JsonStringFormat format, bool includeFieldNames, int pretty, std::stringstream& s) const { if (includeFieldNames) s << '"' << escape(fieldName()) << "\" : "; switch (type()) { case mongo::String: case Symbol: s << '"' << escape(string(valuestr(), valuestrsize() - 1)) << '"'; break; case NumberLong: if (format == TenGen) { s << "NumberLong(" << _numberLong() << ")"; } else { s << "{ \"$numberLong\" : \"" << _numberLong() << "\" }"; } break; case NumberInt: if (format == TenGen) { s << "NumberInt(" << _numberInt() << ")"; break; } case NumberDouble: if (number() >= -std::numeric_limits<double>::max() && number() <= std::numeric_limits<double>::max()) { auto origPrecision = s.precision(); auto guard = makeGuard([&s, origPrecision]() { s.precision(origPrecision); }); s.precision(16); s << number(); } // This is not valid JSON, but according to RFC-4627, "Numeric values that cannot be // represented as sequences of digits (such as Infinity and NaN) are not permitted." so // we are accepting the fact that if we have such values we cannot output valid JSON. else if (std::isnan(number())) { s << "NaN"; } else if (std::isinf(number())) { s << (number() > 0 ? "Infinity" : "-Infinity"); } else { StringBuilder ss; ss << "Number " << number() << " cannot be represented in JSON"; string message = ss.str(); massert(10311, message.c_str(), false); } break; case NumberDecimal: if (format == TenGen) s << "NumberDecimal(\""; else s << "{ \"$numberDecimal\" : \""; // Recognize again that this is not valid JSON according to RFC-4627. // Also, treat -NaN and +NaN as the same thing for MongoDB. if (numberDecimal().isNaN()) { s << "NaN"; } else if (numberDecimal().isInfinite()) { s << (numberDecimal().isNegative() ? "-Infinity" : "Infinity"); } else { s << numberDecimal().toString(); } if (format == TenGen) s << "\")"; else s << "\" }"; break; case mongo::Bool: s << (boolean() ? "true" : "false"); break; case jstNULL: s << "null"; break; case Undefined: if (format == Strict) { s << "{ \"$undefined\" : true }"; } else { s << "undefined"; } break; case Object: embeddedObject().jsonStringStream(format, pretty, false, s); break; case mongo::Array: { if (embeddedObject().isEmpty()) { s << "[]"; break; } s << "[ "; BSONObjIterator i(embeddedObject()); BSONElement e = i.next(); if (!e.eoo()) { int count = 0; while (1) { if (pretty) { s << '\n'; for (int x = 0; x < pretty; x++) s << " "; } if (strtol(e.fieldName(), 0, 10) > count) { s << "undefined"; } else { e.jsonStringStream(format, false, pretty ? pretty + 1 : 0, s); e = i.next(); } count++; if (e.eoo()) break; s << ", "; } } s << " ]"; break; } case DBRef: { if (format == TenGen) s << "Dbref( "; else s << "{ \"$ref\" : "; s << '"' << valuestr() << "\", "; if (format != TenGen) s << "\"$id\" : "; s << '"' << mongo::OID::from(valuestr() + valuestrsize()) << "\" "; if (format == TenGen) s << ')'; else s << '}'; break; } case jstOID: if (format == TenGen) { s << "ObjectId( "; } else { s << "{ \"$oid\" : "; } s << '"' << __oid() << '"'; if (format == TenGen) { s << " )"; } else { s << " }"; } break; case BinData: { ConstDataCursor reader(value()); const int len = reader.readAndAdvance<LittleEndian<int>>(); BinDataType type = static_cast<BinDataType>(reader.readAndAdvance<uint8_t>()); s << "{ \"$binary\" : \""; base64::encode(s, reader.view(), len); auto origFill = s.fill(); auto origFmtF = s.flags(); auto origWidth = s.width(); auto guard = makeGuard([&s, origFill, origFmtF, origWidth] { s.fill(origFill); s.setf(origFmtF); s.width(origWidth); }); s.setf(std::ios_base::hex, std::ios_base::basefield); s << "\", \"$type\" : \""; s.width(2); s.fill('0'); s << type; s << "\" }"; break; } case mongo::Date: if (format == Strict) { Date_t d = date(); s << "{ \"$date\" : "; // The two cases in which we cannot convert Date_t::millis to an ISO Date string are // when the date is too large to format (SERVER-13760), and when the date is before // the epoch (SERVER-11273). Since Date_t internally stores millis as an unsigned // long long, despite the fact that it is logically signed (SERVER-8573), this check // handles both the case where Date_t::millis is too large, and the case where // Date_t::millis is negative (before the epoch). if (d.isFormattable()) { s << "\"" << dateToISOStringLocal(date()) << "\""; } else { s << "{ \"$numberLong\" : \"" << d.toMillisSinceEpoch() << "\" }"; } s << " }"; } else { s << "Date( "; if (pretty) { Date_t d = date(); // The two cases in which we cannot convert Date_t::millis to an ISO Date string // are when the date is too large to format (SERVER-13760), and when the date is // before the epoch (SERVER-11273). Since Date_t internally stores millis as an // unsigned long long, despite the fact that it is logically signed // (SERVER-8573), this check handles both the case where Date_t::millis is too // large, and the case where Date_t::millis is negative (before the epoch). if (d.isFormattable()) { s << "\"" << dateToISOStringLocal(date()) << "\""; } else { // FIXME: This is not parseable by the shell, since it may not fit in a // float s << d.toMillisSinceEpoch(); } } else { s << date().asInt64(); } s << " )"; } break; case RegEx: if (format == Strict) { s << "{ \"$regex\" : \"" << escape(regex()); s << "\", \"$options\" : \"" << regexFlags() << "\" }"; } else { s << "/" << escape(regex(), true) << "/"; // FIXME Worry about alpha order? for (const char* f = regexFlags(); *f; ++f) { switch (*f) { case 'g': case 'i': case 'm': s << *f; default: break; } } } break; case CodeWScope: { BSONObj scope = codeWScopeObject(); if (!scope.isEmpty()) { s << "{ \"$code\" : \"" << escape(_asCode()) << "\" , " << "\"$scope\" : " << scope.jsonString() << " }"; break; } } case Code: s << "\"" << escape(_asCode()) << "\""; break; case bsonTimestamp: if (format == TenGen) { s << "Timestamp( " << durationCount<Seconds>(timestampTime().toDurationSinceEpoch()) << ", " << timestampInc() << " )"; } else { s << "{ \"$timestamp\" : { \"t\" : " << durationCount<Seconds>(timestampTime().toDurationSinceEpoch()) << ", \"i\" : " << timestampInc() << " } }"; } break; case MinKey: s << "{ \"$minKey\" : 1 }"; break; case MaxKey: s << "{ \"$maxKey\" : 1 }"; break; default: StringBuilder ss; ss << "Cannot create a properly formatted JSON string with " << "element: " << toString() << " of type: " << type(); string message = ss.str(); massert(10312, message.c_str(), false); } }
void RemoteDatabase::gotReply(QNetworkReply* reply) { // Check if request was successful if(reply->error() != QNetworkReply::NoError) { QMessageBox::warning(nullptr, qApp->applicationName(), tr("Error when connecting to %1.\n%2").arg(reply->url().toString()).arg(reply->errorString())); reply->deleteLater(); return; } // Check for redirect QString redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toString(); if(!redirectUrl.isEmpty()) { // Avoid redirect loop if(reply->url() == redirectUrl) { reply->deleteLater(); return; } fetch(redirectUrl, static_cast<RequestType>(reply->property("type").toInt()), reply->property("certfile").toString(), reply->property("userdata")); reply->deleteLater(); return; } // What type of data is this? RequestType type = static_cast<RequestType>(reply->property("type").toInt()); // Hide progress dialog before opening a file dialog to make sure the progress dialog doesn't interfer with the file dialog if(type == RequestTypeDatabase || type == RequestTypePush) m_progress->reset(); // Handle the reply data switch(type) { case RequestTypeDatabase: { // It's a database file. // Add cloned database to list of local databases QString saveFileAs = localAdd(reply->url().fileName(), reply->property("certfile").toString(), reply->url(), QUrlQuery(reply->url()).queryItemValue("commit").toStdString()); // Save the downloaded data under the generated file name QFile file(saveFileAs); file.open(QIODevice::WriteOnly); file.write(reply->readAll()); // Set last modified data of the new file to the one provided by the server // Before version 5.10, Qt didn't offer any option to set this attribute, so we're not setting it at the moment #if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0) QString last_modified = reply->rawHeader("Content-Disposition"); QRegExp regex("^.*modification-date=\"(.+)\";.*$"); regex.setMinimal(true); // Set to non-greedy matching if(regex.indexIn(last_modified) != -1) { last_modified = regex.cap(1); bool success = file.setFileTime(QDateTime::fromString(last_modified, Qt::ISODate), QFileDevice::FileModificationTime); if(!success) qWarning() << file.errorString(); } #endif file.close(); // Tell the application to open this file emit openFile(saveFileAs); } break; case RequestTypeDirectory: emit gotDirList(reply->readAll(), reply->property("userdata")); break; case RequestTypeNewVersionCheck: { QString version = reply->readLine().trimmed(); QString url = reply->readLine().trimmed(); emit gotCurrentVersion(version, url); break; } case RequestTypeLicenceList: { // Read and check results json obj = json::parse(reply->readAll(), nullptr, false); if(obj.is_discarded() || !obj.is_object()) break; // Parse data and build ordered licence map: order -> (short name, long name) std::map<int, std::pair<std::string, std::string>> licences; for(auto it=obj.cbegin();it!=obj.cend();++it) licences.insert({it.value()["order"], {it.key(), it.value()["full_name"]}}); // Convert the map into an ordered vector and send it to anyone who's interested std::vector<std::pair<std::string, std::string>> licence_list; std::transform(licences.begin(), licences.end(), std::back_inserter(licence_list), [](const std::pair<int, std::pair<std::string, std::string>>& it) { return it.second; }); emit gotLicenceList(licence_list); break; } case RequestTypeBranchList: { // Read and check results json obj = json::parse(reply->readAll(), nullptr, false); if(obj.is_discarded() || !obj.is_object()) break; json obj_branches = obj["branches"]; // Parse data and assemble branch list std::vector<std::string> branches; for(auto it=obj_branches.cbegin();it!=obj_branches.cend();++it) branches.push_back(it.key()); // Get default branch std::string default_branch = (obj.contains("default_branch") && !obj["default_branch"].empty()) ? obj["default_branch"] : "master"; // Send branch list to anyone who is interested emit gotBranchList(branches, default_branch); break; } case RequestTypePush: { // Read and check results json obj = json::parse(reply->readAll(), nullptr, false); if(obj.is_discarded() || !obj.is_object()) break; // Create or update the record in our local checkout database QString saveFileAs = localAdd(reply->url().fileName(), reply->property("certfile").toString(), QString::fromStdString(obj["url"]), obj["commit_id"]); // If the name of the source file and the name we're saving as differ, we're doing an initial push. In this case, copy the source file to // the destination path to avoid redownloading it when it's first used. if(saveFileAs != reply->property("source_file").toString()) QFile::copy(reply->property("source_file").toString(), saveFileAs); emit uploadFinished(obj["url"]); break; } } // Delete reply later, i.e. after returning from this slot function reply->deleteLater(); }
void BSONElement::toString( StringBuilder& s, bool includeFieldName, bool full, bool redactValues, int depth) const { if (depth > BSONObj::maxToStringRecursionDepth) { // check if we want the full/complete string if (full) { StringBuilder s; s << "Reached maximum recursion depth of "; s << BSONObj::maxToStringRecursionDepth; uassert(16150, s.str(), full != true); } s << "..."; return; } if (includeFieldName && type() != EOO) s << fieldName() << ": "; switch (type()) { case Object: return embeddedObject().toString(s, false, full, redactValues, depth + 1); case mongo::Array: return embeddedObject().toString(s, true, full, redactValues, depth + 1); default: break; } if (redactValues) { s << "\"###\""; return; } switch (type()) { case EOO: s << "EOO"; break; case mongo::Date: s << "new Date(" << date().toMillisSinceEpoch() << ')'; break; case RegEx: { s << "/" << regex() << '/'; const char* p = regexFlags(); if (p) s << p; } break; case NumberDouble: s.appendDoubleNice(number()); break; case NumberLong: s << _numberLong(); break; case NumberInt: s << _numberInt(); break; case NumberDecimal: s << _numberDecimal().toString(); break; case mongo::Bool: s << (boolean() ? "true" : "false"); break; case Undefined: s << "undefined"; break; case jstNULL: s << "null"; break; case MaxKey: s << "MaxKey"; break; case MinKey: s << "MinKey"; break; case CodeWScope: s << "CodeWScope( " << codeWScopeCode() << ", " << codeWScopeObject().toString() << ")"; break; case Code: if (!full && valuestrsize() > 80) { s.write(valuestr(), 70); s << "..."; } else { s.write(valuestr(), valuestrsize() - 1); } break; case Symbol: case mongo::String: s << '"'; if (!full && valuestrsize() > 160) { s.write(valuestr(), 150); s << "...\""; } else { s.write(valuestr(), valuestrsize() - 1); s << '"'; } break; case DBRef: s << "DBRef('" << valuestr() << "',"; s << mongo::OID::from(valuestr() + valuestrsize()) << ')'; break; case jstOID: s << "ObjectId('"; s << __oid() << "')"; break; case BinData: { int len; const char* data = binDataClean(len); // If the BinData is a correctly sized newUUID, display it as such. if (binDataType() == newUUID && len == 16) { // 4 Octets - 2 Octets - 2 Octets - 2 Octets - 6 Octets s << "UUID(\""; s << toHexLower(&data[0], 4); s << "-"; s << toHexLower(&data[4], 2); s << "-"; s << toHexLower(&data[6], 2); s << "-"; s << toHexLower(&data[8], 2); s << "-"; s << toHexLower(&data[10], 6); s << "\")"; break; } s << "BinData(" << binDataType() << ", "; if (!full && len > 80) { s << toHex(data, 70) << "...)"; } else { s << toHex(data, len) << ")"; } } break; case bsonTimestamp: { // Convert from Milliseconds to Seconds for consistent Timestamp printing. auto secs = duration_cast<Seconds>(timestampTime().toDurationSinceEpoch()); s << "Timestamp(" << secs.count() << ", " << timestampInc() << ")"; } break; default: s << "?type=" << type(); break; } }
IDEWidget::IDEWidget(QWidget* parent, const EntityOpenRequest& request) : QWidget(parent), linkBrush(QColor(Qt::blue)) { ui.setupUi(this); File file(request.getAttribute("file").toString().toLocal8Bit().constData()); QVariant lineVariant = request.getAttribute("line"); int selectedLine = lineVariant.isNull() ? -1 : lineVariant.toInt(); QString content; istream* stream = file.openInputStream(); char buffer[4096]; while (!stream->eof()) { stream->read(buffer, sizeof(buffer)-1); buffer[stream->gcount()] = '\0'; content.append(buffer); } delete stream; // Apply some basic syntax highlighting QString richContent("<pre>"); QStringList lines = content.split('\n'); QStringList::iterator it; QString keywords[] = { "end", "objs", "tobj", "anim", "peds", "weap", "cars", "hier", "txdp", "2dfx", "path" }; for (it = lines.begin() ; it != lines.end() ; it++) { QString line = *it; QString cline = line; int cmtIdx = line.indexOf('#'); if (cmtIdx != -1) { line.insert(cmtIdx, "<font color=\"#AAAAAA\">"); line.append("</font>"); cline = line.left(cmtIdx); } for (unsigned int i = 0 ; i < sizeof(keywords)/sizeof(keywords[0]) ; i++) { QString kw = keywords[i]; QRegExp regex(QString("^(\\s*)(%1)(\\s*)$").arg(kw)); cline.replace(regex, "\\1<font color=\"blue\"><b>\\2</b></font>\\3"); } cline.replace(",", "<font color=\"red\">,</font>"); if (cmtIdx != -1) { line.replace(0, cmtIdx, cline); } else { line = cline; } richContent.append(line).append('\n'); } richContent.append("</pre>"); ui.textEdit->setHtml(richContent); // Some kind of bug in QtDesigner incorrectly sets the visibility property of the headers to a rather // random value. ui.staticObjectTable->horizontalHeader()->setVisible(true); ui.timedObjectTable->horizontalHeader()->setVisible(true); ui.animationTable->horizontalHeader()->setVisible(true); ui.pedTable->horizontalHeader()->setVisible(true); ui.weaponTable->horizontalHeader()->setVisible(true); IDEReader ide(file); IDEStatement* stmt; while ((stmt = ide.readStatement()) != NULL) { idetype_t type = stmt->getType(); int line = ide.getLastReadLine(); if (type == IDETypeStaticObject) { IDEStaticObject* sobj = (IDEStaticObject*) stmt; int rc = ui.staticObjectTable->rowCount(); ui.staticObjectTable->setRowCount(rc+1); ui.staticObjectTable->setItem(rc, 0, createItem(QString("%1").arg(sobj->getID()))); ui.staticObjectTable->setItem(rc, 1, createItem(sobj->getModelName().get(), true)); ui.staticObjectTable->setItem(rc, 2, createItem(sobj->getTXDArchiveName().get(), true)); ui.staticObjectTable->setItem(rc, 3, createItem(QString("%1") .arg(sobj->getNumSubObjects()))); ui.staticObjectTable->setItem(rc, 5, createItem(QString("%1") .arg(sobj->getFlags()))); QStringList ddists; for (int32_t i = 0 ; i < sobj->getNumSubObjects() ; i++) { ddists << QString("%1").arg(sobj->getDrawDistances()[i]); } ui.staticObjectTable->setItem(rc, 4, createItem(ddists.join(", "))); if (line == selectedLine) { ui.staticObjectTable->setCurrentCell(rc, 0); ui.tabWidget->setCurrentWidget(ui.staticObjectWidget); } } else if (type == IDETypeTimedObject) { IDETimedObject* tobj = (IDETimedObject*) stmt; int rc = ui.timedObjectTable->rowCount(); ui.timedObjectTable->setRowCount(rc+1); ui.timedObjectTable->setItem(rc, 0, createItem(QString("%1").arg(tobj->getID()))); ui.timedObjectTable->setItem(rc, 1, createItem(tobj->getModelName().get(), true)); ui.timedObjectTable->setItem(rc, 2, createItem(tobj->getTXDArchiveName().get(), true)); ui.timedObjectTable->setItem(rc, 3, createItem(QString("%1") .arg(tobj->getNumSubObjects()))); ui.timedObjectTable->setItem(rc, 5, createItem(QString("%1") .arg(tobj->getFlags()))); ui.timedObjectTable->setItem(rc, 6, createItem(QString("%1") .arg(tobj->getTimeOn()))); ui.timedObjectTable->setItem(rc, 7, createItem(QString("%1") .arg(tobj->getTimeOff()))); QStringList ddists; for (int32_t i = 0 ; i < tobj->getNumSubObjects() ; i++) { ddists << QString("%1").arg(tobj->getDrawDistances()[i]); } ui.timedObjectTable->setItem(rc, 4, createItem(ddists.join(", "))); if (line == selectedLine) { ui.timedObjectTable->setCurrentCell(rc, 0); ui.tabWidget->setCurrentWidget(ui.timedObjectWidget); } } else if (type == IDETypeAnimation) { IDEAnimation* anim = (IDEAnimation*) stmt; int rc = ui.animationTable->rowCount(); ui.animationTable->setRowCount(rc+1); ui.animationTable->setItem(rc, 0, createItem(QString("%1").arg(anim->getID()))); ui.animationTable->setItem(rc, 1, createItem(anim->getModelName().get(), true)); ui.animationTable->setItem(rc, 2, createItem(anim->getTXDArchiveName().get(), true)); ui.animationTable->setItem(rc, 3, createItem(anim->getAnimationName().get())); ui.animationTable->setItem(rc, 4, createItem(QString("%1") .arg(anim->getDrawDist()))); ui.animationTable->setItem(rc, 5, createItem(QString("%1").arg(anim->getFlags()))); if (line == selectedLine) { ui.animationTable->setCurrentCell(rc, 0); ui.tabWidget->setCurrentWidget(ui.animationWidget); } } else if (type == IDETypePedestrian) { IDEPedestrian* ped = (IDEPedestrian*) stmt; int rc = ui.pedTable->rowCount(); ui.pedTable->setRowCount(rc+1); ui.pedTable->setItem(rc, 0, createItem(QString("%1").arg(ped->getID()))); ui.pedTable->setItem(rc, 1, createItem(ped->getModelName().get(), true)); ui.pedTable->setItem(rc, 2, createItem(ped->getTXDArchiveName().get(), true)); ui.pedTable->setItem(rc, 3, createItem(ped->getDefaultPedType().get())); ui.pedTable->setItem(rc, 4, createItem(ped->getBehavior().get())); ui.pedTable->setItem(rc, 5, createItem(ped->getAnimationGroup().get())); ui.pedTable->setItem(rc, 6, createItem(QString("%1") .arg(ped->getDrivableCarClasses(), 0, 16))); ui.pedTable->setItem(rc, 7, createItem(QString("%1").arg(ped->getFlags()))); ui.pedTable->setItem(rc, 8, createItem(ped->getSecondaryAnimationFile().get())); ui.pedTable->setItem(rc, 9, createItem(QString("%1") .arg(ped->getPreferredRadio1()))); ui.pedTable->setItem(rc, 10, createItem(QString("%1") .arg(ped->getPreferredRadio2()))); ui.pedTable->setItem(rc, 11, createItem(ped->getVoiceFile().get())); ui.pedTable->setItem(rc, 12, createItem(ped->getVoice1().get())); ui.pedTable->setItem(rc, 13, createItem(ped->getVoice2().get())); if (line == selectedLine) { ui.pedTable->setCurrentCell(rc, 0); ui.tabWidget->setCurrentWidget(ui.pedWidget); } } else if (type == IDETypeWeapon) { IDEWeapon* weap = (IDEWeapon*) stmt; int rc = ui.weaponTable->rowCount(); ui.weaponTable->setRowCount(rc+1); ui.weaponTable->setItem(rc, 0, createItem(QString("%1").arg(weap->getID()))); ui.weaponTable->setItem(rc, 1, createItem(weap->getModelName().get(), true)); ui.weaponTable->setItem(rc, 2, createItem(weap->getTXDArchiveName().get(), true)); ui.weaponTable->setItem(rc, 3, createItem(weap->getAnimationName().get())); ui.weaponTable->setItem(rc, 4, createItem(QString("%1") .arg(weap->getObjectCount()))); ui.weaponTable->setItem(rc, 6, createItem(QString("%1").arg(weap->getFlags()))); QStringList ddists; for (int32_t i = 0 ; i < weap->getObjectCount() ; i++) { ddists << QString("%1").arg(weap->getDrawDistances()[i]); } ui.weaponTable->setItem(rc, 5, createItem(ddists.join(", "))); if (line == selectedLine) { ui.weaponTable->setCurrentCell(rc, 0); ui.tabWidget->setCurrentWidget(ui.weaponWidget); } } delete stmt; } ErrorLog* log = ide.getErrorLog(); if (log->getMessageCount() > 0) { System* sys = System::getInstance(); char* elem; sys->log(LogEntry::error(tr("Parsing errors in IDE file %1:") .arg(file.getPath().getFileName().get()))); while ((elem = log->nextMessage()) != NULL) { sys->log(LogEntry::error(QString("\t%1").arg(elem))); delete[] elem; } } ui.staticObjectTable->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents); ui.timedObjectTable->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents); ui.animationTable->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents); ui.pedTable->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents); ui.weaponTable->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents); connect(ui.staticObjectTable, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(staticObjectTableCellDoubleClicked(int, int))); connect(ui.timedObjectTable, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(timedObjectTableCellDoubleClicked(int, int))); connect(ui.animationTable, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(animationTableCellDoubleClicked(int, int))); connect(ui.pedTable, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(pedTableCellDoubleClicked(int, int))); connect(ui.weaponTable, SIGNAL(cellDoubleClicked(int, int)), this, SLOT(weaponTableCellDoubleClicked(int, int))); }
bool PluginMetadata::operator == (const PluginMetadata& rhs) const { return (boost::iequals(name, rhs.Name()) || (IsRegexPlugin() && regex_match(rhs.Name(), regex(name, regex::ECMAScript | regex::icase))) || (rhs.IsRegexPlugin() && regex_match(name, regex(rhs.Name(), regex::ECMAScript | regex::icase)))); }