Example #1
0
//---------------------------------------------------------
// utr_io_filter_filename - to filter filenames with given regular expression
//---------------------------------------------------------
void utr_io_filter_filenames(std::vector<string>& Filenames, // vector of filenames
							   const char * Regex // regular expression to test against
							   // during filtering
							 )
{
  using boost::regex;
  using boost::smatch;
  using boost::regex_match;

  typedef std::vector<string>::iterator iter;
  
  assert( Regex != NULL );
  assert( Filenames.size() > 0 );

  const char * r = Regex;
  if(Regex[0]=='.' && Regex[1]=='/') {
      mf_log_warn(" 'File name regex' begins with './' - stripping that from regular expression.");
      r += 2;
  }

  regex re(r);
  smatch what;

  // Find entries that DON'T MATCH and remove them.
  iter it(Filenames.begin());
  while( it != Filenames.end() ) {
	if( regex_match(*it,what,re) == false ) {
	  it = Filenames.erase(it);
	} else {
	  ++it;
	}
  }//!for 
}
Example #2
0
bool Ave::isRadianceName(const string &variableName) {
    using boost::regex;
    using boost::regex_match;

    static const regex regularExpression("(solar_irradiance|L)_[0-9][0-9]?(_er)?");
    return regex_match(variableName, regularExpression);
}
Example #3
0
Language Language::TryParse(const std::wstring& s)
{
    if (IsValidCode(s))
        return Language(s);

    // Is it a standard language code?
    if (regex_match(s, RE_LANG_CODE_PERMISSIVE))
    {
        std::wstring s2(s);
        TryNormalize(s2);
        if (IsValidCode(s2))
            return Language(s2);
    }

    // If not, perhaps it's a human-readable name (perhaps coming from the language control)?
    auto names = GetDisplayNamesData();
    icu::UnicodeString s_icu = ToIcuStr(s);
    s_icu.foldCase();
    std::wstring folded = StdFromIcuStr(s_icu);
    auto i = names.names.find(folded);
    if (i != names.names.end())
        return Language(i->second);

    // Maybe it was in English?
    i = names.namesEng.find(folded);
    if (i != names.namesEng.end())
        return Language(i->second);

    return Language(); // invalid
}
Example #4
0
void BigInteger::Private::assign( const std::string & s ) {
#if defined( __GNUC__ ) && !defined(__clang__)
	using boost::regex;
	using boost::smatch;
	using boost::regex_match;
#else
	using std::regex;
	using std::smatch;
	using std::regex_match;
#endif

	regex pattern( "^(0)|((-?)([1-9]\\d*))$" );
	smatch m;
	if( !regex_match( s, m, pattern ) ) {
		throw ValueError( "invalid number" );
	}
	if( m[1].matched ) {
		this->v.push_back( 0 );
	} else {
		if( m[3].length() != 0 ) {
			this->minus = true;
		}
		std::string buffer( m[4] );
		// add padding to 3 multiple
		if( s.size() % 3 != 0 ) {
			buffer.insert( 0, 3 - s.size() % 3, ' ' );
		}
		for( std::size_t i = 0; i < buffer.size(); i += 3 ) {
			std::istringstream sin( buffer.substr( i, 3 ) );
			int j = -1;
			sin >> j;
			this->v.insert( this->v.begin(), j );
		}
	}
}
Example #5
0
LINDA_TYPE findFunctionType(std::string s) {
  // change string to all lower case, change \t to space
  std::locale loc;
  for (unsigned int i = 0; i < s.length(); i++) {
    s[i] = std::tolower(s[i], loc);
    if (s[i] == '\t')
      s[i] = ' ';
  }

  regex rIn(" *in *\\(.*\\).*");
  regex rOut(" *out *\\(.*\\).*");
  regex rEval(" *eval *\\(.*\\).*");
  regex rRd(" *rd *\\(.*\\).*");
  regex rRdp(" *rdp *\\(.*\\).*");
  regex rInp(" *inp *\\(.*\\).*");
  regex rDump(" *dump *\\(.*\\).*");

  regex rIf(" *if.*");
  regex rFor(" *for.*");
  regex rDefine(" *define.*");
  cmatch m;
  if (regex_match(s.c_str(), m, rIn))
    return IN;
  else if (regex_match(s.c_str(), m, rOut))
    return OUT;
  else if (regex_match(s.c_str(), m, rEval))
    return EVAL;
  else if (regex_match(s.c_str(), m, rRd))
    return RD;
  else if (regex_match(s.c_str(), m, rRdp))
    return RDP;
  else if (regex_match(s.c_str(), m, rInp))
    return INP;
  else if (regex_match(s.c_str(), m, rDump))
    return DUMP;
  else if (regex_match(s.c_str(), m, rIf))
    return IF;
  else if (regex_match(s.c_str(), m, rFor))
    return FOR;
  else if (regex_match(s.c_str(), m, rDefine))
    return DEFINE;
  return OTHER;
}
Example #6
0
// Only support int, double, string as user defined function's parameters.
std::string generateArgs(std::vector<std::string> &args) {
  std::string argStr = "";
  regex intR("int .*");
  regex doubleR("double .*");
  regex stringR("string .*");
  cmatch m;
  for (size_t i = 0; i < args.size(); i++) {
    if (regex_match((args[i]).c_str(), m, intR)) {
      argStr = argStr + "\n\t" + args[i] + " = atoi(argv[" + std::to_string(static_cast<long long int>(i + 1)) + "])"+ ";";
    } else if (regex_match((args[i]).c_str(), m, doubleR)) {
      argStr = argStr + "\n\t" + args[i] + " = atof(argv[" + std::to_string(static_cast<long long int>(i + 1)) + "])"+ ";";      
    } else if (regex_match((args[i]).c_str(), m, stringR)) {
      argStr = argStr + "\n\t" + args[i] + "(argv[" + std::to_string(static_cast<long long int>(i + 1)) + "])"+ ";";
    } else {
      std::cout << "Couldn't recognize user defined function parameter." << std::endl;
      exit(EXIT_FAILURE);
    }
  }
  return argStr;
}
Example #7
0
void ConfigFile::loadFromPropertiesStream(std::istream& propStream)
{
	using boost::algorithm::trim;
	using boost::regex;
	using boost::regex_match;
	using boost::smatch;
	using Util::unescapeString;

	// Expresiones regulares para distintos tipos de líneas
	regex reBlankOrCom("^(#.*)|(?:)$");
	regex reAssignment("^([A-Za-z.-]+)\\s*=\\s*(\\S.*)?");
	
	smatch matchRes;

	// Limpio los datos
	configMap_.clear();

	// Lo leo línea a línea
	std::string line;
	while (std::getline(propStream, line))
	{
		// Saco espacios al principio y al final
		trim(line);
		
		// Si está en blanco o es un coemntario, la ignoro
		if (regex_match(line, reBlankOrCom))
			continue;

		// Uso una expresión regular para partirlo en un par clave-valor
		if (!regex_match(line, matchRes, reAssignment))
			// No es ni comentario, ni línea en blanco ni asignación
			throw 0; // FIXME: Lanzar algo más significativo

		// Guardo ese par en el mapa (no me preocupo de pisar pares anteriores)
		configMap_[matchRes.str(1)] = unescapeString(matchRes.str(2));
	}
}
Example #8
0
pair<bool, uniqued_name> add_concrete_type_if_absent(iterator_df<type_die> t, master_relation_t& r)
{
	// we might get called on to add void
	if (t == iterator_base::END)
	{
		return make_pair(false, make_pair("", ""));
	}

	assert(t == t->get_concrete_type());

	
// 	/* If it's a base type, we might not have a decl_file, */
// 	if (!t->get_decl_file() || *t->get_decl_file() == 0)
// 	{
// 		if (t.tag_here() != DW_TAG_base_type
// 		 && t.tag_here() != DW_TAG_pointer_type
// 		 && t.tag_here() != DW_TAG_reference_type
// 		 && t.tag_here() != DW_TAG_rvalue_reference_type
// 		 && t.tag_here() != DW_TAG_array_type
// 		 && t.tag_here() != DW_TAG_subroutine_type)
// 		{
// 			cerr << "Warning: skipping non-base non-pointer non-array non-subroutine type described by " << *t //
// 			//if (t.name_here()) cerr << t.name_here();
// 			//else cerr << "(unknown, offset: " << std::hex << t.offset_here() << std::dec << ")";
// 			/*cerr */ << " because no file is recorded for its definition." << endl;
// 			return make_pair(false, make_pair("", ""));
// 		}
// 		// else it's a base type, so we go with the blank type
// 		// FIXME: should canonicalise base types here
// 		// (to the same as the ikind/fkinds come out from Cil.Pretty)
// 	}

	uniqued_name n = canonical_key_from_type(t);
	
	smatch m;
	bool already_present = r.find(n) != r.end();
	if (already_present
		&& t.tag_here() != DW_TAG_base_type
		&& !regex_match(n.second, m, regex(".*__(PTR|REF|FUN|RR|ARR[0-9]+)_.*")))
	{
		cerr << "warning: non-base non-pointer non-array non-function type named " << n.second << " already exists!" << endl;
	}
	r[n] = t;
	return make_pair(!already_present, n);
}
Example #9
0
spritesheet
spritesheet_from_ssp_file(
	const boost::filesystem::path& sheet_path
) {
	using boost::cmatch;
	using boost::regex;
	using boost::regex_match;
	
	string_vector lines(read_file(sheet_path));
	
	spritesheet sprites;
	regex expression(
		"\\s?([-_0-9a-z]+)"
		"\\s?="
		"\\s?(\\d+)"
		"\\s+(\\d+)"          
		"\\s+(\\d+)"
		"\\s+(\\d+)",
		regex::extended | regex::icase
	);
	
	int n = 1;
	
	for (auto line : lines) {
		cmatch what;
		if (regex_match(line.c_str(), what, expression)) {
			sprites.insert(std::make_pair(
				what[1],
				rect(
					std::stoi(what[2]),
					std::stoi(what[3]),
					std::stoi(what[4]),
					std::stoi(what[5])
				)
			));
		} else if (!line.empty()) {
			RUNTIME_ERROR("failed to process sprite sheet line"
				" #%1%: \"%2%\"", n, line);
		}
		n++;
	}
	
	return sprites;
}
Example #10
0
/**
 * @return the loaded keys count.
 */
size_t KeyManager::loadKeys() {
	BOOST_LOG_NAMED_SCOPE("KeyManager::loadKeys");
	itsKeyList.resize(0);
	itsKeyMapByPublicId.clear();
	list<path> myDamagedFiles;
	for (auto it = recursive_directory_iterator(getConfigDir());
			it != recursive_directory_iterator(); it++) {
		boost::smatch matchProd;
		const path myFNameWithPath(it->path().native());
		const path myFName(it->path().filename().native());
		if (!is_directory(it->path())
				&& regex_match(myFName.string(), matchProd, K_KEY_FILTER)) {
			BOOST_LOG_TRIVIAL(debug)<< "Found key file " << myFName << ".";
			try {
				YubikoOtpKeyConfig* myCfg = new YubikoOtpKeyConfig(*this, myFNameWithPath);
				myCfg->load();
				YubikoOtpKeyConfigPtr myKey {myCfg};
				itsKeyList.emplace_back(myKey);
				string myId(myKey->getPublicId());
				if (myId.empty()) {
					(myId += "generated:") += myKey->getFilename().string();
				}
				itsKeyMapByPublicId.emplace(KeyMap_t::value_type {myId, myKey.get()});
			} catch( std::exception& myExc ) {
				BOOST_LOG_TRIVIAL(error)<<"Exception caugh while loading key file \"" << myFName << "\" - "<< myExc.what();
				myDamagedFiles.push_back(myFNameWithPath);
			} catch(...) {
				BOOST_LOG_TRIVIAL(error)<<"Unknown exception caugh while loading key file \"" << myFName << "\".";
				myDamagedFiles.push_back(myFNameWithPath);
			}
		} else {
			BOOST_LOG_TRIVIAL(debug)<< "Skipping file  " << myFName << ".";
		}
	}
	for( path myFName : myDamagedFiles) {
		prefixKeyFile(myFName,"damaged");
	}
	return itsKeyList.size();
}
Example #11
0
  parser_type operator()(const message_type& msg) const
  {
    // Important: copy path to local
    const string path(msg.request().path());
      
    smatch what;
    if(!regex_match(path, what, pattern_, match_single_line))
      return fail(msg, set_error);

    part v1;
    if(what.size() > 0)
      v1 = what[0];

    if(func_1_)
      return func_1_(msg, v1);

    part v2;
    if(what.size() > 1)
      v2 = what[1];

    if(func_2_)
      return func_2_(msg, v1, v2);

    part v3;
    if(what.size() > 2)
      v3 = what[2];

    if(func_3_)
      return func_3_(msg, v1, v2, v3);

    part v4;
    if(what.size() > 3)
      v4 = what[3];

    if(func_4_)
      return func_4_(msg, v1, v2, v3, v4);

    return parse(msg);
  }
Example #12
0
int main( int argc, char *argv[] ) {
	std::string  visPath;
	std::string  visExt;
	std::string  backendPath;
	std::string  single;
	std::string  title;
	int          fps;
	int          wndWidth, wndHeight;
	bool         noEffects;
	bool         verbose;
	bool         singleMode;

	GUI::Backend::WindowParams wndParams;

	po::options_description desc("Graphene command line options");
	desc.add_options()
		("help,h",  "Help message")
		("version,v",  "Print version")
		("visPath", po::value<std::string>(&visPath) ->required(), "Path to visualizer shared libraries")
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
		("visExt",  po::value<std::string>(&visExt)  ->default_value(".dll"), "File extension of visualizer shared libraries")
		("backend", po::value<std::string>(&backendPath) ->default_value("GrapheneQt5.dll"), "Path to backend library")
#else
		("visExt",  po::value<std::string>(&visExt)  ->default_value(".so"), "File extension of visualizer shared libraries")
		("backend", po::value<std::string>(&backendPath) ->default_value(PREFIX"/lib/libGrapheneQt5.so"), "Path to backend library")
#endif
		("single",     po::value<std::string>(&single) ->default_value(""), "Use the given name as single mode visualizer")
		("title",      po::value<std::string>(&title) ->default_value("graphene"), "Window title")
		("width",      po::value<int>(&wndWidth)  ->default_value(1024), "Path to backend library")
		("height",     po::value<int>(&wndHeight) ->default_value(576), "Path to backend library")
		("fps",        po::value<int>(&fps) ->default_value(60), "Frames Per Second")
		("logX",       po::value<int>(&wndParams.logX)->default_value(-1), "Log window position x")
		("logY",       po::value<int>(&wndParams.logY)->default_value(-1), "Log window position y")
		("logWidth",   po::value<int>(&wndParams.logWidth)->default_value(-1), "Log window width")
		("logHeight",  po::value<int>(&wndParams.logHeight)->default_value(-1), "Log window height")
		("propX",      po::value<int>(&wndParams.propX)->default_value(-1), "Property window position x")
		("propY",      po::value<int>(&wndParams.propY)->default_value(-1), "Property window position y")
		("propWidth",  po::value<int>(&wndParams.propWidth)->default_value(-1), "Property window width")
		("propHeight", po::value<int>(&wndParams.propHeight)->default_value(-1), "Property window height")
		("no-effects", "Use simple rendering techniques (e.g. no depth-of-field)")
		("maximized", "Show main window maximized")
		("verbose", "Output additional debug messages")
	;

	// Check for required options.
	po::variables_map vm;
	bool optionsException = false;
	try {
		po::store(po::parse_command_line(argc, argv, desc), vm);
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32)
		fs::path cfgFile("graphene.conf");
#else
		fs::path cfgFile(std::string(getenv("HOME"))+"/.graphene.conf");
#endif
		std::ifstream in;
		if (fs::exists(cfgFile)) {
			in.open(cfgFile.string().c_str());
			po::store(po::parse_config_file(in, desc), vm);
			in.close();
		} else {
			std::cout << "config file does not exist" << "\n";
		}
		po::notify(vm);
	} catch (std::exception& e) {
		if (!vm.count("help")) {
			std::cout << e.what() << "\n";
		}
		optionsException = true;
	}
	if (optionsException || vm.count("help")) {
		std::cout << desc << "\n";
		return optionsException ? 1 : 0;
	}
	if (vm.count("version")) {
		std::cout << "graphene version: " << VERSION_MAJOR << "." << VERSION_MINOR << "\n";
		return 0;
	}
	wndParams.maximized = vm.count("maximized") > 0;
	noEffects = vm.count("no-effects") > 0;
	verbose = vm.count("verbose") > 0;
	singleMode = single != "";

	// sanitize paths
	substituteHome(visPath);
	substituteHome(backendPath);

	FW::Events::EventHandler::Ptr eventHandler(new FW::Events::EventHandler());

	GUI::Backend::Ptr backend = getBackend(backendPath);
	if (!backend) return 1;
	backend->init(argc, argv, eventHandler, wndParams, singleMode, verbose);
	backend->setWindowTitle(title);
	backend->setWindowSize(wndWidth, wndHeight);

	Graphene graphene(backend, eventHandler, singleMode, noEffects);

	if (singleMode) {
		fs::path p(visPath);
		p = p / ("vis"+single+visExt);
		if (fs::is_directory(p)) {
			backend->getLog()->error("Input factory is a directory: " + p.string());
			return graphene.run(fps);
		}
		if (!fs::exists(p)) {
			backend->getLog()->error("Input factory does not exist: " + p.string());
			return graphene.run(fps);
		}
		ext::shared_library lib(p.string());
		if (!lib.open()) {
			backend->getLog()->error("Library failed to open: " + p.string());
			return graphene.run(fps);
		}
		std::function<FW::Factory* ()> retrFactory(lib.get<FW::Factory*>("getFactory"));
		if (!retrFactory) {
			backend->getLog()->error("Function \"getFactory\" not found in \""+p.string()+"\". Try adding VIS_DLL_EXPORT(VIS) macro.");
			return graphene.run(fps);
		}
		backend->getLog()->info("Visualizer type \"" + single + "\" initialized");
		FW::Factory* factoryPtr = retrFactory();
		std::shared_ptr<FW::Factory> factory(factoryPtr);
		graphene.addFactory(single, factory);
	} else {
		fs::directory_iterator dirIt(visPath), endIt;
		for (; dirIt != endIt; ++dirIt) {
			fs::path p = dirIt->path();
			if (fs::is_directory(p)) continue;
			smatch what;
			regex pattern("vis(\\w+)"+visExt);
			std::string filename = p.filename().string();
			if (!regex_match(filename, what, pattern)) continue;
			std::string name = what[1];
			ext::shared_library lib(p.string());
			if (!lib.open()) {
				backend->getLog()->warn("Library failed to open: " + p.string());
				continue;
			}
			std::function<FW::Factory* ()> retrFactory(lib.get<FW::Factory*>("getFactory"));
			if (!retrFactory) {
				backend->getLog()->warn("Function \"getFactory\" not found in \""+p.string()+"\". Try adding VIS_DLL_EXPORT(VIS) macro.");
				continue;
			}
			backend->getLog()->info("Adding visualizer type: " + name);
			FW::Factory* factoryPtr = retrFactory();
			std::shared_ptr<FW::Factory> factory(factoryPtr);
			graphene.addFactory(name, factory);
		}
	}

	return graphene.run(fps);
}
Example #13
0
bool Language::IsValidCode(const std::wstring& s)
{
    return regex_match(s, RE_LANG_CODE);
}
Example #14
0
bool isExp(std::string &s) {
  regex rx(".*\\(.*\\)");
  cmatch m;
  return regex_match(s.c_str(), m, rx);
}