Example #1
0
// Return true if first goes before second
bool compareNames( string first, string second) {
  if ( first.compare(second) < 0)
    return true;
  else
    return false;
}
Example #2
0
/**
 * parse characters in the current line to determine if an indent
 * or unindent is needed.
 */
void ASEnhancer::parseCurrentLine(string &line, bool isInPreprocessor, bool isInSQL)
{
	bool isSpecialChar = false;			// is a backslash escape character

	for (size_t i = 0; i < line.length(); i++)
	{
		char ch = line[i];

		// bypass whitespace
		if (isWhiteSpace(ch))
			continue;

		// handle special characters (i.e. backslash+character such as \n, \t, ...)
		if (isSpecialChar)
		{
			isSpecialChar = false;
			continue;
		}
		if (!(isInComment) && line.compare(i, 2, "\\\\") == 0)
		{
			i++;
			continue;
		}
		if (!(isInComment) && ch == '\\')
		{
			isSpecialChar = true;
			continue;
		}

		// handle quotes (such as 'x' and "Hello Dolly")
		if (!isInComment && (ch == '"' || ch == '\''))
		{
			if (!isInQuote)
			{
				quoteChar = ch;
				isInQuote = true;
			}
			else if (quoteChar == ch)
			{
				isInQuote = false;
				continue;
			}
		}

		if (isInQuote)
			continue;

		// handle comments

		if (!(isInComment) && line.compare(i, 2, "//") == 0)
		{
			// check for windows line markers
			if (line.compare(i + 2, 1, "\xf0") > 0)
				lineNumber--;
			// unindent if not in case brackets
			if (line.find_first_not_of(" \t") == i
			        && sw.switchBracketCount == 1
			        && sw.unindentCase)
				shouldUnindentComment = true;
			break;                 // finished with the line
		}
		else if (!(isInComment) && line.compare(i, 2, "/*") == 0)
		{
			// unindent if not in case brackets
			if (sw.switchBracketCount == 1 && sw.unindentCase)
				shouldUnindentComment = true;
			isInComment = true;
			size_t commentEnd = line.find("*/", i);
			if (commentEnd == string::npos)
				i = line.length() - 1;
			else
				i = commentEnd - 1;
			continue;
		}
		else if ((isInComment) && line.compare(i, 2, "*/") == 0)
		{
			// unindent if not in case brackets
			if (sw.switchBracketCount == 1 && sw.unindentCase)
				shouldUnindentComment = true;
			isInComment = false;
			i++;
			continue;
		}

		if (isInComment)
		{
			// unindent if not in case brackets
			if (sw.switchBracketCount == 1 && sw.unindentCase)
				shouldUnindentComment = true;
			size_t commentEnd = line.find("*/", i);
			if (commentEnd == string::npos)
				i = line.length() - 1;
			else
				i = commentEnd - 1;
			continue;
		}

		// if we have reached this far then we are NOT in a comment or string of special characters

		if (line[i] == '{')
			bracketCount++;

		if (line[i] == '}')
			bracketCount--;

		bool isPotentialKeyword = isCharPotentialHeader(line, i);

		// ----------------  wxWidgets and MFC macros  ----------------------------------

		if (isPotentialKeyword)
		{
			if (findKeyword(line, i, "BEGIN_EVENT_TABLE")
			        || findKeyword(line, i, "BEGIN_DISPATCH_MAP")
			        || findKeyword(line, i, "BEGIN_EVENT_MAP")
			        || findKeyword(line, i, "BEGIN_MESSAGE_MAP")
			        || findKeyword(line, i, "BEGIN_PROPPAGEIDS"))
			{
				nextLineIsEventIndent = true;
				break;
			}
			if (findKeyword(line, i, "END_EVENT_TABLE")
			        || findKeyword(line, i, "END_DISPATCH_MAP")
			        || findKeyword(line, i, "END_EVENT_MAP")
			        || findKeyword(line, i, "END_MESSAGE_MAP")
			        || findKeyword(line, i, "END_PROPPAGEIDS"))
			{
				isInEventTable = false;
				break;
			}
		}

		// ----------------  process SQL  -----------------------------------------------

		if (isInSQL)
		{
			if (isBeginDeclareSectionSQL(line, i))
				nextLineIsDeclareIndent = true;
			if (isEndDeclareSectionSQL(line, i))
				isInDeclareSection = false;
			break;
		}

		// ----------------  process switch statements  ---------------------------------

		if (isPotentialKeyword && findKeyword(line, i, "switch"))
		{
			switchDepth++;
			switchStack.push_back(sw);                      // save current variables
			sw.switchBracketCount = 0;
			sw.unindentCase = false;                        // don't clear case until end of switch
			i += 5;                                         // bypass switch statement
			continue;
		}

		// just want unindented case statements from this point

		if (caseIndent
		        || switchDepth == 0
		        || (isInPreprocessor && !preprocessorIndent))
		{
			// bypass the entire word
			if (isPotentialKeyword)
			{
				string name = getCurrentWord(line, i);
				i += name.length() - 1;
			}
			continue;
		}

		i = processSwitchBlock(line, i);

	}   // end of for loop * end of for loop * end of for loop * end of for loop
}
bool startsWith(const string& base, const string& key) {
  return base.compare(0, key.size(), key) == 0;
}
Example #4
0
void AtomTypes::AddSymbol(string typeName)
{
    string symbol = typeName.substr(0, 2);

    if(typeName.compare("AndLink")==0)
        symbol="∧";
    if(typeName.compare("OrLink")==0)
        symbol="∨";
    if(typeName.compare("NotLink")==0)
        symbol="¬";
    if(typeName.compare("FalseLink")==0)
        symbol=".F.";
    if(typeName.compare("TrueLink")==0)
        symbol=".T.";
    if(typeName.compare("SetLink")==0)
        symbol="{}";
    if(typeName.compare("MemberLink")==0)
        symbol="∈";
    if(typeName.compare("SubsetLink")==0)
        symbol="⊂";
    if(typeName.compare("ListLink")==0)
        symbol="()";
    if(typeName.compare("ForallLink")==0)
        symbol="∀";
    if(typeName.compare("ExistsLink")==0)
        symbol="∃";
    if(typeName.compare("VariableTypeNode")==0)
        symbol="VT";
    if(typeName.compare("ImplicationLink")==0)
        symbol="⇒";
    if(typeName.compare("EvaluationLink")==0)
        symbol="=";
    if(typeName.compare("InheritanceLink")==0)
        symbol="is";

    atomTypeSymbols.push_back(symbol);
}
FastStixelWorldEstimator::FastStixelWorldEstimator(
        const boost::program_options::variables_map &options,
        const AbstractVideoInput::dimensions_t &input_dimensions_,
        const MetricStereoCamera &camera_,
        const GroundPlane &ground_plane_prior_)
    :
      input_dimensions(input_dimensions_),
      camera(camera_),
      camera_calibration(camera_.get_calibration()),
      ground_plane_prior(ground_plane_prior_),
      expected_object_height(get_option_value<float>(options, "stixel_world.expected_object_height")),
      minimum_object_height_in_pixels(get_option_value<int>(options, "stixel_world.minimum_object_height_in_pixels"))
{

    silent_mode = true;
    if(options.count("silent_mode"))
    {
        silent_mode = get_option_value<bool>(options, "silent_mode");
    }

    ground_plane_estimator_p.reset(new FastGroundPlaneEstimator(
                                       options, camera.get_calibration()));

    {
        // estimate prior ground horizon estimate ---
        const float far_far_away = 1E3; // [meters]
        const float x = 0, height = 0; // [meters]
        const Eigen::Vector2f uv_point =
                camera.get_left_camera().project_ground_plane_point(ground_plane_prior, x, far_far_away, height);
        const int horizon_row = std::min<int>(std::max(0.0f, uv_point[1]), input_dimensions.y - 1);
        const std::vector<int> ground_object_boundary_prior(input_dimensions.x, horizon_row);

        ground_plane_estimator_p->set_ground_area_prior(ground_object_boundary_prior);
    }

    const int stixel_width = get_option_value<int>(options, "stixel_world.stixel_width");
    if(stixel_width < 1)
    {
        throw std::runtime_error("stixel_world.stixels_width must be >= 1 pixels");
    }

    const string method = get_option_value<string>(options, "stixel_world.method");

    if(method.compare("fast") == 0)
    {
        const string height_method =
                get_option_value<string>(options, "stixel_world.height_method");

        if(height_method.empty() or height_method.compare("fixed") == 0)
        {
            stixels_estimator_p.reset(new FastStixelsEstimator(options,
                                                               camera,
                                                               expected_object_height,
                                                               minimum_object_height_in_pixels,
                                                               stixel_width));
        }
        else if(height_method.compare("3d_cost") == 0)
        {
            throw std::invalid_argument("FastStixelWorldEstimator does not support stixel_world.height_method == '3d_cost'");
        }
        else if(height_method.compare("two_steps") == 0)
        {

            stixels_estimator_p.reset(new FastStixelsEstimatorWithHeightEstimation(options,
                                                                                   camera,
                                                                                   expected_object_height,
                                                                                   minimum_object_height_in_pixels,
                                                                                   stixel_width));
        }
        else
        {
            log_error() << "Received unknown stixel_world.height_method value: " << height_method << std::endl;
            throw std::invalid_argument("FastStixelWorldEstimator::FastStixelWorldEstimator received a unknown "
                                        "'stixel_world.height_method' value");
        }

    }
    else if (method.compare("fast_uv") == 0)
    {
        stixels_estimator_p.reset(new ImagePlaneStixelsEstimator(options,
                                                                 camera,
                                                                 expected_object_height,
                                                                 minimum_object_height_in_pixels,
                                                                 stixel_width));
    }
    else
    {
        log_error() << "Received unknown stixel_world.method value: " << method << std::endl;
        throw std::invalid_argument("FastStixelWorldEstimator::FastStixelWorldEstimator received a unknown "
                                    "'stixel_world.method' value");
    }

    return;
}
Example #6
0
bool get_bool(string s)
{
    if(!s.compare("true"))
        return true;
    else return false;
}
/* 
* author: tory
* date: 2012.12.29
* describe:领取邮件中的物品
*/
bool MailSysterm::mail_goods_receive(Hero* myHero, string mail_id)
{
	if(myHero == NULL)	return false;
	map<string, Mail_Infor*>::iterator iter = mail_Inbox.find(mail_id);
	if(iter == mail_Inbox.end())	return false;	
		
	Mail_Infor* m_i = iter->second;
	if(m_i == NULL)	return false;
			
	Mail_Txt* m_t = (Mail_Txt*)m_i->data;		//tory modify 2012.12.29
	
	if(mail_id.compare(m_i->identity) != 0)
	{
		cout<<"mail_goods_receivep:the mail id is not same"<<endl;
		return false;
	}

	int all_number = m_t->good1_num + m_t->good2_num + m_t->good3_num + m_t->good4_num;
	
	//jolly add 1.25  for bagfull
	int count=0;
	if (m_t->good1_num!=0)
	{
		count++;
	}
	if (m_t->good2_num!=0)
	{
		count++;
	}
	if (m_t->good3_num!=0)
	{
		count++;
	}
	if (m_t->good4_num!=0)
	{
		count++;
	}
	
	if(myHero->getBag()->bagIsFull(count))
	{//背包内格子数不够
		cout<<"mail_goods_receivep:the bag is not null"<<endl;
		return false;
	} 
	
	//将物品将在到背包内
	if(m_t->good1_num > 0)
	{
		saveGoodsInBag(myHero, m_t->good1_id, m_t->good1_num);	
		strncpy(m_t->good1_id, "0", 15);
		m_t->good1_num = 0;
	}
	if(m_t->good2_num > 0)
	{
		saveGoodsInBag(myHero, m_t->good2_id, m_t->good2_num);	
		strncpy(m_t->good2_id, "0", 15);
		m_t->good2_num = 0;
	}
	if(m_t->good3_num > 0)
	{
		saveGoodsInBag(myHero, m_t->good3_id, m_t->good3_num);	
		strncpy(m_t->good3_id, "0", 15);
		m_t->good3_num = 0;
	}
	if(m_t->good4_num > 0)
	{
		saveGoodsInBag(myHero, m_t->good4_id, m_t->good4_num);	
		strncpy(m_t->good4_id, "0", 15);
		m_t->good4_num = 0;
	}	
	
	//将游戏币与非绑定元宝加载到背包内
	increaseGameMoney(myHero, m_t->money);
	m_t->money = 0;
	
	increaseGold(myHero, m_t->gamegold);	
	m_t->gamegold = 0;
	
	int index = 0;
	memset(g_out_buf, 0, 20480);	
	sprintf(g_out_buf, "17,6,1,%d,%s", index, mail_id.c_str());
	cout<<"@@Tory, mail_goods_receive:"<<g_out_buf<<endl;
	send_msg(myHero->getFd(), g_out_buf);
}
Example #8
0
int operator >  (const string & left, const string & right)
{ return left.compare(right) > 0; }
Example #9
0
double KMLP::learningWeights(string outputAction, double currentQ, double prevQ, double reward)
{
    static int cnt = 0;
    // Modified Connectionist Q-Learning by G. Rummery.(1994)
    Qt = currentQ;
    Qt_1 = prevQ;
    r = reward;
    selectedAction = outputAction;


    // calculate gradient and eligibility trace update
    double grad, gradP;
    if(outputAction.compare(m_name) == 0){  // equal
        // weight update
        if(cnt>0){
            double td = eta*(r+gamma*Qt-Qt_1);
            for(int i=0;i<m_nInput;i++)
                for(int j=0;j<m_nHidden;j++){
                    if(r<0)
                        int a=2;
                    m_hiddenW[i][j] += td*m_hiddenE[i][j];
                }
            for(int i=0;i<m_nHidden;i++)
                for(int j=0;j<m_nOutput;j++)
                    m_outputW[i][j] += td*m_outputE[i][j];
        }


        for(int i=0;i<m_nHidden;i++){
            gradP = sigmoidInv(m_netO[0])*m_nvHidden[i];
            m_outputE[i][0] = gradP + gamma*lamda*m_outputE[i][0];
            for(int j=0;j<m_nInput;j++){
                grad = sigmoidInv(m_netO[0])*m_outputW[i][0]*sigmoidInv(m_netH[i])*m_nvInput[j];
                m_hiddenE[j][i] = grad + gamma*lamda*m_hiddenE[j][i];
            }
        }
    }

    else {
        for(int i=0;i<m_nInput;i++)
            for(int j=0;j<m_nHidden;j++)
                m_hiddenE[i][j] = gamma*lamda*m_hiddenE[i][j];
        for(int i=0;i<m_nHidden;i++)
            for(int j=0;j<m_nOutput;j++)
                m_outputE[i][j] = gamma*lamda*m_outputE[i][j];;
    }

    // calculate sum of weight changes
    weightChange = 0;
    if(cnt > 0){
        for(int i=0;i<m_nInput;i++)
            for(int j=0;j<m_nHidden;j++)
                weightChange += (m_hiddenWP[i][j] - m_hiddenW[i][j])*(m_hiddenWP[i][j] - m_hiddenW[i][j]);
        for(int i=0;i<m_nHidden;i++)
            weightChange += (m_outputWP[i][0] - m_outputW[i][0]) * (m_outputWP[i][0] - m_outputW[i][0]);
    }

    // store to the previous weights
    for(int i=0;i<m_nInput;i++)
        for(int j=0;j<m_nHidden;j++)
            m_hiddenWP[i][j] = m_hiddenW[i][j];
    for(int i=0;i<m_nHidden;i++)
        m_outputWP[i][0] = m_outputW[i][0];

    cnt ++;

    return weightChange;
}
Example #10
0
    void run(std::istream& in)
    {
        vector<string> tokens;
        string line;


        while(getline(in,line,'\n'))
        {
            if(AbstractApplication::stopping()) break;
            if(line.empty()) continue;
            if(line[0]=='#')
            {
                if(line.size()>1 && line[1]=='#')
                {
                    cout << line << endl;
                    continue;
                }
                cout << line << tokenizer.delim
                     << "uniprot.beg"  << tokenizer.delim
                     << "uniprot.end"  << tokenizer.delim
                     << "uniprot.type"  << tokenizer.delim
                     << "uniprot.status"  << tokenizer.delim
                     << "uniprot.desc"  << tokenizer.delim
                     << "uniprot.evidence"  << tokenizer.delim
                     << "uniprot.ref"
                     << endl;
                continue;
            }

            tokenizer.split(line,tokens);
            if(column_aa_pos>=(int)tokens.size())
            {
                cerr << "Out of range for COLUMN_AA in " << line << endl;
                continue;
            }
            if(column_spId>=(int)tokens.size())
            {
                cerr << "Out of range for SWISSPROT-ID in " << line << endl;
                continue;
            }


            string swissprotId=tokens[column_spId];
            if(swissprotId.empty() || swissprotId.compare(".")==0)
            {
                cout << line;
                for(int i=0; i< 7; ++i) cout << tokenizer.delim << ".";
                cout << endl;
                continue;
            }
            char* p2;
            int posAA= (int)strtol(tokens[column_aa_pos].c_str(),&p2,10);
            if(*p2!=0 || posAA<1)
            {
                cerr << "Bad Column-aa in " << line << endl;
                continue;
            }
            if(!(current_recordid.compare(swissprotId)==0 && record!=NULL))
            {
                if(record!=NULL) ::xmlFreeDoc(record);
                record=NULL;

                ostringstream urlos;
                urlos << "http://www.uniprot.org/uniprot/" << swissprotId << ".xml";
                string url(urlos.str());
                netstreambuf in;
                in.open(url.c_str());
                string xml=in.content();
                in.close();
                int options=XML_PARSE_NOERROR|XML_PARSE_NONET;
                record=xmlReadMemory(xml.c_str(),xml.size(),
                                     url.c_str(),
                                     NULL,
                                     options);
                if(record==NULL)
                {
                    cerr << "#warning: Cannot find record for "<< swissprotId << endl;
                    cout << line ;
                    for(int i=0; i< 7; ++i) cout << tokenizer.delim << ".";
                    cout << endl;
                    continue;
                }
                current_recordid.assign(swissprotId);
            }
            bool found=false;
            xmlNodePtr uniprot=xmlDocGetRootElement(record);
            xmlNodePtr entry=first(uniprot,"entry");
            if(entry!=NULL)
            {
                for(xmlNodePtr feature = entry->children; feature!=NULL; feature = feature->next)
                {
                    if (feature->type != XML_ELEMENT_NODE) continue;
                    if(!::xmlStrEqual(feature->name,BAD_CAST "feature"))
                    {
                        continue;
                    }
                    bool match=false;
                    xmlNodePtr location=first(feature,"location");
                    if(location==NULL) continue;

                    int featBeg;
                    int featEnd;
                    xmlNodePtr locpos=first(location,"position");
                    if(locpos!=NULL)
                    {
                        featBeg=parseAttInt(locpos,"position");
                        featEnd=featBeg;
                        if(featBeg==posAA) match=true;
                    }
                    else
                    {
                        xmlNodePtr locbegin=first(location,"begin");
                        xmlNodePtr locend=first(location,"end");
                        if(locbegin!=NULL && locend!=NULL)
                        {
                            featBeg=parseAttInt(locbegin,"position");
                            featEnd=parseAttInt(locend,"position");
                            if(featBeg<=featEnd && featBeg<=posAA && posAA<=featEnd)
                            {
                                match=true;
                            }
                        }
                    }
                    if(!match) continue;
                    cout << line << tokenizer.delim
                         << featBeg  << tokenizer.delim
                         << featEnd  << tokenizer.delim
                         << parseAttStr(feature,"type")  << tokenizer.delim
                         << parseAttStr(feature,"status")  << tokenizer.delim
                         << parseAttStr(feature,"description")  << tokenizer.delim
                         << parseAttStr(feature,"evidence")  << tokenizer.delim
                         << parseAttStr(feature,"ref")
                         << endl
                         ;

                    found=true;
                }
            }
            if(!found)
            {
                cout << line;
                for(int i=0; i< 7; ++i) cout << tokenizer.delim << ".";
                cout << endl;
            }
        }
    }
Example #11
0
int operator == (const string & left, const string & right)
{ return left.compare(right) == 0; }
bool endWith(const string str,const string needle) {
  if (str.length() >= needle.length()) {
    return (0 == str.compare (str.length() - needle.length(), needle.length(), needle));
  }
  return false;
}
bool beginWith(const string str,const string needle) {
  return (!str.compare(0,needle.length(),needle));
}
Example #14
0
/*
**Insert node in the binary tree whose root is root. The innsertion is made 
to create an AVL binary tree.
**Returns 1 if the word was inserted or 0 if the word already existed.
*/
int insert_word(AVL_Node *&root, string word, string translation) {
    if(root == NULL) {
        root = new_node(word, translation, NULL);
        return 1;
    }

    AVL_Node *aux = root;

    while(1) {
        int comparison = word.compare(aux->word);
        if(comparison < 0) {
            if(aux->son_left == NULL) {
                //insert new node to the left of the subtree
                aux->son_left = new_node(word, translation, aux);
                break;
            }
            aux = aux->son_left;
        }
        else if(comparison > 0) {
            if(aux->son_right == NULL) {
                //insert new node to the right of the subtree
                aux->son_right = new_node(word, translation, aux); 
                break;
            }
            aux = aux->son_right;
        }
        else {
            //There's a node with that word
            return 0;
        }
    }

    //Go up the tree and correct the heights. If the height is changed then check
    //if rebalance is needed. Notice that aux begins in the parent of the new node
    while(aux != NULL) {
        update_height(aux);
        int balance = get_balance(aux);
        if(balance == 2) {
            if(get_balance(aux->son_right) == -1) {
                rotate_right(aux->son_right);//Double rotation
            }
            rotate_left(aux);
            if(aux == root) {
                //Updates the root of the tree if it shifts
                root = aux->parent;
            }
        }
        else if(balance == -2) {
            if(get_balance(aux->son_left) == 1) {
                rotate_left(aux->son_left);//Double rotation
            }
            rotate_right(aux);
            if(aux == root) {
                //Updates the root of the tree if it shifts
                root = aux->parent;
            }
        }
        aux = aux->parent;
    }
    return 1;
}
/**
 * Executes the refinement analysis
 *
 * \param OutputFilePrefix If different of empty string, it indicates that
 *        every step should be printed
 *
 * \return True if the refinement worked properly, false otherwise
 *
 */
bool ClusteringRefinementDivisive::Run(const vector<CPUBurst*>& Bursts,
                                       vector<Partition>&       IntermediatePartitions,
                                       Partition&               LastPartition,
                                       bool                     PrintStepsInformation,
                                       string                   OutputFilePrefix)
{
  bool           Stop = false;

  ostringstream  Messages;

  this->OutputFilePrefix = OutputFilePrefix;

  if (OutputFilePrefix.compare("") == 0)
  {
    PrintStepsInformation = false;
  }
  else
  {
    PrintStepsInformation = true;
  }

  if (Bursts.size() == 0)
  {
    SetErrorMessage("no bursts no analyze");
    return false;
  }

  if (Steps <= 1)
  {
    SetErrorMessage("number of steps in a refinement should be higher than 1");
    return false;
  }

  for (size_t i = 0; i < Bursts.size(); i++)
  {
    Instance2Burst[Bursts[i]->GetInstance()] = i;
  }

  IntermediatePartitions.clear();
  IntermediatePartitions.push_back(Partition());

  StatisticsHistory.clear();
  StatisticsHistory.push_back(ClusteringStatistics());

  NodesPerLevel.clear();
  NodesPerLevel.push_back(vector<ClusterInformation*>(0));

  ClusteringCore = new libClustering();

  Messages << "*** TOTAL NUMBER OF BURSTS = " << Bursts.size() << " ***" << endl;
  Messages << "*** STEP 1 (Eps = " << EpsilonPerLevel[0] << ") ***" << endl;
  system_messages::information(Messages.str());
  if (!RunFirstStep(Bursts, IntermediatePartitions[0]))
  {
    return false;
  }

  /* On step 0, all new nodes are part of the hierarchy */
  map<cluster_id_t, ClusterInformation*>::iterator NewNodesIt;

  LastStep = 0;

  /* Iterate through the epsilon values, and generate the clusters hierarchy */
  for (size_t CurrentStep = 1;
              CurrentStep < Steps && !Stop;
              CurrentStep++)
  {
    Messages.str("");

    Messages << "****** STEP " << (CurrentStep+1) << " (Eps = " << EpsilonPerLevel[CurrentStep];;
    Messages << ") ******" << endl;
    system_messages::information(Messages.str());

    IntermediatePartitions.push_back(Partition());
    StatisticsHistory.push_back(ClusteringStatistics());
    NodesPerLevel.push_back(vector<ClusterInformation*>(0));

    Stop = true;
    if (!RunStep(CurrentStep,
                 Bursts,
                 IntermediatePartitions[CurrentStep-1],
                 IntermediatePartitions[CurrentStep],
                 Stop))
    {
      return false;
    }

    if (!Stop)
    {
      LastStep++;
    }
    else
    {
      Messages.str("");
      Messages << "****** CONVERGENCE ******" << endl;
      system_messages::information(Messages.str());
    }
  }

  /* Prune non-expanded nodes and reclassify noise points at the leaves */
  Messages.str("");
  Messages << "****** PRUNING TREE ******" << endl;
  system_messages::information(Messages.str());

  for (size_t i = 0; i < NodesPerLevel[0].size(); i++)
  {
    if (NodesPerLevel[0][i]->GetID() != NOISE_CLUSTERID)
    {
      ColapseNonDividedSubtrees(NodesPerLevel[0][i]);
      ReclassifyNoise (Bursts, NodesPerLevel[0][i], 0);
    }
  }

  /* Generate last partition */
  GeneratePartition(LastPartition);

  /* DEBUG
  cout << "Last Partition has " << LastPartition.NumberOfClusters() << " clusters" << endl; */

  if (PrintStepsInformation)
  {
    Messages.str("");
    Messages << "|-> Printing las trees" << endl;
    system_messages::information(Messages.str());

    if (!PrintTrees(LastStep, true)) /* Last tree */
    {
      return false;
    }
  }

  return true;
}
Example #16
0
void colorSelect(string color){
	if (color.compare("red") == 0)
		glColor3f(1,0,0);
	else if (color.compare("green") == 0)
		glColor3f(0,1,0);
	else if (color.compare("blue") == 0)
		glColor3f(0,0,1);
	else if (color.compare("yellow") == 0)
		glColor3f(1,1,0);
	else if (color.compare("yellow1") == 0)
		glColor3f(0.918,0.835,0.078);
	else if (color.compare("yellow2") == 0)
		glColor3f(0.659,0.592,0.212);
	else if (color.compare("grey") == 0)
		glColor3f(0.72,0.72,0.67);
	else if (color.compare("orange") == 0)
		glColor3f(1,0.5,0);
	else if (color.compare("purple") == 0)
		glColor3f(1,0,1);
	else if (color.compare("white") == 0)
		glColor3f(1,1,1);
	else if (color.compare("black") == 0) 
		glColor3f(0,0,0);
	else if (color.compare("skin") == 0)
		glColor3f(1,0.84,0.76);
	else if (color.compare("brown") == 0)
		glColor3f(0.55,0.27,0.07);
	else
		glColor3f(1,0,0);
}
Example #17
0
bool compare(string a,string b)
{
     if(a.length()>b.length())return true;
     if(a.length()==b.length() && a.compare(b)<=0)return true;
     return false;
}
Example #18
0
string menu(string phrase1, string phrase2, char op){
	stringstream phraseConc;
	switch(op){
		case 'A': case 'a':
			phraseConc << phrase1;
			break;
		case 'B': case 'b':
			phraseConc << "Frase1: " << phrase1.size() << " Frase2: " << phrase2.size();
			break;
		case 'C': case 'c':
			if(phrase1.compare(phrase2)){
				phraseConc << "As frases são diferentes";
			} else {
				phraseConc << "As frases são iguais";
			}
			break;
		case 'D': case 'd':
			phraseConc << phrase1 << phrase2;
			break;
		case 'E': case 'e':{
			stringstream conc;
			string concString;
			char character;
			conc << phrase1 << phrase2;
			concString = conc.str();
			cin >> character;
			int times = 0;
			for(int i = 0; i<concString.length(); i++){
				if(concString[i] == character){
					times++;
				}
			}
			phraseConc << times;
		}
			break;
		case 'F': case 'f':{
			stringstream conc;
			string concString;
			char character;
			conc << phrase1 << phrase2;
			concString = conc.str();
			cin >> character;
			for(int i = 0; i<concString.length(); i++){
				if(concString[i] == character){
					for(int place = i; place<concString.length(); place++){
						concString[i] = concString[i+1];
					}
				}
			}
			phraseConc << concString;
		}
			break;
		case 'G': case 'g':{
			stringstream conc;
			string concString;
			char character;
			char characterSub;
			conc << phrase1 << phrase2;
			concString = conc.str();
			cin >> character;
			cin >> characterSub;
			for(int i = 0; i<concString.length(); i++){
				if(concString[i] == character){
					concString[i] = characterSub;
				}
			}
			phraseConc << concString;
		}
			break;
		default:
			break;
	}
 return phraseConc.str();
}
Example #19
0
int RateMatrix::FindModel(
						  string& theModel
						 ) 
{
	int model = -1;

	trim(theModel);

	for(size_t i = 0; i < 3; i++) 
		theModel.at(i) = toupper(theModel.at(i));
	if (theModel.compare("TRN") == 0) theModel.assign("TN93");
	if (theModel.compare("TRNeq") == 0) theModel.assign("TN93eq");
	if (theModel.compare("K2P") == 0) theModel.assign("K80");
	if (theModel.compare("K3P") == 0) theModel.assign("K81");
	if (theModel.compare("K3Pne") == 0) theModel.assign("K81ne");
	for(int i = JC69; i<numModels; i++) {
		if(theModel.compare(modelNames[i]) == 0) {
			model = i;
			if (model <= GTR) {
				if(isNucModel == -1) {
					isNucModel = 1;
					numStates = NUM_NUC;
				} else {
					if(!isNucModel) {
						cerr << "Substitution model " << modelNames[model] << " is a nucleotide model, but simulation run is for amino acids." << endl;
						exit(EXIT_FAILURE);							
					}
				}
			} else {
				if(isNucModel == -1) {
					isNucModel = 0;
					numStates = NUM_AA;
				} else {
					if(isNucModel) {
						cerr << "Substitution model " << modelNames[model] << " is an amino acid model, but simulation run is for nucleotides." << endl;
						exit(EXIT_FAILURE);
					}
				}
			}
		} else if (theModel.compare(0,3,"REV",0,3)==0) {
			if(isNucModel == -1) {
				isNucModel = 1;
				numStates = NUM_NUC;
			} else {
				if(!isNucModel) {
					
				}
			}
			model = GTR;
		}
	}
	if(model == -1) {
		cerr << "Unknown model: " << theModel << endl << endl;
		exit(EXIT_FAILURE);
	}

	numStates_squared = numStates * numStates;
	numStates_cubed = numStates_squared * numStates;

	return model;
}
Example #20
0
void mk_sigaccjecupdown(string flavor = "112",  const string uncert = "jec")
{
    // gStyle->SetOptFit(1100); // chi2 and prob, not parameters
    // gStyle->SetOptFit(1); // chi2 and prob, not parameters
    // gStyle->SetOptStat("irme"); // integral, RMS, mean, # of entries
    // gStyle->SetStatFontSize(0.005);
    // gStyle->SetStatY(0.4);
    TLatex *   tex = new TLatex(0.678392,0.9283217,"CMS Preliminary 9.95 fb^{-1} at #sqrt{s}  =  8 TeV");
    tex->SetNDC();
    tex->SetTextAlign(22);
    tex->SetTextFont(42);
    // tex->SetTextSize(0.03846154);
    tex->SetLineWidth(2);
    cout<<"blabl"<<endl;
    // for(int k=0; k<3; k++){
    // for(int k=0; k<2; k++){
    for(int k=2; k<3; k++) {
        //Which plots to make
        //define input variables
        vector <string > namelist;
        vector <string > VarList;
        vector <TFile* > data;
        vector <TFile* > filelist;
        vector <TFile* > filelist_btag;
        vector <TFile* > filelist_2D;
        vector <TFile* > filelist_kin;
        vector <TFile* > filelist_param;
        vector <TFile* > filelist_diag;
        vector <TFile* > filelist_stealth;
        vector <TFile* > filelist0b;
        vector <float > EvtGen;
        vector <float > Xsec;
        vector <float > GlunioMass;

        vector<float> nEvtTot;
        vector<float> McXsec;
        vector<float> lumis;
        vector<float> DataLumi;
        vector<float> GaussMeanIni;
        vector<float> LeftEdge;
        vector<float> RightEdge;
        vector<vector<float  > > MassBins;

        // string uncert="btagup";
        // if(k==1) uncert="btagdown";
        // if(k==1) uncert="down";
        // if(k==2) uncert="";

        namelist.push_back("KinematicOptimization");
        // filelist_kin.push_back(TFile::Open(("Acc_Gluino_NoLumi_pt110_8TeVxsec_BtagMap_2500GeV"+uncert+".root").c_str()));
        // filelist_kin.push_back(TFile::Open("Acc_Gluino_NoLumi_pt60_pt110_8TeVxsec_BtagMap.root"));
        // filelist_kin.push_back(TFile::Open(("Acc_RPV112" + uncert + ".root").c_str()));
        filelist_kin.push_back(TFile::Open(("Acc_RPV" + flavor + "_Sph4.root").c_str()));
        filelist_kin.push_back(TFile::Open(("Acc_RPV" + flavor + uncert +  "up_Sph4.root").c_str()));
        filelist_kin.push_back(TFile::Open(("Acc_RPV" + flavor + uncert +  "down_Sph4.root").c_str()));
//   filelist_kin.push_back(TFile::Open(("Acc_Gluino_NoLumi_pt60_pt110_8TeVxsec_BtagMap" + uncert + ".root").c_str()));

        TFile f1(("RPV_" + flavor + "_accandwdith"+uncert+".root").c_str(), "recreate");
        f1.cd();

        string nameIN;
        string cuts;
        string prefix;
        string postfix;
        string folder;
        string ptcut;
        folder="plots/";
        postfix=".pdf";
        /////////////Plots for each Mass separatly//////////////
        /////////////----------------------------------------/////////////

        for (int p = 0; p < 2; p++) {
            // ptcut="112";
            // if(p==1) ptcut="" + flavor;
            ptcut="60";
            if(p==1) ptcut="110";
            ///////////////////////////////////////////////////////////////////
            ///////////Plot nice Mjjj plots
            //////////////////////////////////////////////////////////////////
            // string histname = string("GausWidth_vs_Mass_112") + ptcut;
            string histname = string("GausWidth_vs_Mass_" + flavor) + "_" + ptcut;
            cout<< histname << endl;
            TGraphErrors *h_gauswidth = (TGraphErrors*) filelist_kin[0]->Get(histname.c_str())->Clone();
            TGraphErrors *h_gauswidthup = (TGraphErrors*) filelist_kin[1]->Get(histname.c_str())->Clone();
            TGraphErrors *h_gauswidthdown = (TGraphErrors*) filelist_kin[2]->Get(histname.c_str())->Clone();
            histname = string("GausAcceptance_vs_Mass_" + flavor) + "_" + ptcut;
            // histname = string("GausAcceptance_vs_Mass_112") + ptcut;
            cout<< histname << endl;
            TGraphErrors *h_gausacc = (TGraphErrors*) filelist_kin[0]->Get(histname.c_str())->Clone();
            TGraphErrors *h_gausaccup = (TGraphErrors*) filelist_kin[1]->Get(histname.c_str())->Clone();
            TGraphErrors *h_gausaccdown = (TGraphErrors*) filelist_kin[2]->Get(histname.c_str())->Clone();

            TCanvas * cGluinoFitsOpti = new TCanvas(("RPV_"+ptcut+"_"+cuts).c_str(), ("RPV_" + ptcut+"_"+cuts).c_str(), 800, 600);
            //h_gauswidth->SetFillColor(kOrange-2);
            // h_gauswidth->SetLineColor(kBlack);
            string title;
            string systematic = "pile-up";
            // title="Gaussian Width vs. Mass for Light-ptcut RPV";
            string tag = "Heavy", sphericity = " Sphericity Cut";
            if (flavor.compare("112") == 0)
                tag = "Light";
            else if (ptcut == "60")
                sphericity = "";
            string titlepart = tag + "-flavor RPV " + flavor + " p_{T} = " + ptcut + sphericity;
            title = "Width for " + titlepart;
            /*
            if(k==0){
            title="RPV gluino #bf{" + systematic + " up} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 60 GeV}";
            if (i>=5 || p==0) title="RPV gluino #bf{" + systematic + " up} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 110 GeV}";
            }

            		if(k==1){
            title="RPV gluino #bf{" + systematic + " down} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 60 GeV}";
            if (i>=5 || p==0) title="RPV gluino #bf{" + systematic + " down} m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 110 GeV}";
            		}

            				if(k==2){
            title="RPV gluino m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 60 GeV}";
            if (i>=5 || p==0) title="RPV gluino m="+to_string(masses[i])+", ptcut = "+ptcut+", #Delta = 110 GeV, #bf{6^{th} Jet p_{T} = 110 GeV}";
            				}
            				*/
            TLegend *leg;
            leg = new TLegend(0.6,0.2,0.8994975,0.5,NULL,"brNDC");
            float linesiz = 2.0;
            h_gauswidthup->SetLineColor(kBlue);
            h_gauswidthup->SetLineWidth(linesiz);
            h_gauswidthup->SetMarkerColor(kBlue);
            TF1 *fitfunc = h_gauswidthup->GetFunction("GausWidth");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kBlue);
            leg->AddEntry(h_gauswidthup,"JES up", "L");
            h_gauswidthup->GetYaxis()->SetTitle("Width [GeV]");
            h_gauswidthup->GetYaxis()->SetTitleOffset(1.3);
            h_gauswidthup->GetXaxis()->SetTitle("RPV Mass [GeV]");
            h_gauswidthup->SetTitle(title.c_str());
            h_gauswidthup->Draw("A*");
            fitfunc = h_gauswidth->GetFunction("GausWidth");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kBlack);
            else cout << "Bad func name\n";
            h_gauswidth->SetLineColor(kBlack);
            h_gauswidth->SetMarkerColor(kBlack);
            h_gauswidth->SetLineWidth(linesiz);
            // h_gauswidth->SetTitleSize(0.01);
            // h_gauswidth->Draw("AL");
            leg->AddEntry(h_gauswidth,"Nominal JES", "L");
            h_gauswidth->Draw("same*");
            h_gauswidthdown->SetLineWidth(linesiz);
            h_gauswidthdown->SetMarkerColor(kRed);
            h_gauswidthdown->SetLineColor(kRed);
            fitfunc = h_gauswidthdown->GetFunction("GausWidth");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kRed);
            leg->AddEntry(h_gauswidthdown,"JES down", "L");
            h_gauswidthdown->Draw("same*");
            leg->Draw();
            cGluinoFitsOpti->Write();
            cGluinoFitsOpti->SaveAs((folder + "RPVwidthjesupdn" +flavor + ptcut+uncert+postfix).c_str());
            TCanvas * cGluinoFitsOpt2 = new TCanvas(("RPVacc_"+ptcut+"_"+cuts).c_str(), ("RPV_" + ptcut+"_"+cuts).c_str(), 800, 600);
            leg = new TLegend(0.6,0.2,0.8994975,0.5,NULL,"brNDC");
            title="Acceptance for " + titlepart;
            h_gausacc->SetTitle(title.c_str());
            h_gausacc->GetYaxis()->SetTitle("Acceptance");
            h_gausacc->GetYaxis()->SetTitleOffset(1.4);
            h_gausacc->GetXaxis()->SetTitle("RPV Mass [GeV]");
            // if (flavor.compare("113_223") == 0 && ptcut == "110") {
            // gStyle->SetStatY(0.8);
            // h_gausacc->GetYaxis()->SetRangeUser(0.0, 0.035);
            //}

            fitfunc = h_gausacc->GetFunction("total");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kBlack);
            else cout << "Bad func name\n";
            h_gausacc->SetLineColor(kBlack);
            h_gausacc->SetMarkerColor(kBlack);
            h_gausacc->SetLineWidth(linesiz);
            leg->AddEntry(h_gausacc,"Nominal JES", "L");
            // h_gausacc->Draw("AL");
            h_gausacc->Draw("A*");
            fitfunc = h_gausaccup->GetFunction("total");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kBlue);
            else cout << "Bad func name\n";
            h_gausaccup->SetLineColor(kBlue);
            h_gausaccup->SetMarkerColor(kBlue);
            h_gausaccup->SetLineWidth(linesiz);
            leg->AddEntry(h_gausaccup,"JES up", "L");
            h_gausaccup->Draw("same*");
            fitfunc = h_gausaccdown->GetFunction("total");
            if (fitfunc != NULL)
                fitfunc->SetLineColor(kRed);
            else cout << "Bad func name\n";
            h_gausaccdown->SetLineColor(kRed);
            h_gausaccdown->SetMarkerColor(kRed);
            h_gausaccdown->SetLineWidth(linesiz);
            leg->AddEntry(h_gausaccdown,"JES down", "L");
            h_gausaccdown->Draw("same*");
            leg->Draw();

            cGluinoFitsOpt2->Write();
            cGluinoFitsOpt2->SaveAs((folder + "RPVaccjesupdn" +flavor + ptcut+uncert+postfix).c_str());
            f1.cd();




            /////////////////Make some DataPlots///////////////////////
        }

    }


}
Example #21
0
bool Internal::set_value(string val)
{
    if (!Input::isEnabled()) return true;

    if (get_type() == TINT)
    {
        if (val == "inc")
        {
            double step = 1.0;
            if (Utils::is_of_type<double>(get_param("step")))
                Utils::from_string(get_param("step"), step);

            set_value(dvalue + step);
        }
        else if (val == "dec")
        {
            double step = 1.0;
            if (Utils::is_of_type<double>(get_param("step")))
                Utils::from_string(get_param("step"), step);

            set_value(dvalue - step);
        }
        else if (val.compare(0, 4, "inc ") == 0)
        {
            string t = val;
            t.erase(0, 4);

            double step = 1.0;
            if (Utils::is_of_type<double>(t))
                Utils::from_string(t, step);

            set_value(dvalue + step);
        }
        else if (val.compare(0, 4, "dec ") == 0)
        {
            string t = val;
            t.erase(0, 4);

            double step = 1.0;
            if (Utils::is_of_type<double>(t))
                Utils::from_string(t, step);

            set_value(dvalue - step);
        }
        else if (Utils::is_of_type<double>(val))
        {
            double dval;
            Utils::from_string(val, dval);

            set_value(dval);
        }
        else
        {
            return false;
        }
    }
    else if (get_type() == TSTRING)
    {
        cInfoDom("output") << get_param("id") << ": got action, " << val;

        force_input_string(val);

        EventManager::create(CalaosEvent::EventOutputChanged,
                             { { "id", Input::get_param("id") },
                               { "state", svalue } });
    }
    else if (get_type() == TBOOL)
    {
        if (val.compare(0, 8, "impulse ") == 0)
        {
            string tmp = val;
            tmp.erase(0, 8);
            // classic impulse, output goes false after <time> miliseconds
            if (Utils::is_of_type<int>(tmp))
            {
                int t;
                Utils::from_string(tmp, t);

                cInfoDom("output") << get_param("id")
                                   << ": got impulse action, staying true for "
                                   << t << "ms";

                set_value(true);

                timer = new EcoreTimer((double)t / 1000., [=]()
                {
                    set_value(false);
                });
            }
            else
            {
                // extended impulse using pattern
                impulse_extended(tmp);
            }

            return true;
        }
        else if (val == "toggle")
        {
            return set_value(!bvalue);
        }
        else if (val == "true" || val == "on")
        {
            return set_value(true);
        }
        else if (val == "false" || val == "off")
        {
            return set_value(false);
        }
        else
        {
            return false;
        }
    }

    return true;
}
Example #22
0
bool startsWith(const string& src, const string& sub)
{
    bool result = (src.compare(0, sub.size(), sub) == 0);
    return result;
}
Example #23
0
ScenePatch::ScenePatch(int order,int partsU, int partsV,string compute)
{
	this->order=order;
	this->partsU=partsU;
	this->partsV=partsV;
	this->compute=compute;
	index=0;


	if (compute.compare("fill") == 0)
	{
		drawmode=GL_FILL;
	}
	else if (compute.compare("line") == 0)
	{
		drawmode=GL_LINE;
	}
	else if (compute.compare("point") == 0)
	{
		drawmode=GL_POINT;
	}

	//textures
	if(order==1)
	{
		textPoints1[0][0]=0;
		textPoints1[0][1]=0;
		textPoints1[1][0]=1;
		textPoints1[1][1]=0;
		textPoints1[2][0]=0;
		textPoints1[2][1]=1;
		textPoints1[3][0]=1;
		textPoints1[3][1]=1;
	}

	else if(order==2)
	{
		textPoints2[0][0]=0;
		textPoints2[0][1]=0;
		textPoints2[1][0]=0,5;
		textPoints2[1][1]=0;
		textPoints2[2][0]=1;
		textPoints2[2][1]=0;

		textPoints2[3][0]=0;
		textPoints2[3][1]=0,5;
		textPoints2[4][0]=0,5;
		textPoints2[4][1]=0,5;
		textPoints2[5][0]=1;
		textPoints2[5][1]=0,5;
		
		textPoints2[6][0]=0;
		textPoints2[6][1]=1;
		textPoints2[7][0]=0,5;
		textPoints2[7][1]=1;
		textPoints2[8][0]=1;
		textPoints2[8][1]=1;
	}

	else if(order==3)
	{
		textPoints3[0][0]=0;
		textPoints3[0][1]=0;
		textPoints3[1][0]=1/3.0;
		textPoints3[1][1]=0;
		textPoints3[2][0]=2/3.0;
		textPoints3[2][1]=0;
		textPoints3[3][0]=1;
		textPoints3[3][1]=0;

		textPoints3[4][0]=0;
		textPoints3[4][1]=1/3.0;
		textPoints3[5][0]=1/3.0;
		textPoints3[5][1]=1/3.0;
		textPoints3[6][0]=2/3.0;
		textPoints3[6][1]=1/3.0;
		textPoints3[7][0]=1;
		textPoints3[7][1]=1/3.0;

		textPoints3[8][0]=0;
		textPoints3[8][1]=2/3.0;
		textPoints3[9][0]=1/3.0;
		textPoints3[9][1]=2/3.0;
		textPoints3[10][0]=2/3.0;
		textPoints3[10][1]=2/3.0;
		textPoints3[11][0]=1;
		textPoints3[11][1]=2/3.0;

		textPoints3[12][0]=0;
		textPoints3[12][1]=1;
		textPoints3[13][0]=1/3.0;
		textPoints3[13][1]=1;
		textPoints3[14][0]=2/3.0;
		textPoints3[14][1]=1;
		textPoints3[15][0]=1;
		textPoints3[15][1]=1;
	}


}
Example #24
0
bool endsWith(const string& src, const string& sub)
{
    bool result = (src.compare(src.size() - sub.size(), src.size(), sub) == 0);
    return result;
}
Example #25
0
/**
 * check if a one-line bracket has been reached,
 * i.e. if the currently reached '{' character is closed
 * with a complimentry '}' elsewhere on the current line,
 *.
 * @return     false = one-line bracket has not been reached.
 *             true  = one-line bracket has been reached.
 */
bool ASEnhancer::isOneLineBlockReached(string &line, int startChar) const
{
	assert(line[startChar] == '{');

	bool isInComment_ = false;
	bool isInQuote_ = false;
	int _bracketCount = 1;
	int lineLength = line.length();
	char quoteChar_ = ' ';
	char ch = ' ';

	for (int i = startChar + 1; i < lineLength; ++i)
	{
		ch = line[i];

		if (isInComment_)
		{
			if (line.compare(i, 2, "*/") == 0)
			{
				isInComment_ = false;
				++i;
			}
			continue;
		}

		if (ch == '\\')
		{
			++i;
			continue;
		}

		if (isInQuote_)
		{
			if (ch == quoteChar_)
				isInQuote_ = false;
			continue;
		}

		if (ch == '"' || ch == '\'')
		{
			isInQuote_ = true;
			quoteChar_ = ch;
			continue;
		}

		if (line.compare(i, 2, "//") == 0)
			break;

		if (line.compare(i, 2, "/*") == 0)
		{
			isInComment_ = true;
			++i;
			continue;
		}

		if (ch == '{')
			++_bracketCount;
		else if (ch == '}')
			--_bracketCount;

		if (_bracketCount == 0)
			return true;
	}

	return false;
}
Example #26
0
int main( int argc, const char** argv )
{
    CvCapture* capture = 0;
    Mat frame, frameCopy, image;
    const string scaleOpt = "--scale=";
    size_t scaleOptLen = scaleOpt.length();
    const string cascadeOpt = "--cascade=";
    size_t cascadeOptLen = cascadeOpt.length();
    const string nestedCascadeOpt = "--nested-cascade";
    size_t nestedCascadeOptLen = nestedCascadeOpt.length();
    const string tryFlipOpt = "--try-flip";
    size_t tryFlipOptLen = tryFlipOpt.length();
    string inputName;
    bool tryflip = false;

    help();

    CascadeClassifier cascade, nestedCascade;
    double scale = 1;

    for( int i = 1; i < argc; i++ )
    {
        cout << "Processing " << i << " " <<  argv[i] << endl;
        if( cascadeOpt.compare( 0, cascadeOptLen, argv[i], cascadeOptLen ) == 0 )
        {
            cascadeName.assign( argv[i] + cascadeOptLen );
            cout << "  from which we have cascadeName= " << cascadeName << endl;
        }
        else if( nestedCascadeOpt.compare( 0, nestedCascadeOptLen, argv[i], nestedCascadeOptLen ) == 0 )
        {
            if( argv[i][nestedCascadeOpt.length()] == '=' )
                nestedCascadeName.assign( argv[i] + nestedCascadeOpt.length() + 1 );
            if( !nestedCascade.load( nestedCascadeName ) )
                cerr << "WARNING: Could not load classifier cascade for nested objects" << endl;
        }
        else if( scaleOpt.compare( 0, scaleOptLen, argv[i], scaleOptLen ) == 0 )
        {
            if( !sscanf( argv[i] + scaleOpt.length(), "%lf", &scale ) || scale < 1 )
                scale = 1;
            cout << " from which we read scale = " << scale << endl;
        }
        else if( tryFlipOpt.compare( 0, tryFlipOptLen, argv[i], tryFlipOptLen ) == 0 )
        {
            tryflip = true;
            cout << " will try to flip image horizontally to detect assymetric objects\n";
        }
        else if( argv[i][0] == '-' )
        {
            cerr << "WARNING: Unknown option %s" << argv[i] << endl;
        }
        else
            inputName.assign( argv[i] );
    }

    if( !cascade.load( cascadeName ) )
    {
        cerr << "ERROR: Could not load classifier cascade" << endl;
        help();
        return -1;
    }

    if( inputName.empty() || (isdigit(inputName.c_str()[0]) && inputName.c_str()[1] == '\0') )
    {
        capture = cvCaptureFromCAM( inputName.empty() ? 0 : inputName.c_str()[0] - '0' );
        int c = inputName.empty() ? 0 : inputName.c_str()[0] - '0' ;
        if(!capture) cout << "Capture from CAM " <<  c << " didn't work" << endl;
    }
    else if( inputName.size() )
    {
        image = imread( inputName, 1 );
        if( image.empty() )
        {
            capture = cvCaptureFromAVI( inputName.c_str() );
            if(!capture) cout << "Capture from AVI didn't work" << endl;
        }
    }
    else
    {
        image = imread( "lena.jpg", 1 );
        if(image.empty()) cout << "Couldn't read lena.jpg" << endl;
    }

    cvNamedWindow( "result", 1 );

    if( capture )
    {
        cout << "In capture ..." << endl;
        for(;;)
        {
            IplImage* iplImg = cvQueryFrame( capture );
            frame = iplImg;
            if( frame.empty() )
                break;
            if( iplImg->origin == IPL_ORIGIN_TL )
                frame.copyTo( frameCopy );
            else
                flip( frame, frameCopy, 0 );

            detectAndDraw( frameCopy, cascade, nestedCascade, scale, tryflip );

            if( waitKey( 10 ) >= 0 )
                goto _cleanup_;
        }

        waitKey(0);

_cleanup_:
        cvReleaseCapture( &capture );
    }
    else
    {
        cout << "In image read" << endl;
        if( !image.empty() )
        {
            detectAndDraw( image, cascade, nestedCascade, scale, tryflip );
            waitKey(0);
        }
        else if( !inputName.empty() )
        {
            /* assume it is a text file containing the
            list of the image filenames to be processed - one per line */
            FILE* f = fopen( inputName.c_str(), "rt" );
            if( f )
            {
                char buf[1000+1];
                while( fgets( buf, 1000, f ) )
                {
                    int len = (int)strlen(buf), c;
                    while( len > 0 && isspace(buf[len-1]) )
                        len--;
                    buf[len] = '\0';
                    cout << "file " << buf << endl;
                    image = imread( buf, 1 );
                    if( !image.empty() )
                    {
                        detectAndDraw( image, cascade, nestedCascade, scale, tryflip );
                        c = waitKey(0);
                        if( c == 27 || c == 'q' || c == 'Q' )
                            break;
                    }
                    else
                    {
                    	cerr << "Aw snap, couldn't read image " << buf << endl;
                    }
                }
                fclose(f);
            }
        }
    }

    cvDestroyWindow("result");

    return 0;
}
Example #27
0
Md2Player::Md2Player (const string &dirname,const string &dirname1,const string &dirname2)
  throw (std::runtime_error)
  : _playerMesh (NULL), _weaponMesh (NULL)
{
  std::ifstream ifs;
  string path;
  dirent *dit;
  DIR *dd;

  // Open the directory
  dd = opendir (dirname.c_str ());
  if (!dd)
    throw std::runtime_error ("Couldn't open dir");

  // Test if player mesh exists
  path = dirname+dirname1;
  ifs.open (path.c_str (), std::ios::binary);

  if (!ifs.fail ())
    {
      ifs.close ();
      _playerMesh = Md2ModelPtr(new Md2Model (path));
    }

  // Test if weapon mesh exists
  path = dirname+dirname2/* + "/weapon.md2"*/;
  ifs.open (path.c_str (), std::ios::binary);

  if (!ifs.fail ())
    {
      ifs.close ();
      _weaponMesh = Md2ModelPtr(new Md2Model (path));
    }

  // If we haven't found any model, this is not a success...
  if (!_playerMesh.get () && !_weaponMesh.get ())
    throw std::runtime_error ("No model found");

  _name.assign (dirname, dirname.find_last_of ('/') + 1,
		dirname.length ());

  // Read directory for textures
  while ((dit = readdir (dd)) != NULL)
    {
      const string filename (dit->d_name);
      path = dirname + "/" + filename;

      const char *str = filename.c_str ();
      string::size_type l = filename.find_last_of ('.');

      // Skip directories
      if (l > filename.length ())
	continue;

      // Skip files beginning with "<char>_" and files
      // ending with "_i.<char*>"
      if ((str[1] != '_') &&
	  !((str[l-1] == 'i') && (str[l-2] == '_')))
	{
	  // Check if it's a known image file format
	  if (filename.compare (l, 4, ".pcx") == 0 ||
	      filename.compare (l, 4, ".tga") == 0 ||
	      filename.compare (l, 4, ".PCX") == 0 ||
	      filename.compare (l, 4, ".TGA") == 0)
	    {
	      if (filename.compare (0, 7, "weapon.") == 0)
		{
		  // We've got the weapon skin
		  _weaponMesh->loadTexture (path);
		  _weaponMesh->setTexture (path);
		}
	      else
		{
		  // Assume this is a player skin
		  _playerMesh->loadTexture (path);
		}
	    }
	}
    }

  // Close directory
  closedir (dd);

  // Attach models to MD2 objects
  if (_playerMesh.get ())
    {
      _playerObject.setModel (_playerMesh.get ());

      // Set first skin as default skin
      _currentSkin = _playerMesh->skins ().begin ()->first;
      _currentAnim = _playerObject.currentAnim ();
    }

  if (_weaponMesh.get ())
    {
      _weaponObject.setModel (_weaponMesh.get ());

      if (!_playerMesh.get ())
	_currentAnim = _weaponObject.currentAnim ();
    }
}
Example #28
0
bool Internal::set_value(string val)
{
    if (get_type() == TINT)
    {
        if (val == "inc")
        {
            double step = 1.0;
            if (Utils::is_of_type<double>(get_param("step")))
                Utils::from_string(get_param("step"), step);

            set_value(dvalue + step);
        }
        else if (val == "dec")
        {
            double step = 1.0;
            if (Utils::is_of_type<double>(get_param("step")))
                Utils::from_string(get_param("step"), step);

            set_value(dvalue - step);
        }
        else if (val.compare(0, 4, "inc ") == 0)
        {
            string t = val;
            t.erase(0, 4);

            double step = 1.0;
            if (Utils::is_of_type<double>(t))
                Utils::from_string(t, step);

            set_value(dvalue + step);
        }
        else if (val.compare(0, 4, "dec ") == 0)
        {
            string t = val;
            t.erase(0, 4);

            double step = 1.0;
            if (Utils::is_of_type<double>(t))
                Utils::from_string(t, step);

            set_value(dvalue - step);
        }
        else if (Utils::is_of_type<double>(val))
        {
            double dval;
            Utils::from_string(val, dval);

            set_value(dval);
        }
        else
        {
            return false;
        }
    }
    else if (get_type() == TSTRING)
    {
        cInfoDom("output") << get_param("id") << ": got action, " << val;

        force_input_string(val);

        string sig = "output ";
        sig += Input::get_param("id") + " ";
        sig += url_encode(string("state:") + Utils::to_string(svalue));
        IPC::Instance().SendEvent("events", sig);
    }
    else if (get_type() == TBOOL)
    {
        if (val.compare(0, 8, "impulse ") == 0)
        {
            string tmp = val;
            tmp.erase(0, 8);
            // classic impulse, output goes false after <time> miliseconds
            if (Utils::is_of_type<int>(tmp))
            {
                int t;
                Utils::from_string(tmp, t);

                cInfoDom("output") << get_param("id")
                                   << ": got impulse action, staying true for "
                                   << t << "ms";

                set_value(true);

                timer = new EcoreTimer((double)t / 1000., [=]()
                {
                    set_value(false);
                });
            }
            else
            {
                // extended impulse using pattern
                impulse_extended(tmp);
            }

            return true;
        }
        else if (val == "toggle")
        {
            return set_value(!bvalue);
        }
        else if (val == "true" || val == "on")
        {
            return set_value(true);
        }
        else if (val == "false" || val == "off")
        {
            return set_value(false);
        }
        else
        {
            return false;
        }
    }

    return true;
}
Example #29
0
  void fromJsonSub(const json11::Json& json) {
   //cout << "[[Revisions::fromJson]]..." << endl;
   batchcomplete = json["batchcomplete"].string_value();
   continue_res.clear();
   continue_2_res.clear();
   if(json.object_items().find("continue") != json.object_items().end()) {
    auto continueJson = json["continue"].object_items();
    if(continueJson.find("rvcontinue") != continueJson.end()) continue_res = continueJson["rvcontinue"].string_value();
    else if(continueJson.find("arvcontinue") != continueJson.end()) continue_res = continueJson["arvcontinue"].string_value();
    continue_2_res = continueJson["continue"].string_value();
   }
   //cout << "[[Revisions::fromJson]] continue_res: " << continue_res << endl;
   auto queryJson = json["query"].object_items();
   if(queryJson.find("normalized") != queryJson.end()) {
    auto normalizedJson = queryJson["normalized"].array_items();
    for(auto inor : normalizedJson) {
     string from = inor["from"].string_value();
     if(pagesNormalizedTitles.find(from) != pagesNormalizedTitles.end()) continue;
     string to = inor["to"].string_value();
     pagesNormalizedTitles[from] = to;
    }
   }

   map<string, json11::Json> pagesJsonObjects = queryJson["pages"].object_items();
   //cout << "[[Revisions::fromJson]] pagesJsonObjects.size(): " << pagesJsonObjects.size() << endl;
   for(auto ipro : pagesJsonObjects) {
    if(pagesById.find(stol(ipro.first)) == pagesById.end()) {
     //Page page(ipro.second);
     Page page;
     page.fromJson(ipro.second);
     pages.push_back(page);
     //cout << "[[Revisions::fromJson]] pages.size(): " << pages.size() << endl;
     //Page* pagePointer = &pages[pages.size()-1];
     //cout << "[[Revisions::fromJson]] page.pageid: " << page.pageid << endl;
     //pagesById[page.pageid] = pagePointer;
     //cout << "[[Revisions::fromJson]] page.title: " << page.title << endl;
     //pagesByTitle[page.title] = pagePointer;
     pagesById[page.pageid] = pages.size()-1;
     pagesByTitle[page.title] = pages.size()-1;
     /*
     pagesById[page.pageid] = page;
     pagesByTitle[page.title] = page;
     */
    } else {
     //cout << "[[Revisions::fromJson]] stol(ipro.first): " << stol(ipro.first) << endl;
     cout << "[[Revisions::fromJson]] pagesById[stol(ipro.first)]: " << pagesById[stol(ipro.first)] << endl;
     //pagesById[stol(ipro.first)]->fromJson(ipro.second);
     //pagesById[stol(ipro.first)].fromJson(ipro.second);
     pages[pagesById[stol(ipro.first)]].fromJson(ipro.second);
    }
   }

   vector<json11::Json> pagesJsonArray = queryJson["allrevisions"].array_items();;
   //cout << "[[Revisions::fromJson]] pagesJsonArray.size(): " << pagesJsonArray.size() << endl;
   for(auto ipra : pagesJsonArray) {
    //Page page(ipra);
    Page page;
    page.fromJson(ipra);
    //cout << "[[Revisions::fromJson]] page.pageid: " << page.pageid << endl;
    if(pagesById.find(page.pageid) == pagesById.end()) {
     pages.push_back(page);
     //cout << "[[Revisions::fromJson]] pages.size(): " << pages.size() << endl;
     //Page* pagePointer = &pages[pages.size()-1];
     //cout << "[[Revisions::fromJson]] pagePointer: " << pagePointer << endl;
     //cout << "[[Revisions::fromJson]] page.pageid (new): " << page.pageid << endl;
     //pagesById[page.pageid] = pagePointer;
     //cout << "[[Revisions::fromJson]] page.title: " << page.title << endl;
     //pagesByTitle[page.title] = pagePointer;
     pagesById[page.pageid] = pages.size()-1;
     pagesByTitle[page.title] = pages.size()-1;
     /*
     pagesById[page.pageid] = page;
     pagesByTitle[page.title] = page;
     */
    } else {
     //cout << "[[Revisions::fromJson]] page.pageid (old): " << page.pageid << endl;
     //Page* pagePointer = pagesById[page.pageid];
     //cout << "[[Revisions::fromJson]] pagesById[page.pageid]: pagePointer" << pagePointer << endl;
     //pagePointer->fromJson(ipra);
     pages[pagesById[page.pageid]].fromJson(ipra);
     //pagesById[page.pageid]->fromJson(ipra);
     //pagesById[pageRevisions.pageid].fromJson(ipra);
    }
   }

   //cout << "[[Revisions::fromJson]] pages.size(): " << pages.size() << endl;
   revisions.clear();
   for(Page prs : pages) {
    for(Revision r : prs.revisions) {
     revisions.push_back(r);
    }
   }

   //cout << "[[Revisions::fromJson]] revisions.size(): " << revisions.size() << endl;
   if(dir.compare("older") == 0) sort(revisions.begin( ), revisions.end( ), [] (const Revision& lhs, const Revision& rhs) {return lhs.revid < rhs.revid;});
   else sort(revisions.begin( ), revisions.end( ), [] (const Revision& lhs, const Revision& rhs) {return lhs.revid > rhs.revid;});   
  }
Example #30
0
void populate_filenames(string input, s_pathlist * paths)
{
    ALLEGRO_PATH * base_path = al_create_path(input.c_str());

    input = al_get_path_filename(base_path);

    //fisrt we gotta make sure this is, in fact, an exported DF map
    if (input.compare(0, 14, "world_graphic-") != 0)
    {
        //it isn't the old style naming. Now we check if it's new new one.
        size_t pos = input.find_last_of(".");
        string extension = input.substr(pos);
        string baseName = input.substr(0, pos);
        pos = baseName.find_last_of("-");
        string type = baseName.substr(pos);
        baseName = baseName.substr(0, pos);

        if (!(
            type.compare("-bm") == 0
            || type.compare("-detailed") == 0
            || type.compare("-dip") == 0
            || type.compare("-drn") == 0
            || type.compare("-el") == 0
            || type.compare("-elw") == 0
            || type.compare("-evil") == 0
            || type.compare("-hyd") == 0
            || type.compare("-nob") == 0
            || type.compare("-rain") == 0
            || type.compare("-sal") == 0
            || type.compare("-sav") == 0
            || type.compare("-str") == 0
            || type.compare("-tmp") == 0
            || type.compare("-trd") == 0
            || type.compare("-veg") == 0
            || type.compare("-vol") == 0
            ))
        {
            log_printf("Map name isn't a recognizable format");
            return;
        }
        pos = baseName.length() - 12;
        string date = baseName.substr(pos);
        baseName = baseName.substr(0, pos);

        current_save = baseName;

        log_printf("Loaded up %s\n", current_save.c_str());

        //and now it's time to fill out the list of image paths

        char buffer[256];


        paths->biome_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-bm%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->biome_map, buffer);

        paths->combined_biome_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-detailed%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->combined_biome_map, buffer);

        paths->elevation_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-el%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->elevation_map, buffer);

        paths->elevation_map_with_water = al_clone_path(base_path);
        sprintf(buffer, "%s%s-elw%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->elevation_map_with_water, buffer);

        paths->structure_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-str%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->structure_map, buffer);

        paths->trade_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-trd%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->trade_map, buffer);

        paths->temperature_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-tmp%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->temperature_map, buffer);

        paths->rainfall_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-rain%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->rainfall_map, buffer);

        paths->drainage_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-drn%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->drainage_map, buffer);

        paths->savagery_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-sav%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->savagery_map, buffer);

        paths->volcanism_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-vol%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->volcanism_map, buffer);

        paths->vegetation_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-veg%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->vegetation_map, buffer);

        paths->evil_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-evil%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->evil_map, buffer);

        paths->salinity_map = al_clone_path(base_path);
        sprintf(buffer, "%s%s-sal%s", baseName.c_str(), date.c_str(), extension.c_str());
        al_set_path_filename(paths->salinity_map, buffer);

        al_destroy_path(base_path);

        user_config.map_path = al_path_cstr(paths->biome_map, ALLEGRO_NATIVE_PATH_SEP);
        return;
    }

    //now we get rid of all the junk in the beginning, to get the name of the fort.
    input.erase(0, 14);

    char buffer[256];

    if (
        input.compare(0, 4, "drn-") == 0
        || input.compare(0, 4, "elw-") == 0
        || input.compare(0, 4, "sal-") == 0
        || input.compare(0, 4, "sav-") == 0
        || input.compare(0, 4, "tmp-") == 0
        || input.compare(0, 4, "veg-") == 0
        || input.compare(0, 4, "vol-") == 0
        || input.compare(0, 4, "str-") == 0
        || input.compare(0, 4, "trd-") == 0
        ) {
            input.erase(0, 4);
    }else if (input.compare(0, 3, "el-") == 0
        || input.compare(0, 3, "bm-") == 0) {
            input.erase(0, 3);
    }else if (
        input.compare(0, 5, "evil-") == 0
        || input.compare(0, 5, "rain-") == 0
        ) {
            input.erase(0, 5);
    }
    //save the resulting name to a gobal
    current_save = input;
    if(current_save.rfind("--") < std::string::npos) { //get rid of the double dash.
        current_save.erase(current_save.find_last_of("-"), std::string::npos); // -16014.bmp
    }
    current_save.erase(current_save.find_last_of("-"), std::string::npos); // -16014.bmp
    current_save.erase(current_save.find_last_of("-"), std::string::npos); // -250
    log_printf("Loaded up %s\n", current_save.c_str());
    //and now it's time to fill out the list of image paths
    paths->biome_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-bm-%s", input.c_str());
    al_set_path_filename(paths->biome_map, buffer);

    paths->combined_biome_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-%s", input.c_str());
    al_set_path_filename(paths->combined_biome_map, buffer);

    paths->elevation_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-el-%s", input.c_str());
    al_set_path_filename(paths->elevation_map, buffer);

    paths->elevation_map_with_water = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-elw-%s", input.c_str());
    al_set_path_filename(paths->elevation_map_with_water, buffer);

    paths->structure_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-str-%s", input.c_str());
    al_set_path_filename(paths->structure_map, buffer);

    paths->trade_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-trd-%s", input.c_str());
    al_set_path_filename(paths->trade_map, buffer);

    paths->temperature_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-tmp-%s", input.c_str());
    al_set_path_filename(paths->temperature_map, buffer);

    paths->rainfall_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-rain-%s", input.c_str());
    al_set_path_filename(paths->rainfall_map, buffer);

    paths->drainage_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-drn-%s", input.c_str());
    al_set_path_filename(paths->drainage_map, buffer);

    paths->savagery_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-sav-%s", input.c_str());
    al_set_path_filename(paths->savagery_map, buffer);

    paths->volcanism_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-vol-%s", input.c_str());
    al_set_path_filename(paths->volcanism_map, buffer);

    paths->vegetation_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-veg-%s", input.c_str());
    al_set_path_filename(paths->vegetation_map, buffer);

    paths->evil_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-evil-%s", input.c_str());
    al_set_path_filename(paths->evil_map, buffer);

    paths->salinity_map = al_clone_path(base_path);
    sprintf(buffer, "world_graphic-sal-%s", input.c_str());
    al_set_path_filename(paths->salinity_map, buffer);

    al_destroy_path(base_path);

    user_config.map_path = al_path_cstr(paths->biome_map, ALLEGRO_NATIVE_PATH_SEP);
}