コード例 #1
0
ファイル: environment.hpp プロジェクト: sirjaren/utsushi
  void
  clearenv_(const std::string& regular_expression)
  {
    regex re (regular_expression);
    cmatch var;

    char **p = environ;
    while (p && *p)
      {
        if (regex_match (*p, var, re))
          {
            unsetenv (var[1]);
          }
        ++p;
      }
  }
コード例 #2
0
ファイル: Object.cpp プロジェクト: kubawal/Samolocik
bool Object::Parse(string filename)
{
	ifstream ifs(filename);
	if(!ifs)
		return false;

	regex row[6] = 
	{
		regex("BEGFILE$"),
		regex("OBJNAME (\\w+)$"),
		regex("FILENAME (.+)$"),
		regex("PTS (\\d+)$"),
		regex("DMG (\\d+)$"),
		regex("ENDFILE$")
	};
	
	smatch match;
	string in;

	getline(ifs, in);
	if(!regex_match(in, match, row[0]))
		return false;


	getline(ifs, in);
	if(!regex_match(in, match, row[1]))
		return false;
	else
		name = match[1]; 
	

	getline(ifs, in);
	if(!regex_match(in, match, row[2]))
		return false;
	else
		graphfile = match[1];   

	getline(ifs, in);
	if(!regex_match(in, match, row[3]))
		return false;
	else
		points = from_string<int>(match[1]);

	getline(ifs, in);
	if(!regex_match(in, match, row[4]))
		return false;
	else
		damage = from_string<int>(match[1]);

	getline(ifs, in);
	if(!regex_match(in, match, row[5]))
		return false;

	return true;
}
コード例 #3
0
//-----------------------------------------------------------------------------------------
void OgitorsRoot::GetObjectListByCustomProperty(unsigned int type, const Ogre::String& nameregexp, bool inverse, ObjectVector& list)
{
    list.clear();

    try
    {
        const boost::regex e(nameregexp.c_str());

        NameObjectPairList::iterator list_st, list_ed;

        if(type == 0)
        {
            list_st = mNameList.begin();
            list_ed = mNameList.end();
        }
        else
        {
            list_st = mNamesByType[type].begin();
            list_ed = mNamesByType[type].end();
        }

        OgitorsPropertyVector pvec;

        while(list_st != list_ed)
        {
            pvec = list_st->second->getCustomProperties()->getPropertyVector();
            bool add_list = false;
            for(unsigned int k = 0;k < pvec.size();k++)
            {
                if(regex_match(pvec[k]->getName().c_str(), e))
                {
                    add_list = true;
                    break;
                }
            }
            
            if(add_list != inverse)
                list.push_back(list_st->second);
            
            list_st++;
        }
    }
    catch(...)
    {
        list.clear();
    }
}
コード例 #4
0
bool ClienteDeNotificaciones::inicializar	(	const std::string& rutaFicheroServidores,
												const std::string& rutaFicheroFiltro,
												const std::string& rutaFicheroHistorial,
												int tiempoExpiracionNotificaciones,
												bool mostrarRutaCompletaNotificaciones,
												bool mostrarRemitenteNotificaciones,
												int numeroSesionesAntiguas )
{
	//Se inicializa el notificador; en caso de problemas, se retorna false
	if (!notificador_.inicializar(nombre_de_aplicacion_, rutaFicheroFiltro)) return false;
	
	//Se configura el notificador con en base a los parámetros recibidos
	notificador_.establecer_tiempo_visible(tiempoExpiracionNotificaciones);
	notificador_.establecer_mostrar_ruta_completa(mostrarRutaCompletaNotificaciones);
	notificador_.establecer_anadir_remitente(mostrarRemitenteNotificaciones);
	notificador_.establecer_numero_de_historiales_antiguos(numeroSesionesAntiguas);
	notificador_.establecer_historial_de_sesion(rutaFicheroHistorial);
	
	//Se parsea el fichero de servidores, conectando a cada uno de los especificados
	ifstream fichero_servidores;
	fichero_servidores.open(rutaFicheroServidores);
	if (!fichero_servidores.is_open()) return false;
	
	string linea = "";
	string direccion = "";
	string puerto = "";
	while (getline(fichero_servidores, linea))
	{
		//if (regex_match(linea, regex("[.]+/[\\d]+")))
		if (regex_match(linea, regex("[^/]+/[\\d]+")))
		{
			direccion = linea.substr(0, linea.find_first_of('/'));
			puerto = linea.substr(linea.find_first_of('/') + 1, string::npos);
			conectarServidor(anadirServidor(direccion, puerto));
			
		}
		
	}
	fichero_servidores.close();
	
	//Si la lista de proveedores está vacía, se retorna error para informar de que ha habido algún problema
	if (proveedores_.empty()) return false;
	
	//Se espera a que no quede ningún Servidor activo para finalizar
	for (unsigned int i = 0; i < proveedores_.size(); ++i) proveedores_[i].esperar();
	return true;
}
コード例 #5
0
/** @brief (validate operation field with regex)
  * match operand with different operand regexes and extract operand from string
  * if does not match make operand field empty and generate error message
  */
bool InputReader::validateOperand() {
    if(autalities::tolow(operation) == "word"){
        autalities::removeTrailingSpaces(operand);
        return true;
    }
    smatch sm;
    regex r1("[xX]\'[a-fA-F0-9]+\'\\s*", regex_constants::ECMAScript);
    regex r2("[cC]\'(\\w|\\W)+\'\\s*", regex_constants::ECMAScript);
    if(regex_match(operand, r1) || regex_match(operand, r2)) {
        autalities::removeTrailingSpaces(operand);
        return true;
    } else if (regex_match(operand, sm, OPERAND_REGEX)) {
        autalities::removeTrailingSpaces(operand);
        return true;
    } else if (regex_match(operand, sm, IMMEDIATE_INDIRECT_REGEX)) {
        autalities::removeTrailingSpaces(operand);
        return true;
    } else if (regex_match(operand, sm, TWO_OPERANDS_REGEX)) {
        autalities::removeTrailingSpaces(operand);
        return true;
    } else if (regex_match(operand, sm, LITERAL_CHAR_REGEX)) {
        autalities::removeTrailingSpaces(operand);
        return true;
    } else if(regex_match(operand, sm, LITERAL_HEX_REGEX)) {
        autalities::removeTrailingSpaces(operand);
        return true;
    } else if(regex_match(operand, sm, INDEXING_REGEX)) {
        autalities::removeTrailingSpaces(operand);
        return true;
    } else if(regex_match(operand , sm, IS_HEX_REGEX)){
        autalities::removeTrailingSpaces(operand);
        return true;
    }
    operand = "";
    valid = false;
    addToErrorMessage("wrong format operand field");
    //cout << operand << "\n";
    return false;
}
コード例 #6
0
ファイル: filesnarf.c プロジェクト: IFGHou/dsniff
void
nfs3_call(u_int32_t xid, u_int32_t proc, u_char *buf, int len)
{
	XDR xdrs;
	struct LOOKUP3args largs;
	struct READ3args rargs;
	struct myreadargs *ma;
	char *fname;
	
	switch (proc) {
		
	case NFSPROC3_LOOKUP:
		memset(&largs, 0, sizeof(largs));
		xdrmem_create(&xdrs, buf, len, XDR_DECODE);
		
		if (xdr_LOOKUP3args(&xdrs, &largs)) {
			if (regex_match(largs.what.name)) {
				xid_map_enter(xid, NFS_PROGRAM, NFS_V3,
					      proc, (void *)largs.what.name);
			}
		}
		xdr_destroy(&xdrs);
		break;
		
	case NFSPROC3_READ:
		memset(&rargs, 0, sizeof(rargs));
		xdrmem_create(&xdrs, buf, len, XDR_DECODE);
		
		if (xdr_READ3args(&xdrs, &rargs)) {
			fname = fh_map_find(rargs.file.data.data_val,
					    rargs.file.data.data_len);
			if (fname != NULL) {
				ma = (struct myreadargs *) malloc(sizeof(*ma));
				if (ma != NULL) {
					ma->filename = fname;
					ma->offset = rargs.offset;
					xid_map_enter(xid, NFS_PROGRAM, NFS_V3,
						      NFSPROC_READ,
						      (void *)ma);
				}
			}
		}
		xdr_destroy(&xdrs);
		break;
	}
}
コード例 #7
0
ファイル: filesnarf.c プロジェクト: IFGHou/dsniff
void
nfs2_call(u_int32_t xid, u_int32_t proc, u_char *buf, int len)
{
	XDR xdrs;
	struct diropargs dargs;
	struct readargs rargs;
	struct myreadargs *ma;
	char *fname;
	
	switch (proc) {
		
	case NFSPROC_LOOKUP:
		memset(&dargs, 0, sizeof(dargs));
		xdrmem_create(&xdrs, buf, len, XDR_DECODE);
		
		if (xdr_diropargs(&xdrs, &dargs)) {
			if (regex_match(dargs.name)) {
				xid_map_enter(xid, NFS_PROGRAM, NFS_VERSION,
					      proc, (void *)dargs.name);
			}
		}
		xdr_destroy(&xdrs);
		break;
		
	case NFSPROC_READ:
		memset(&rargs, 0, sizeof(rargs));
		xdrmem_create(&xdrs, buf, len, XDR_DECODE);
		
		if (xdr_readargs(&xdrs, &rargs)) {
			fname = fh_map_find(rargs.file.data, NFS_FHSIZE);
			if (fname != NULL) {
				ma = (struct myreadargs *) malloc(sizeof(*ma));
				if (ma != NULL) {
					ma->filename = fname;
					ma->offset = rargs.offset;
					xid_map_enter(xid, NFS_PROGRAM,
						      NFS_VERSION,
						      NFSPROC_READ,
						      (void *)ma);
				}
			}
		}
		xdr_destroy(&xdrs);
		break;
	}
}
コード例 #8
0
tImage* TextureManager::registerTexture(string path) 
{
	string trimmed_path, forced_ext;
	tImage *img;

	//std::count << path.length() << "test" << std::endl;
	printf("registeringShader:\n");

	if (path.length() <= 0) {
		return NULL;
	}

	trimmed_path = path.substr(0, path.find_last_of('.'));

	/* see if we've already loaded this shader */
	img = getTextureByName(trimmed_path);
	if (img != NULL) {
		std::cout << "\texisting texture found" << std::endl;
		return img;
	}

	/* check to see if this shader is just a static texture */
	if (regex_match(path.begin(), path.end(), image_file_regex)) {
		std::cout << "\tstatic texture detected: " << path << std::endl;
		img = _allocateTexture(path);

		// default path does not work, try .jpg instead
		if (img == NULL) {
			forced_ext = trimmed_path + DEFAULT_IMG_EXT;
			img = _allocateTexture(forced_ext);
		}
	} else {
		std::cout << "\tunsupported shader type " << path << std::endl;
	}

	if (img == NULL)
	{
		SHADOW_LOG_ERROR("UNABLE TO LOAD IMAGE");
		return NULL;
	}

	/* add this texture to the map */
	textures[trimmed_path] = img;

	return img;
}
コード例 #9
0
ファイル: parser.cpp プロジェクト: DeukYeolChoe/WebBrowser
wstring Parser::getFormMethod(wstring content)
{
	wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
	wstring method = L"";
	content.erase(remove(content.begin(), content.end(), '\t'), content.end());
	wstring contentInfo = content;

	const wregex re(L"(<form[^>]*method=['|\"](.*?)['|\"].*?>)", regex::icase);

	wsmatch results;
	if (regex_match(contentInfo.cbegin(), contentInfo.cend(), results, re))
	{
		method = results[1];
		wcout << "Method = " << method << endl;
	}
	return method;
}
コード例 #10
0
   bool 
   RegularExpression::TestExactMatch(const String &sExpression, const String &sValue)
   {
      try
      {
         wregex expression(sExpression); 
         
         if(regex_match(sValue, expression)) 
            return true;
      }
      catch (std::runtime_error &) // regex_match will throw runtime_error if regexp is too complex.
      {
         return false;
      }

      return false;
   }
コード例 #11
0
ファイル: ParserList.cpp プロジェクト: sudarsangp/todomanager
bool ParserList::getInstructionAndArguments(const string& userCommand,
        string& instruction,
        string& arguments) {
    regex rgx(regexInstructionAndArguments, regex_constants::icase);
    smatch matchResults;

    if (!regex_match(userCommand, matchResults, rgx)) {

        return false;
    }

    assert(matchResults.size() > ARGS_POS);
    instruction = matchResults[INSTRUCTION_POS];
    arguments = matchResults[ARGS_POS];

    return true;
}
コード例 #12
0
static int
hdr_plugin(TSCont contp, TSEvent event, void *edata) 
{
	TSHttpTxn txnp = (TSHttpTxn)edata;

	switch (event) {
		case TS_EVENT_HTTP_READ_REQUEST_HDR:
			regex_match(contp, txnp);
			break;
		case TS_EVENT_HTTP_SEND_RESPONSE_HDR:
			hdr_handler(contp, txnp);
			break;
		default:
			break;
	}
	return 0;
}
コード例 #13
0
ファイル: regex.cpp プロジェクト: r3c/tesca
		bool RegexLineReader::parse (const std::string& line)
		{
			smatch match;

			this->row.clear ();

			if (!regex_match (line, match, this->regex))
				return false;

			for (auto& pair: this->lookup)
			{
				if (pair.first < match.size ())
					this->row.set (pair.second, Variant (match[pair.first]));
			}

			return true;
		}
コード例 #14
0
ファイル: file-chooser.cpp プロジェクト: sirjaren/utsushi
void
file_chooser::on_file_type_changed ()
{
  Glib::RefPtr< Gtk::TreeSelection > s (file_type_.get_selection ());
  if (!s) return;

  Gtk::TreeModel::iterator it (s->get_selected ());
  if (!it) return;

  Gtk::TreeModel::Row r (*it);
  extension_list      l (r[column->exts]);

  if (l.empty ())
    {
      expander_.set_label (_("File Type"));
    }
  else
    {
      expander_.set_label ((format (_("File type: %1%"))
                            % r.get_value (column->text)).str ());

      if (!count (l.begin (), l.end (), get_current_extension ()))
        set_current_extension (l.front ());
    }

  if (!single_image_mode_)
    {
      single_file_.set_sensitive (supports_multi_image (get_current_name ()));
      if (!supports_multi_image (get_current_name ()))
        {
          if (!regex_match (get_current_name (), filename_re))
            {
              fs::path path (get_current_name ());
              fs::path stem (path.stem ());
              fs::path ext  (path.extension ());

              path = stem;
              path = path.native () + default_pattern_;
              path.replace_extension (ext);

              set_current_name (path.string ());
            }
        }
      single_file_.set_active (requests_single_file (get_current_name ()));
    }
}
コード例 #15
0
ファイル: ReceptionClient.cpp プロジェクト: azazel7/Jinn
bool ReceptionClient::initialiserClient()
{
    int nombreEssai = 0;
    this->socketClient = socket(AF_INET, SOCK_STREAM, 0);
    if(this->socketClient < 0)
    {
        GestionnaireLogger::ecrirMessage(FATAL, "Impossible de créer la socket");
        return false;
    }
    struct sockaddr_in sin = { 0 }; /* initialise la structure avec des 0 */
    boost::regex expression ("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    if(regex_match(this->ip, expression) == false)
    {
        //        resolution de nom
        struct hostent *hostinfo = NULL;
        hostinfo = gethostbyname(this->ip.c_str()); /* on récupère les informations de l'hôte auquel on veut se connecter */
        if (hostinfo == NULL) /* l'hôte n'existe pas */
        {
            GestionnaireLogger::ecrirMessage(ERROR, "Nom de domaine introuvable");
            close(this->socketClient);
            return false;
        }

        sin.sin_addr = *((struct in_addr *)hostinfo->h_addr); /* l'adresse se trouve dans le champ h_addr de la structure hostinfo */
    }
    else
    {
        sin.sin_addr.s_addr = inet_addr(this->ip.c_str());
    }

    sin.sin_port = htons(this->port); /* on utilise htons pour le port */
    sin.sin_family = AF_INET;

    while(connect(this->socketClient,(struct sockaddr *) &sin, sizeof(struct sockaddr)) == -1)
    {
        GestionnaireLogger::ecrirMessage(TypeMessage::ERROR, "Impossible de se connecter");
        nombreEssai++;
        if(nombreEssai == 10)
        {
            GestionnaireLogger::ecrirMessage(TypeMessage::FATAL, "Impossible de se connecter après dix essais");
            return false;
        }
        sleep(2);
    }
    return true;
}
コード例 #16
0
ファイル: CheckExternalScripts.cpp プロジェクト: palli/nscp
void CheckExternalScripts::addAllScriptsFrom(std::string str_path) {
	boost::filesystem::path path(str_path);
	if (path.has_relative_path())
		path = get_base_path() / path;
	file_helpers::patterns::pattern_type split_path = file_helpers::patterns::split_pattern(path);
	if (!boost::filesystem::is_directory(split_path.first))
		NSC_LOG_ERROR_STD("Path was not found: " + split_path.first.string());

	boost::regex pattern(split_path.second.string());
	boost::filesystem::directory_iterator end_itr; // default construction yields past-the-end
	for ( boost::filesystem::directory_iterator itr( split_path.first ); itr != end_itr; ++itr ) {
		if ( !is_directory(itr->status()) ) {
			std::string name = file_helpers::meta::get_filename(itr->path());
			if (regex_match(name, pattern))
				add_command(name, (split_path.first / name).string());
		}
	}
}
コード例 #17
0
ファイル: Toolbox.cpp プロジェクト: gbanana/orthanc
  void Toolbox::DecodeDataUriScheme(std::string& mime,
                                    std::string& content,
                                    const std::string& source)
  {
    boost::regex pattern("data:([^;]+);base64,([a-zA-Z0-9=+/]*)",
                         boost::regex::icase /* case insensitive search */);

    boost::cmatch what;
    if (regex_match(source.c_str(), what, pattern))
    {
      mime = what[1];
      content = what[2];
    }
    else
    {
      throw OrthancException(ErrorCode_BadFileFormat);
    }
  }
コード例 #18
0
ファイル: FormatField.cpp プロジェクト: dtaliun/auxc
void FormatField::parse(const char* start, const char* end) throw (VCFException) {
	genotypes = false;
	values.clear();
	text.assign(start, end);

	if (!regex_match(text, format_regex)) {
		throw VCFException(__FILE__, __FUNCTION__, __LINE__, "Error while parsing FORMAT field.");
	}

	sregex_token_iterator fields_iter(text.begin(), text.end(), format_split_regex, -1);
	while (fields_iter != send) {
		values.emplace_back(std::move(fields_iter->str()));
		++fields_iter;
	}
	if (values.front().compare("GT") == 0) {
		genotypes = true;
	}
}
inline unsigned parseDuration(const std::string &s)
{
    if (simple_duration_is_valid(s))
    {
        unsigned hours = 0;
        unsigned minutes = 0;
        unsigned seconds = 0;
        boost::regex e(
            "((\\d|\\d\\d):(\\d|\\d\\d):(\\d|\\d\\d))|((\\d|\\d\\d):(\\d|\\d\\d))|(\\d|\\d\\d)",
            boost::regex_constants::icase | boost::regex_constants::perl);

        std::vector<std::string> result;
        boost::algorithm::split_regex(result, s, boost::regex(":"));
        const bool matched = regex_match(s, e);
        if (matched)
        {
            if (1 == result.size())
            {
                minutes = std::stoul(result[0]);
            }
            if (2 == result.size())
            {
                minutes = std::stoul(result[1]);
                hours = std::stoul(result[0]);
            }
            if (3 == result.size())
            {
                seconds = std::stoul(result[2]);
                minutes = std::stoul(result[1]);
                hours = std::stoul(result[0]);
            }
            return (3600 * hours + 60 * minutes + seconds);
        }
    }
    else if (iso_8601_duration_is_valid(s))
    {
        util::iso_8601_grammar<std::string::const_iterator> iso_parser;
        boost::spirit::qi::parse(s.begin(), s.end(), iso_parser);

        return iso_parser.get_duration();
    }

    return std::numeric_limits<unsigned>::max();
}
コード例 #20
0
ファイル: Player.cpp プロジェクト: fredwulei/CSE532S
void Player::read(string name, string script)
{
	ifstream infile(script);
	if (!infile.is_open()) {
		string error = "[ERROR]:  Open file fail: " + script;
		throw CodeException(FAIL_FILE_OPEN, error.c_str());
	}
	string currentLine;
	//Using regular expression to check the data for each line
	regex re("^\\s*(\\d+)\\s*([^\\d\\s].*?)\\s*$");
	while (getline(infile, currentLine)) {
		smatch sm;
		regex_match(currentLine, sm, re);
		if (sm.size() > 0) {
			//Once the line match the RE, come in this if condition and insert data
			lines[stoi(sm[1])] = SingleLine(name, sm[2]);
		}
	}
}
コード例 #21
0
ファイル: xtube.com.cpp プロジェクト: evertoncl/haarpcache
// use this line to compile
// g++ -I. -fPIC -shared -g -o xtube.com.so xtube.com.cpp
//~ http.*\.(publicvideo|publicphoto)\.xtube\.com\/(videowall\/)?videos?\/.*(\.flv\?.*|\_Thumb\.flv$)
//~ 
string get_filename(string url, int *ra, int *rb) {
	vector<string> resultado;
	stringexplode(url,"/",&resultado);
	url = resultado.at(resultado.size() - 1);
	
	if (url.find("?") == string::npos) {
		return url;
	} else {
		resultado.clear();
		stringexplode(url, "?", &resultado);
		string tmp;
		if( (tmp = regex_match("[\\?&]fs=[0-9]+",resultado.at(1))) != "" ) {
			tmp.erase(0,4);
			*ra = atoi(tmp.c_str());
			*rb = -1;
		}
		return resultado.at(0);
	}
}
コード例 #22
0
ファイル: session_impl.cpp プロジェクト: gitforks/restbed
 const multimap< string, string > SessionImpl::parse_request_headers( istream& stream )
 {
     smatch matches;
     string data = "";
     multimap< string, string > headers;
     static const regex pattern( "^([^:.]*): *(.*)\\s*$" );
     
     while ( getline( stream, data ) and data not_eq "\r" )
     {
         if ( not regex_match( data, matches, pattern ) or matches.size( ) not_eq 3 )
         {
             throw runtime_error( "Your client has issued a malformed or illegal request header. That’s all we know." );
         }
         
         headers.insert( make_pair( matches[ 1 ].str( ), matches[ 2 ].str( ) ) );
     }
     
     return headers;
 }
コード例 #23
0
void MicroDVDSubtitleFormat::ReadFile(AssFile *target, agi::fs::path const& filename, std::string const& encoding) const {
	TextFileReader file(filename, encoding);

	target->LoadDefault(false);

	agi::vfr::Framerate fps;

	bool isFirst = true;
	while (file.HasMoreLines()) {
		boost::smatch match;
		std::string line = file.ReadLineFromFile();
		if (!regex_match(line, match, line_regex)) continue;

		std::string text = match[3].str();

		// If it's the first, check if it contains fps information
		if (isFirst) {
			isFirst = false;

			double cfr;
			if (agi::util::try_parse(text, &cfr)) {
				fps = cfr;
				continue;
			}

			// If it wasn't an fps line, ask the user for it
			fps = AskForFPS(true, false);
			if (!fps.IsLoaded()) return;
		}

		int f1 = boost::lexical_cast<int>(match[1]);
		int f2 = boost::lexical_cast<int>(match[2]);

		boost::replace_all(text, "|", "\\N");

		auto diag = new AssDialogue;
		diag->Start = fps.TimeAtFrame(f1, agi::vfr::START);
		diag->End = fps.TimeAtFrame(f2, agi::vfr::END);
		diag->Text = text;
		target->Line.push_back(*diag);
	}
}
コード例 #24
0
ファイル: setting.cpp プロジェクト: Carye/gdipp
bool gdipp_setting::is_process_excluded(const wchar_t *proc_name) const
{
	// if no process name is specified, return true if the current process is excluded
	// otherwise, return true if the specified process is excluded

	const wchar_t *final_name;
	if (proc_name == NULL)
		final_name = _process_name;
	else
		final_name = proc_name;

	for (list<const wstring>::const_iterator iter = _exclude_process.begin(); iter != _exclude_process.end(); iter++)
	{
		const wregex name_ex(iter->data(), regex_flags);
		if (regex_match(final_name, name_ex))
			return true;
	}

	return false;
}
コード例 #25
0
ファイル: stockholm.cpp プロジェクト: ihh/indelhistorian
void Stockholm::read (istream& in) {
  gf.clear();
  gc.clear();
  gs.clear();
  gr.clear();
  gapped.clear();

  smatch sm;
  map<string,string> seq;
  vguard<string> rowName;
  while (in && !in.eof()) {
    string line;
    getline(in,line);
    if (regex_match (line, sm, seq_re)) {
      if (!seq.count (sm.str(1)))
	rowName.push_back (sm.str(1));
      seq[sm.str(1)] += sm.str(2);
    } else if (regex_match (line, sm, gf_re))
      gf[sm.str(1)].push_back (sm.str(2));
    else if (regex_match (line, sm, gc_re))
      gc[sm.str(1)] += sm.str(2);
    else if (regex_match (line, sm, gr_re))
      gr[sm.str(2)][sm.str(1)] += sm.str(3);
    else if (regex_match (line, sm, gs_re))
      gs[sm.str(2)][sm.str(1)].push_back (sm.str(3));
    else if (regex_match (line, hash_re))
      continue;
    else if (regex_match (line, divider_re))
      break;
    else if (regex_match (line, nonwhite_re))
      Warn ("Unrecognized line in Stockholm file: %s", line.c_str());
  }
  for (const auto& name : rowName) {
    FastSeq fs;
    fs.name = name;
    fs.seq = seq[name];
    gapped.push_back (fs);
  }
}
コード例 #26
0
void ObjectRecognition::loadModels(boost::shared_ptr<std::vector<Object>> objects) {
    boost::filesystem::path models_path(ros::package::getPath("object_recognition") + "/trained_objects");
    boost::regex modelfile_pattern("^model_([a-z]+)[0-9]*[.]pcd$");
    for (boost::filesystem::recursive_directory_iterator iter(models_path), end; iter!=end; iter++) {
        boost::match_results<std::string::const_iterator> results;
        std::string file_path = iter->path().string(); 
        std::string file_name = iter->path().leaf().string(); 
        if (regex_match(file_name, results, modelfile_pattern)) {
            std::string object_name = std::string(results[1].first, results[1].second);
            Object trained_object;
            trained_object.label = object_name;
            if (-1 == pcl::io::loadPCDFile(file_path, *(trained_object.descriptors))) {
                ROS_ERROR_STREAM("Unable to load object model: \"" << file_path << "\"");
                continue;
            }
            objects->push_back(trained_object);
            ROS_INFO_STREAM("Loaded object model \"" << object_name << "\"");
        }
    }
}
コード例 #27
0
ファイル: Texture.cpp プロジェクト: RicardoCoutinho/SDL-2D
bool Texture::load( SDL_Renderer * renderer )
{
    dispose();
    
    bool success = true;
    regex regexp { REGEX_TEXTURE , regex_constants::ECMAScript };
    
    if ( regex_match( path, regexp ) )
    {
        SDL_Surface * surface = IMG_Load( path.c_str() );
        
        if( surface == NULL )
        {
            printf( "Unable to load image from %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
        }
        else
        {
            texture = SDL_CreateTextureFromSurface(renderer, surface);
            
            if ( texture == NULL)
            {
                printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
                success = false;
            }
            else
            {
                width  = surface->w;
                height = surface->h;
            }
            
            SDL_FreeSurface( surface );
        }
    }
    else
    {
        printf( "Failed to load texture from %s! Incompatible format\n", path.c_str() );
        success = false;
    }
    
    return success;
}
コード例 #28
0
std::string Limitless::loadFileToString(std::string path, std::string fileName)
{
	std::string buffer;
	std::string filePath=path+'/'+fileName;
	FILE *file=fopen(filePath.c_str(), "r");

	if(file != NULL)
	{
		int capacity=1024;
		char *localBuffer=(char *)malloc(capacity);
		boost::regex expression("^\\s*#include\\s*[\"<]\\s*([\\w.]+)\\s*[\">]\\s*?");

		while(fgets(localBuffer, capacity, file) != NULL)
		{
			while(strlen(localBuffer) == capacity-1)
			{
				if(localBuffer[capacity-2] == '\n')
					break;

				localBuffer=(char *)realloc(localBuffer, capacity+1024);

				if(localBuffer == NULL)
					return buffer;

				if(fgets(&localBuffer[capacity-1], 1025, file) == NULL)
					break;
				capacity+=1024;
			}

			boost::cmatch match;

			if(regex_match(localBuffer, match, expression))
				buffer+=loadFileToString(path, match[1]);
			else
				buffer+=localBuffer;
		}
		fclose(file);
		free(localBuffer);
	}
	return buffer;
}
コード例 #29
0
//-----------------------------------------------------------------------------------------
void OgitorsRoot::RegExpByName(const Ogre::String& nameregexp, bool inverse, const ObjectVector& list_in, ObjectVector& list_out)
{
    list_out.clear();
    
    try
    {
        const boost::regex e(nameregexp.c_str());

        for(unsigned int i = 0;i < list_in.size();i++)   
        {
            if(regex_match(list_in[i]->getName().c_str(), e) != inverse)
            {
                list_out.push_back(list_in[i]);
            }
        }
    }
    catch(...)
    {
        list_out.clear();
    }
}
コード例 #30
0
ファイル: SipParser.cpp プロジェクト: yookdin/mserver
//==========================================================================================================
//==========================================================================================================
SipParser::SipMatcher::SipMatcher(SipElement _elem, string _highlevel_re_str, bool _final):
    elem(_elem),
    highlevel_re_str(_highlevel_re_str),
    final(_final)
{
    if(final)
    {
        re_str = highlevel_re_str;
        re = re_str;
    }
}


//==========================================================================================================
// Return whether the given string matches this matcher SIP element
//==========================================================================================================
bool SipParser::SipMatcher::match(string line)
{
    cur_line = line;
    return regex_match(cur_line, match_result, re);
}