本文整理汇总了C++中Regex类的典型用法代码示例。如果您正苦于以下问题:C++ Regex类的具体用法?C++ Regex怎么用?C++ Regex使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Regex类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: getAuthenticatedName
bool Condor_Auth_X509::CheckServerName(char const *fqh,char const *ip,ReliSock *sock,CondorError *errstack)
{
if( param_boolean("GSI_SKIP_HOST_CHECK",false) ) {
return true;
}
char const *server_dn = getAuthenticatedName();
if( !server_dn ) {
std::string msg;
formatstr(msg,"Failed to find certificate DN for server on GSI connection to %s",ip);
errstack->push("GSI", GSI_ERR_DNS_CHECK_ERROR, msg.c_str());
return false;
}
std::string skip_check_pattern;
if( param(skip_check_pattern,"GSI_SKIP_HOST_CHECK_CERT_REGEX") ) {
Regex re;
const char *errptr=NULL;
int erroffset=0;
std::string full_pattern;
formatstr(full_pattern,"^(%s)$",skip_check_pattern.c_str());
if( !re.compile(full_pattern.c_str(),&errptr,&erroffset) ) {
dprintf(D_ALWAYS,"GSI_SKIP_HOST_CHECK_CERT_REGEX is not a valid regular expression: %s\n",skip_check_pattern.c_str());
return false;
}
if( re.match(server_dn,NULL) ) {
return true;
}
}
ASSERT( errstack );
ASSERT( m_gss_server_name );
ASSERT( ip );
if( !fqh || !fqh[0] ) {
std::string msg;
formatstr(msg,"Failed to look up server host address for GSI connection to server with IP %s and DN %s. Is DNS correctly configured? This server name check can be bypassed by making GSI_SKIP_HOST_CHECK_CERT_REGEX match the DN, or by disabling all hostname checks by setting GSI_SKIP_HOST_CHECK=true or defining GSI_DAEMON_NAME.",ip,server_dn);
errstack->push("GSI", GSI_ERR_DNS_CHECK_ERROR, msg.c_str());
return false;
}
std::string connect_name;
gss_buffer_desc gss_connect_name_buf;
gss_name_t gss_connect_name;
OM_uint32 major_status = 0;
OM_uint32 minor_status = 0;
char const *connect_addr = sock->get_connect_addr();
std::string alias_buf;
if( connect_addr ) {
Sinful s(connect_addr);
char const *alias = s.getAlias();
if( alias ) {
dprintf(D_FULLDEBUG,"GSI host check: using host alias %s for %s %s\n",alias,fqh,sock->peer_ip_str());
alias_buf = alias;
fqh = alias_buf.c_str();
}
}
formatstr(connect_name,"%s/%s",fqh,sock->peer_ip_str());
gss_connect_name_buf.value = strdup(connect_name.c_str());
gss_connect_name_buf.length = connect_name.size()+1;
major_status = gss_import_name(&minor_status,
&gss_connect_name_buf,
GLOBUS_GSS_C_NT_HOST_IP,
&gss_connect_name);
free( gss_connect_name_buf.value );
if( major_status != GSS_S_COMPLETE ) {
std::string comment;
formatstr(comment,"Failed to create gss connection name data structure for %s.\n",connect_name.c_str());
print_log( major_status, minor_status, 0, comment.c_str() );
return false;
}
int name_equal = 0;
major_status = gss_compare_name( &minor_status,
m_gss_server_name,
gss_connect_name,
&name_equal );
gss_release_name( &major_status, &gss_connect_name );
if( !name_equal ) {
std::string msg;
formatstr(msg,"We are trying to connect to a daemon with certificate DN (%s), but the host name in the certificate does not match any DNS name associated with the host to which we are connecting (host name is '%s', IP is '%s', Condor connection address is '%s'). Check that DNS is correctly configured. If the certificate is for a DNS alias, configure HOST_ALIAS in the daemon's configuration. If you wish to use a daemon certificate that does not match the daemon's host name, make GSI_SKIP_HOST_CHECK_CERT_REGEX match the DN, or disable all host name checks by setting GSI_SKIP_HOST_CHECK=true or by defining GSI_DAEMON_NAME.\n",
server_dn,
fqh,
ip,
connect_addr ? connect_addr : sock->peer_description() );
errstack->push("GSI", GSI_ERR_DNS_CHECK_ERROR, msg.c_str());
}
return name_equal != 0;
}
示例2: FormatHTMLChunk
void FormatHTMLChunk(TreeBuilder &treeBuilder,const char *buffer, size_t count)
{
RegexMatch match;
while (regexElementFinder.Match(buffer, count, match))
{
PrintMatches("link finder ", buffer, match);
FormatString(treeBuilder, buffer, match.End(1));
bool close = (match.Start(2) != match.End(2));
bool hasAttrs = (match.Start(4) != match.End(4));
string tagname(buffer + match.Start(3), match.Length(3));
size_t pos;
for (pos = 0; pos < tagname.length() && !isspace(tagname[pos]); ++pos)
{}
if (pos < tagname.length())
{
tagname.erase(pos, string::npos);
}
if (close)
{
treeBuilder.Pop(tagname);
}
else
{
ParseTreeNodePtr node(treeBuilder.NodeFactory(tagname));
treeBuilder.Push(node);
if (hasAttrs)
{
RegexMatch attrMatch;
const char *attrs = buffer + match.Start(4);
int attrLength = match.Length(4);
// printf("Attrs: %.*s\n", attrLength, attrs);
while (regexAttrMatch1.Match(attrs, attrLength, attrMatch)
|| regexAttrMatch2.Match(attrs, attrLength, attrMatch)
|| regexAttrMatch3.Match(attrs, attrLength, attrMatch))
{
PrintMatches("Attributes",attrs,attrMatch);
string attr(attrs + attrMatch.Start(1), attrMatch.Length(1));
treeBuilder.CurrentNode()->AddAttribute(attr.c_str());
// string val(attrs + attrMatch.Start(2), attrMatch.Length(2));
// treeBuilder.CurrentNode()->AddAttributeValue(val.c_str());
FormatAttribute(treeBuilder.CurrentNode(),
attrs + attrMatch.Start(2), attrMatch.Length(2));
attrs += attrMatch.End(3);
attrLength -= attrMatch.End(3);
}
if (match.Start(5) != match.End(5))
{
treeBuilder.Pop();
}
}
}
buffer += match.End(6);
count -= match.End(6);
}
FormatString(treeBuilder, buffer, count);
}
示例3: ASSERT_M
bool PlayerOptions::FromOneModString( const RString &sOneMod, RString &sErrorOut )
{
ASSERT_M( NOTESKIN != NULL, "The Noteskin Manager must be loaded in order to process mods." );
RString sBit = sOneMod;
sBit.MakeLower();
Trim( sBit );
/* "drunk"
* "no drunk"
* "150% drunk"
* "*2 100% drunk": approach at 2x normal speed */
float level = 1;
float speed = 1;
vector<RString> asParts;
split( sBit, " ", asParts, true );
FOREACH_CONST( RString, asParts, s )
{
if( *s == "no" )
{
level = 0;
}
else if( isdigit((*s)[0]) || (*s)[0] == '-' )
{
/* If the last character is a *, they probably said "123*" when
* they meant "*123". */
if( s->Right(1) == "*" )
{
// XXX: We know what they want, is there any reason not to handle it?
// Yes. We should be strict in handling the format. -Chris
sErrorOut = ssprintf("Invalid player options \"%s\"; did you mean '*%d'?", s->c_str(), StringToInt(*s) );
return false;
}
else
{
level = StringToFloat( *s ) / 100.0f;
}
}
else if( *s[0]=='*' )
{
sscanf( *s, "*%f", &speed );
if( !isfinite(speed) )
speed = 1.0f;
}
}
sBit = asParts.back();
#define SET_FLOAT( opt ) { m_ ## opt = level; m_Speed ## opt = speed; }
const bool on = (level > 0.5f);
static Regex mult("^([0-9]+(\\.[0-9]+)?)x$");
vector<RString> matches;
if( mult.Compare(sBit, matches) )
{
StringConversion::FromString( matches[0], level );
SET_FLOAT( fScrollSpeed )
SET_FLOAT( fTimeSpacing )
m_fTimeSpacing = 0;
m_fMaxScrollBPM = 0;
}
else if( sscanf( sBit, "c%f", &level ) == 1 )
{
if( !isfinite(level) || level <= 0.0f )
level = CMOD_DEFAULT;
SET_FLOAT( fScrollBPM )
SET_FLOAT( fTimeSpacing )
m_fTimeSpacing = 1;
m_fMaxScrollBPM = 0;
}
// oITG's m-mods
else if( sscanf( sBit, "m%f", &level ) == 1 )
{
// OpenITG doesn't have this block:
/*
if( !isfinite(level) || level <= 0.0f )
level = CMOD_DEFAULT;
*/
SET_FLOAT( fMaxScrollBPM )
m_fTimeSpacing = 0;
}
else if( sBit == "clearall" )
{
Init();
m_sNoteSkin= NOTESKIN->GetDefaultNoteSkinName();
}
else if( sBit == "resetspeed" )
{
/* level is set to the values from Init() because all speed related
fields are being reset to initial values, and they each have different
initial values. -kyz */
level= 0;
SET_FLOAT(fMaxScrollBPM);
SET_FLOAT(fTimeSpacing);
level= 1.0f;
SET_FLOAT(fScrollSpeed);
level= CMOD_DEFAULT;
//.........这里部分代码省略.........
示例4: main
int main(int argc, char** argv) {
time_t currentTime = time(0);
fprintf(stderr, "Analysis started at: %s", ctime(¤tTime));
PARSE_PARAMETER(argc, argv);
PARAMETER_STATUS();
if (FLAG_REMAIN_ARG.size() > 0) {
fprintf(stderr, "Unparsed arguments: ");
for (unsigned int i = 0; i < FLAG_REMAIN_ARG.size(); i++) {
fprintf(stderr, " %s", FLAG_REMAIN_ARG[i].c_str());
}
fprintf(stderr, "\n");
abort();
}
REQUIRE_STRING_PARAMETER(FLAG_inVcf,
"Please provide input file using: --inVcf");
const char* fn = FLAG_inVcf.c_str();
VCFInputFile vin(fn);
// set range filters here
// e.g.
// vin.setRangeList("1:69500-69600");
vin.setRangeList(FLAG_rangeList.c_str());
vin.setRangeFile(FLAG_rangeFile.c_str());
// set people filters here
if (FLAG_peopleIncludeID.size() || FLAG_peopleIncludeFile.size()) {
vin.excludeAllPeople();
vin.includePeople(FLAG_peopleIncludeID.c_str());
vin.includePeopleFromFile(FLAG_peopleIncludeFile.c_str());
}
vin.excludePeople(FLAG_peopleExcludeID.c_str());
vin.excludePeopleFromFile(FLAG_peopleExcludeFile.c_str());
// let's write it out.
if (FLAG_updateId != "") {
int ret = vin.updateId(FLAG_updateId.c_str());
fprintf(stdout, "%d samples have updated id.\n", ret);
}
// load gene ranges
std::map<std::string, std::string> geneRange;
if (FLAG_geneName.size()) {
if (FLAG_geneFile.size() == 0) {
fprintf(stderr, "Have to provide --geneFile to extract by gene.\n");
abort();
}
LineReader lr(FLAG_geneFile);
std::vector<std::string> fd;
while (lr.readLineBySep(&fd, "\t ")) {
if (FLAG_geneName != fd[0]) continue;
fd[2] = chopChr(fd[2]); // chop "chr1" to "1"
if (geneRange.find(fd[0]) == geneRange.end()) {
geneRange[fd[0]] = fd[2] + ":" + fd[4] + "-" + fd[5];
} else {
geneRange[fd[0]] += "," + fd[2] + ":" + fd[4] + "-" + fd[5];
}
};
}
std::string range;
for (std::map<std::string, std::string>::iterator it = geneRange.begin();
it != geneRange.end(); it++) {
if (range.size() > 0) {
range += ",";
}
range += it->second;
};
fprintf(stderr, "range = %s\n", range.c_str());
vin.setRangeList(range.c_str());
Regex regex;
if (FLAG_annoType.size()) {
regex.readPattern(FLAG_annoType);
}
// print header
std::vector<std::string> names;
vin.getVCFHeader()->getPeopleName(&names);
printf("CHROM\tPOS");
for (unsigned int i = 0; i < names.size(); i++) {
printf("\t%s", names[i].c_str());
}
printf("\n");
// real working part
int nonVariantSite = 0;
while (vin.readRecord()) {
VCFRecord& r = vin.getVCFRecord();
VCFPeople& people = r.getPeople();
VCFIndividual* indv;
if (FLAG_variantOnly) {
bool hasVariant = false;
int geno;
int GTidx = r.getFormatIndex("GT");
for (size_t i = 0; i < people.size(); i++) {
indv = people[i];
geno = indv->justGet(GTidx).getGenotype();
//.........这里部分代码省略.........
示例5: FOREACH_CONST_Attr
//.........这里部分代码省略.........
utf8_get_char_len(sCodepoint[0]) == int(sCodepoint.size()) )
{
c = utf8_get_char( sCodepoint.c_str() );
if(c == wchar_t(-1))
LOG->Warn("Font definition '%s' has an invalid value '%s'.",
ini.GetPath().c_str(), sName.c_str() );
}
else if( !FontCharAliases::GetChar(sCodepoint, c) )
{
LOG->Warn("Font definition '%s' has an invalid value '%s'.",
ini.GetPath().c_str(), sName.c_str() );
continue;
}
cfg.CharToGlyphNo[c] = atoi( sValue );
continue;
}
if( sName.substr(0, 6) == "RANGE " )
{
/*
* range CODESET=first_frame or
* range CODESET #start-end=first_frame
* eg
* range CP1252=0 (default for 256-frame fonts)
* range ASCII=0 (default for 128-frame fonts)
*
* (Start and end are in hex.)
*
* Map two high-bit portions of ISO-8859- to one font:
* range ISO-8859-2 #80-FF=0
* range ISO-8859-3 #80-FF=128
*
* Map hiragana to 0-84:
* range Unicode #3041-3094=0
*/
vector<CString> asMatches;
static Regex parse("^RANGE ([A-Z\\-]+)( ?#([0-9A-F]+)-([0-9A-F]+))?$");
bool bMatch = parse.Compare( sName, asMatches );
ASSERT( asMatches.size() == 4 ); /* 4 parens */
if( !bMatch || asMatches[0].empty() )
RageException::Throw("Font definition '%s' has an invalid range '%s': parse error",
ini.GetPath().c_str(), sName.c_str() );
/* We must have either 1 match (just the codeset) or 4 (the whole thing). */
int iCount = -1;
int iFirst = 0;
if( !asMatches[2].empty() )
{
sscanf( asMatches[2].c_str(), "%x", &iFirst );
int iLast;
sscanf( asMatches[3].c_str(), "%x", &iLast );
if( iLast < iFirst )
RageException::Throw("Font definition '%s' has an invalid range '%s': %i < %i.",
ini.GetPath().c_str(), sName.c_str(), iLast < iFirst );
iCount = iLast - iFirst + 1;
}
CString sRet = cfg.MapRange( asMatches[0], iFirst, atoi(sValue), iCount );
if( !sRet.empty() )
RageException::Throw( "Font definition '%s' has an invalid range '%s': %s.",
ini.GetPath().c_str(), sName.c_str(), sRet.c_str() );
continue;
}
if( sName.substr(0, 5) == "LINE " )
{
/* line ROW=CHAR1CHAR2CHAR3CHAR4
* eg.
* line 0=ABCDEFGH
*
* This lets us assign characters very compactly and readably. */
CString sRowStr = sName.substr(5);
ASSERT( IsAnInt(sRowStr) );
const int iRow = atoi( sRowStr.c_str() );
const int iFirstFrame = iRow * iNumFramesWide;
if( iRow > iNumFramesHigh )
RageException::Throw( "The font definition \"%s\" tries to assign line %i, but the font is only %i characters high",
ini.GetPath().c_str(), iFirstFrame, iNumFramesHigh );
/* Decode the string. */
const wstring wdata( CStringToWstring(sValue) );
if( int(wdata.size()) > iNumFramesWide )
RageException::Throw( "The font definition \"%s\" assigns %i characters to row %i (\"%ls\"), but the font only has %i characters wide",
ini.GetPath().c_str(), wdata.size(), iRow, wdata.c_str(), iNumFramesWide );
for( unsigned i = 0; i < wdata.size(); ++i )
cfg.CharToGlyphNo[wdata[i]] = iFirstFrame+i;
}
}
}
示例6: push
void Perl_stack::push(const Regex& regex) {
XPUSHs(sv_2mortal(SvREFCNT_inc(regex.get_SV())));
}
示例7: Regex
SandboxVector SandboxUtils::findSandboxes(Module& M) {
FunctionIntMap funcToOverhead;
FunctionIntMap funcToClearances;
map<Function*,string> funcToSandboxName;
map<string,FunctionSet> sandboxNameToEntryPoints;
StringSet ephemeralSandboxes;
SandboxVector sandboxes;
// function-level annotations of sandboxed code
Regex *sboxPerfRegex = new Regex("perf_overhead_\\(([0-9]{1,2})\\)", true);
SmallVector<StringRef, 4> matches;
if (GlobalVariable* lga = M.getNamedGlobal("llvm.global.annotations")) {
ConstantArray* lgaArray = dyn_cast<ConstantArray>(lga->getInitializer()->stripPointerCasts());
for (User::op_iterator i=lgaArray->op_begin(), e = lgaArray->op_end(); e!=i; i++) {
ConstantStruct* lgaArrayElement = dyn_cast<ConstantStruct>(i->get());
// get the annotation value first
GlobalVariable* annotationStrVar = dyn_cast<GlobalVariable>(lgaArrayElement->getOperand(1)->stripPointerCasts());
ConstantDataArray* annotationStrArray = dyn_cast<ConstantDataArray>(annotationStrVar->getInitializer());
StringRef annotationStrArrayCString = annotationStrArray->getAsCString();
GlobalValue* annotatedVal = dyn_cast<GlobalValue>(lgaArrayElement->getOperand(0)->stripPointerCasts());
if (isa<Function>(annotatedVal)) {
Function* annotatedFunc = dyn_cast<Function>(annotatedVal);
StringRef sandboxName;
if (annotationStrArrayCString.startswith(SANDBOX_PERSISTENT) || annotationStrArrayCString.startswith(SANDBOX_EPHEMERAL)) {
sandboxEntryPoints.insert(annotatedFunc);
outs() << INDENT_1 << "Found sandbox entrypoint " << annotatedFunc->getName() << "\n";
outs() << INDENT_2 << "Annotation string: " << annotationStrArrayCString << "\n";
if (annotationStrArrayCString.startswith(SANDBOX_PERSISTENT)) {
sandboxName = annotationStrArrayCString.substr(strlen(SANDBOX_PERSISTENT)+1);
}
else if (annotationStrArrayCString.startswith(SANDBOX_EPHEMERAL)) {
sandboxName = annotationStrArrayCString.substr(strlen(SANDBOX_EPHEMERAL)+1);
ephemeralSandboxes.insert(sandboxName);
}
outs() << INDENT_2 << "Sandbox name: " << sandboxName << "\n";
if (funcToSandboxName.find(annotatedFunc) != funcToSandboxName.end()) {
outs() << INDENT_1 << "*** Error: Function " << annotatedFunc->getName() << " is already an entrypoint for another sandbox\n";
}
else {
funcToSandboxName[annotatedFunc] = sandboxName;
sandboxNameToEntryPoints[sandboxName].insert(annotatedFunc);
}
}
else if (sboxPerfRegex->match(annotationStrArrayCString, &matches)) {
int overhead;
outs() << INDENT_2 << "Threshold set to " << matches[1].str() <<
"%\n";
matches[1].getAsInteger(0, overhead);
funcToOverhead[annotatedFunc] = overhead;
}
else if (annotationStrArrayCString.startswith(CLEARANCE)) {
StringRef className = annotationStrArrayCString.substr(strlen(CLEARANCE)+1);
outs() << INDENT_2 << "Sandbox has clearance for \"" << className << "\"\n";
ClassifiedUtils::assignBitIdxToClassName(className);
funcToClearances[annotatedFunc] |= (1 << ClassifiedUtils::getBitIdxFromClassName(className));
}
}
}
}
// TODO: sanity check overhead and clearance annotations
// Combine all annotation information for function-level sandboxes to create Sandbox instances
for (pair<string,FunctionSet> p : sandboxNameToEntryPoints) {
string sandboxName = p.first;
FunctionSet entryPoints = p.second;
int idx = assignBitIdxToSandboxName(sandboxName);
int overhead = 0;
int clearances = 0;
bool persistent = find(ephemeralSandboxes.begin(), ephemeralSandboxes.end(), sandboxName) == ephemeralSandboxes.end();
// set overhead and clearances; any of the entry points could be annotated
for (Function* entryPoint : entryPoints) {
if (funcToOverhead.find(entryPoint) != funcToOverhead.end()) {
overhead = funcToOverhead[entryPoint];
}
if (funcToClearances.find(entryPoint) != funcToClearances.end()) {
clearances = funcToClearances[entryPoint];
}
}
SDEBUG("soaap.util.sandbox", 3, dbgs() << INDENT_2 << "Creating new Sandbox instance for " << sandboxName << "\n");
sandboxes.push_back(new Sandbox(sandboxName, idx, entryPoints, persistent, M, overhead, clearances));
SDEBUG("soaap.util.sandbox", 3, dbgs() << INDENT_2 << "Created new Sandbox instance\n");
}
/*
for (map<Function*,string>::iterator I=funcToSandboxName.begin(), E=funcToSandboxName.end(); I!=E; I++) {
Function* entryPoint = I->first;
string sandboxName = I->second;
int idx = assignBitIdxToSandboxName(sandboxName);
int overhead = funcToOverhead[entryPoint];
int clearances = funcToClearances[entryPoint];
bool persistent = find(ephemeralSandboxes.begin(), ephemeralSandboxes.end(), entryPoint) == ephemeralSandboxes.end();
SDEBUG("soaap.util.sandbox", 3, dbgs() << INDENT_2 << "Creating new Sandbox instance\n");
sandboxes.push_back(new Sandbox(sandboxName, idx, entryPoint, persistent, M, overhead, clearances));
SDEBUG("soaap.util.sandbox", 3, dbgs() << INDENT_2 << "Created new Sandbox instance\n");
}
//.........这里部分代码省略.........
示例8: name
namespace MCPP {
static const String name("Plugin Message Support");
static const Word priority=1;
static const String reg("REGISTER");
static const String unreg("UNREGISTER");
static const Regex is_builtin("^MC\\|");
static Vector<String> get_strings (const Vector<Byte> & buffer) {
// Decode
auto str=UTF8().Decode(buffer.begin(),buffer.end());
// Separate on NULL character
Vector<String> retr;
for (auto cp : str.CodePoints()) {
if (retr.Count()==0) retr.EmplaceBack();
if (cp=='\0') {
retr.EmplaceBack();
continue;
}
retr[retr.Count()-1] << cp;
}
return retr;
}
void PluginMessages::reg (SmartPointer<Client> client, Vector<Byte> data) {
auto channels=get_strings(data);
lock.Write([&] () mutable {
auto iter=clients.find(client);
if (iter==clients.end()) return;
for (auto & channel : channels) iter->second.insert(std::move(channel));
});
}
void PluginMessages::unreg (SmartPointer<Client> client, Vector<Byte> data) {
auto channels=get_strings(data);
lock.Write([&] () mutable {
auto iter=clients.find(client);
if (iter==clients.end()) return;
for (auto & channel : channels) iter->second.erase(channel);
});
}
void PluginMessages::handler (PacketEvent event) {
auto & packet=event.Data.Get<incoming>();
// Handle register/unregister separately
if (packet.Channel==MCPP::reg) {
reg(
std::move(event.From),
std::move(packet.Data)
);
return;
} else if (packet.Channel==MCPP::unreg) {
unreg(
std::move(event.From),
std::move(packet.Data)
);
return;
}
// Try and get associated handler
auto iter=callbacks.find(packet.Channel);
//.........这里部分代码省略.........
示例9: if
bool
Metric::evaluateDaemonAd(classad::ClassAd &metric_ad,classad::ClassAd const &daemon_ad,int max_verbosity,StatsD *statsd,ExtArray<MyString> *regex_groups,char const *regex_attr)
{
if( regex_attr ) {
name = regex_attr;
}
if( !evaluateOptionalString(ATTR_NAME,name,metric_ad,daemon_ad,regex_groups) ) return false;
metric_ad.EvaluateAttrInt(ATTR_VERBOSITY,verbosity);
if( verbosity > max_verbosity ) {
// avoid doing more work; this metric requires higher verbosity
return false;
}
std::string target_type_str;
if( !evaluateOptionalString(ATTR_TARGET_TYPE,target_type_str,metric_ad,daemon_ad,regex_groups) ) return false;
target_type.initializeFromString(target_type_str.c_str());
if( target_type.contains_anycase("machine_slot1") ) {
restrict_slot1 = true;
}
std::string my_type;
daemon_ad.EvaluateAttrString(ATTR_MY_TYPE,my_type);
if( !target_type.isEmpty() && !target_type.contains_anycase("any") ) {
if( restrict_slot1 && !strcasecmp(my_type.c_str(),"machine") ) {
int slotid = 1;
daemon_ad.EvaluateAttrInt(ATTR_SLOT_ID,slotid);
if( slotid != 1 ) {
return false;
}
bool dynamic_slot = false;
daemon_ad.EvaluateAttrBool(ATTR_SLOT_DYNAMIC,dynamic_slot);
if( dynamic_slot ) {
return false;
}
}
else if( !target_type.contains_anycase(my_type.c_str()) ) {
// avoid doing more work; this is not the right type of daemon ad
return false;
}
}
classad::Value requirements_val;
requirements_val.SetBooleanValue(true);
if( !evaluate(ATTR_REQUIREMENTS,requirements_val,metric_ad,daemon_ad,BOOLEAN,regex_groups,regex_attr) ) {
return false;
}
bool requirements = true;
if( !requirements_val.IsBooleanValue(requirements) || requirements!=true ) {
return false;
}
if( !regex_attr ) {
std::string regex;
if( !evaluateOptionalString(ATTR_REGEX,regex,metric_ad,daemon_ad,NULL) ) return false;
if( !regex.empty() ) {
Regex re;
const char *errptr=NULL;
int erroffset=0;
if( !re.compile(regex.c_str(),&errptr,&erroffset,PCRE_ANCHORED) ) {
EXCEPT("Invalid regex %s",regex.c_str());
}
for( classad::ClassAd::const_iterator itr = daemon_ad.begin();
itr != daemon_ad.end();
itr++ )
{
ExtArray<MyString> the_regex_groups;
if( re.match(itr->first.c_str(),&the_regex_groups) ) {
// make a new Metric for this attribute that matched the regex
counted_ptr<Metric> metric(statsd->newMetric());
metric->evaluateDaemonAd(metric_ad,daemon_ad,max_verbosity,statsd,&the_regex_groups,itr->first.c_str());
}
}
return false;
}
}
std::string aggregate_str;
if( !evaluateOptionalString(ATTR_AGGREGATE,aggregate_str,metric_ad,daemon_ad,regex_groups) ) return false;
aggregate = NO_AGGREGATE;
if( strcasecmp(aggregate_str.c_str(),"sum")==0 ) {
aggregate = SUM;
}
else if( strcasecmp(aggregate_str.c_str(),"avg")==0 ) {
aggregate = AVG;
}
else if( strcasecmp(aggregate_str.c_str(),"min")==0 ) {
aggregate = MIN;
}
else if( strcasecmp(aggregate_str.c_str(),"max")==0 ) {
aggregate = MAX;
}
else if( !aggregate_str.empty() ) {
EXCEPT("Invalid aggregate function %s",aggregate_str.c_str());
}
// set default stats grouping
if( isAggregateMetric() ) {
group = "HTCondor Pool";
}
//.........这里部分代码省略.........
示例10: RegexParagraphList
RegexParagraphList(const char *name, const char *regex, const char *listregex) :
RegexMatcher(name, regex),
regexListBreaker("List Breaker", listregex)
{
regexListBreaker.Compile();
}
示例11: processCommit
void Gource::processCommit(RCommit& commit, float t) {
//find user of this commit or create them
RUser* user = 0;
//see if user already exists but if not wait until
//we actually use one of their files before adding them
std::map<std::string, RUser*>::iterator seen_user = users.find(commit.username);
if(seen_user != users.end()) user = seen_user->second;
//check user against filters, if found, discard commit
if(user == 0 && !gGourceSettings.user_filters.empty()) {
for(std::vector<Regex*>::iterator ri = gGourceSettings.user_filters.begin(); ri != gGourceSettings.user_filters.end(); ri++) {
Regex* r = *ri;
if(r->match(commit.username)) {
return;
}
}
}
//find files of this commit or create it
for(std::list<RCommitFile>::iterator it = commit.files.begin(); it != commit.files.end(); it++) {
RCommitFile& cf = *it;
RFile* file = 0;
std::map<std::string, RFile*>::iterator seen_file = files.find(cf.filename);
if(seen_file != files.end()) file = seen_file->second;
if(file == 0) {
//if we already have max files in circulation
//we cant add any more
if(files.size() >= gGourceSettings.max_files)
continue;
//check filename against filters
if(!gGourceSettings.file_filters.empty()) {
bool filtered_filename = false;
for(std::vector<Regex*>::iterator ri = gGourceSettings.file_filters.begin(); ri != gGourceSettings.file_filters.end(); ri++) {
Regex* r = *ri;
if(r->match(cf.filename)) {
filtered_filename = true;
break;
}
}
if(filtered_filename) continue;
}
int tagid = tag_seq++;
file = new RFile(cf.filename, cf.colour, vec2f(0.0,0.0), tagid);
files[cf.filename] = file;
tagfilemap[tagid] = file;
root->addFile(file);
while(root->getParent() != 0) {
debugLog("parent changed to %s\n", root->getPath().c_str());
root = root->getParent();
}
}
//create user if havent yet. do it here to ensure at least one of there files
//was added (incase we hit gGourceSettings.max_files)
if(user == 0) {
vec2f pos;
if(dir_bounds.area() > 0) {
pos = dir_bounds.centre();
} else {
pos = vec2f(0,0);
}
int tagid = tag_seq++;
user = new RUser(commit.username, pos, tagid);
users[commit.username] = user;
tagusermap[tagid] = user;
if(gGourceSettings.highlight_all_users) {
user->setHighlighted(true);
} else {
// set the highlighted flag if name matches a highlighted user
for(std::vector<std::string>::iterator hi = gGourceSettings.highlight_users.begin(); hi != gGourceSettings.highlight_users.end(); hi++) {
std::string highlight = *hi;
if(highlight.size() && user->getName() == highlight) {
//.........这里部分代码省略.........
示例12: Regex
namespace libdnf {
static const Regex RELDEP_REGEX =
Regex("^(\\S*)\\s*(<=|>=|<|>|=)?\\s*(.*)$", REG_EXTENDED);
static bool
getCmpFlags(int *cmp_type, std::string matchCmpType)
{
int subexpr_len = matchCmpType.size();
auto match_start = matchCmpType.c_str();
if (subexpr_len == 2) {
if (strncmp(match_start, "<=", 2) == 0) {
*cmp_type |= HY_LT;
*cmp_type |= HY_EQ;
}
else if (strncmp(match_start, ">=", 2) == 0) {
*cmp_type |= HY_GT;
*cmp_type |= HY_EQ;
}
else
return false;
} else if (subexpr_len == 1) {
if (*match_start == '<')
*cmp_type |= HY_LT;
else if (*match_start == '>')
*cmp_type |= HY_GT;
else if (*match_start == '=')
*cmp_type |= HY_EQ;
else
return false;
} else
return false;
return true;
}
bool
DependencySplitter::parse(const char * reldepStr)
{
enum { NAME = 1, CMP_TYPE = 2, EVR = 3, _LAST_ };
auto matchResult = RELDEP_REGEX.match(reldepStr, false, _LAST_);
if (!matchResult.isMatched() || matchResult.getMatchedLen(NAME) == 0) {
return false;
}
name = matchResult.getMatchedString(NAME);
evr = matchResult.getMatchedString(EVR);
cmpType = 0;
int evrLen = matchResult.getMatchedLen(EVR);
int cmpTypeLen = matchResult.getMatchedLen(CMP_TYPE);
if (cmpTypeLen < 1) {
if (evrLen > 0) {
// name contains the space char, e.g. filename like "hello world.jpg"
evr.clear();
name = reldepStr;
}
return true;
}
if (evrLen < 1)
return false;
return getCmpFlags(&cmpType, matchResult.getMatchedString(CMP_TYPE));
}
}
示例13: setGourceDefaults
//.........这里部分代码省略.........
}
}
if((entry = gource_settings->getEntry("follow-user")) != 0) {
ConfEntryList* follow_user_entries = gource_settings->getEntries("follow-user");
for(ConfEntryList::iterator it = follow_user_entries->begin(); it != follow_user_entries->end(); it++) {
entry = *it;
if(!entry->hasValue()) conffile.entryException(entry, "specify follow-user (user)");
follow_users.push_back(entry->getString());
}
}
if(gource_settings->getBool("file-extensions")) {
file_extensions=true;
}
if((entry = gource_settings->getEntry("file-filter")) != 0) {
ConfEntryList* filters = gource_settings->getEntries("file-filter");
for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {
entry = *it;
if(!entry->hasValue()) conffile.entryException(entry, "specify file-filter (regex)");
std::string filter_string = entry->getString();
Regex* r = new Regex(filter_string, 1);
if(!r->isValid()) {
delete r;
conffile.entryException(entry, "invalid file-filter regular expression");
}
file_filters.push_back(r);
}
}
if((entry = gource_settings->getEntry("user-filter")) != 0) {
ConfEntryList* filters = gource_settings->getEntries("user-filter");
for(ConfEntryList::iterator it = filters->begin(); it != filters->end(); it++) {
entry = *it;
if(!entry->hasValue()) conffile.entryException(entry, "specify user-filter (regex)");
std::string filter_string = entry->getString();
Regex* r = new Regex(filter_string, 1);
if(!r->isValid()) {
delete r;
conffile.entryException(entry, "invalid user-filter regular expression");
}
user_filters.push_back(r);
}
}
示例14: to_string
void OpenLayersNode::AsHTML(HTMLOutputter &outputter)
{
static const char * str_width = "width";
static const char * str_height = "height";
static const char * str_px = "px";
attrs[string("mapnum")] = to_string(++mapNum);
set_default(attrs, str_width, to_string(640));
set_default(attrs, str_height, to_string(480));
if (debug) cout << "Outputing OpenLayers node " << mapNum << endl;
attrs[str_width] = attrs[str_width] + str_px;
attrs[str_height] = attrs[str_height] + str_px;
{
map<string, string> vars;
CopyMap(attrs, vars);
static const char *prefix =
"<div class=\"map\" id=\"map$mapnum\" style=\"width: $width; height: $height; direction: ltr;\"></div>"
"<script type=\"text/javascript\">\n"
"//<![CDATA[\n";
outputter.AddString(subst(prefix, vars));
outputter.AddString(subst(sections_preamble,vars));
}
bool markerlayer = false;
const char *buffer = text.data();
size_t bufferLength = text.length();
while (bufferLength && isspace(*buffer))
{
--bufferLength;
++buffer;
}
if (debug) cout << "Processing line (" << bufferLength << ") '" << string(buffer, bufferLength) << "'" << endl;
while (bufferLength)
{
RegexMatch match;
bool changed(false);
if (regex_kml.Match(buffer, bufferLength, match))
{
buffer += match.End(0); bufferLength -= match.End(0);
map<string, string> vars;
CopyMap(attrs, vars);
if (debug) cout << "Outputting kml URL '" << match.Match(2) << "'" << endl;
vars[string("kmlurl")] = match.Match(2);
outputter.AddString(subst(sections_KML, vars));
changed = true;
} else if (regex_gpstrack.Match(buffer, bufferLength, match)) {
buffer += match.End(0); bufferLength -= match.End(0);
map<string, string> vars;
CopyMap(attrs, vars);
vars[string("fromdate")] = match.Match(2);
vars[string("todate")] = match.Match(3);
vars[string("imgoffset")] = match.Match(4);
if (vars.find("imgoffset") == vars.end())
vars[string("imgoffset")] = string("14");
outputter.AddString(subst(sections_gpstracklayer, vars));
changed = true;
} else if (regex_dotkml.Match(buffer, bufferLength, match))
{
buffer += match.End(0); bufferLength -= match.End(0);
map<string, string> vars;
CopyMap(attrs, vars);
vars[string("kmlurl")] = match.Match(1);
outputter.AddString(subst(sections_KML, vars));
changed = true;
} else if (regex_gpx.Match(buffer, bufferLength, match))
{
buffer += match.End(0); bufferLength -= match.End(0);
map<string, string> vars;
CopyMap(attrs, vars);
vars[string("gpxurl")] = match.Match(2);
vars[string("gpxtitle")] = match.Match(3);
outputter.AddString(subst(sections_GPX, vars));
changed = true;
} else if (regex_dotgpx.Match(buffer, bufferLength, match))
{
buffer += match.End(0); bufferLength -= match.End(0);
map<string, string> vars;
CopyMap(attrs, vars);
vars[string("gpxurl")] = match.Match(1);
outputter.AddString(subst(sections_GPX, vars));
changed = true;
//.........这里部分代码省略.........
示例15: parseCommit
//parse apache access.log entry into components
bool ApacheCombinedLog::parseCommit(RCommit& commit) {
std::string line;
std::vector<std::string> matches;
if(!logf->getNextLine(line)) return false;
apache_entry_start.match(line, &matches);
if(matches.size()!=4) {
return 0;
}
//get details
commit.username = matches[0];
//std::string user = matches[1];
//parse timestamp
struct tm time_str;
std::string request_str = matches[3];
std::string datestr = matches[2];
apache_entry_date.match(datestr, &matches);
if(matches.size()!=8) {
return 0;
}
int day = atoi(matches[0].c_str());
int year = atoi(matches[2].c_str());
int hour = atoi(matches[3].c_str());
int minute = atoi(matches[4].c_str());
int second = atoi(matches[5].c_str());
// int zone = atoi(matches[7].c_str());
//negative timezone
// if(strcmp(matches[6].c_str(), "-")==0) {
// zone = -zone;
// }
int month=0;
for(int i=0;i<12;i++) {
if(matches[1] == months[i]) {
month=i;
break;
}
}
time_str.tm_year = year - 1900;
time_str.tm_mon = month;
time_str.tm_mday = day;
time_str.tm_hour = hour;
time_str.tm_min = minute;
time_str.tm_sec = second;
time_str.tm_isdst = -1;
commit.timestamp = mktime(&time_str);
matches.clear();
apache_entry_request.match(request_str, &matches);
if(matches.size() < 5) {
return false;
}
std::string rtype = matches[0];
std::string file = matches[1];
std::string proto = matches[2];
int code = atoi(matches[3].c_str());
int bytes = atol(matches[4].c_str());
//remove args from url
int argpos = file.rfind("?");
if(argpos != std::string::npos) {
file = file.substr(0,argpos);
}
if(file.size()==0) file = "/";
//name index pages
if(file[file.size()-1] == '/') {
file += "index.html";
}
std::string action = "A";
commit.addFile(file, action);
std::string refer;
std::string agent;
if(matches.size() > 5) {
std::string agentstr = matches[5];
matches.clear();
apache_entry_agent.match(agentstr, &matches);
if(matches.size()>1) {
//.........这里部分代码省略.........