Example #1
0
int DataManager::SetValue(const string varName, string value, int persist /* = 0 */)
{
    if (!mInitialized)
        SetDefaultValues();

    // Don't allow empty values or numerical starting values
    if (varName.empty() || (varName[0] >= '0' && varName[0] <= '9'))
        return -1;

    map<string, string>::iterator constChk;
    constChk = mConstValues.find(varName);
    if (constChk != mConstValues.end())
        return -1;

    map<string, TStrIntPair>::iterator pos;
    pos = mValues.find(varName);
    if (pos == mValues.end())
        pos = (mValues.insert(TNameValuePair(varName, TStrIntPair(value, persist)))).first;
    else
        pos->second.first = value;

    if (pos->second.second != 0)
        SaveValues();

    gui_notifyVarChange(varName.c_str(), value.c_str());
    return 0;
}
Example #2
0
    int longestValidParentheses(string s) {
		if(s.size() <= 1)
			return 0;

		stack<int> lefts;
		int leftmost = -1;
		int longest = 0;
		int i;

		for(i = 0; i < s.size(); i++){
			if(s[i] == '('){
				lefts.push(i);
			}
			else{
				// must be ')'
				if(lefts.empty())
					leftmost = i;
				else{
					lefts.pop();
					if(lefts.empty()){
						longest = max(longest, i-leftmost);
					}
					else{
						longest = max(longest, i-lefts.top());
					}
				}
			}
		}

		return longest;
    }
Example #3
0
void dp(int pos, string msg)
{
	//cout<< msg<< endl;
	if(pos == message.size())
	{
		if(!(S.check()))
		{
			Set.insert(msg);
			//cout << msg << endl;
		}
		if(msg == message)
			ans++;
	}
	if(S.check())
	{
		char c = S.pop();
		//cout << "$" << c << "$"<<endl;
		msg += c;
		//cout <<"$$" <<  msg << "$$"<<endl;
		dp(pos, msg);
		S.push(c);
		msg = msg.substr(0, msg.size() - 1);
	}
	
	if(pos < message.size())
	{
		S.push(message[pos]);
		dp(pos+1, msg);
		S.pop();
	}
	return;
}
 string solveEquation(string equation) {
   //the below are all wrong expression
   if (equation == "0x=0" || equation == "0=0x" || equation == "0x+0x=0x"){
     return "Infinite solutions";
   }
   if (equation == "0x=1" || equation == "1=0x"){
     return "No solution";
   }
   //partition string from '=' into 2 strings
   //get all the constants towars the right
   int pos = equation.find('=');
   string left = equation.substr(0,pos);
   string right = equation.substr(pos+1);
   extractConstants(left,true);
   extractConstants(right,false);
   int total = 0;
   int total_lit = 0;
   for (auto v : consts) {
     total += v.first*v.second;
   }
   for (auto v : literal) {
     total_lit += v.first*v.second;
   }
   cout<<total<<" "<<total_lit<<"\n";
   if (total_lit == 0 && total != 0) {
     return "No solution";
   }
   if (total_lit == 0 && total == 0) {
     return "Infinite solutions";
   }
   total = total/total_lit;
   res = "x=" + to_string(total);
   return res;
 }
Example #5
0
	/**Call Templated encode */
	void encode(istream & in, ostream & out){
		
		while(getline(in,line)){ // get line from stream
			std::transform(line.begin(), line.end(),line.begin(), ::toupper);
			out<<cp.encode(key,line,lenVec)+"\n";//encode & write char into file
		}		
	}
Example #6
0
bool ParseUtil::isParenExp(string text) {
  bool lFound = false;
  bool rFound = false;
  for (int i = 0; i < text.size(); i++) {
    char c = text.at(i);
    if (c == '(') {
      lFound = true;
      break;
    } else if (c == ' ') {

    } else {
      return false;
    }
  }

  for (int i = text.size() - 1; i >= 0; i--) {
    char c = text.at(i);
    if (c == ')') {
      rFound = true;
      break;
    } else if (c == ' ') {

    } else {
      return false;
    }
  }
  return (lFound && rFound);
}
Example #7
0
File: 5.cpp Project: nebffa/ctci
string compress(string input)
{
	string output;
	char cur_char = input[0];
	int n_consecutive_chars = 0;

	for (string::iterator it = input.begin(); it != input.end(); it++)
	{
		if (cur_char == *it)
		{
			n_consecutive_chars++;
		}
		else
		{
			ostringstream oss;
			output += cur_char;
			oss << n_consecutive_chars;
			output += oss.str();
			cur_char = *it;
			n_consecutive_chars = 1;
		}
	}
	ostringstream oss;
	output += cur_char;
	oss << n_consecutive_chars;
	output += oss.str();

	if (input.size() <= output.size())
	{
		return input;
	}
	return output;
}
 int lengthOfLongestSubstring(string s) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     bool hash[128];
     int max = 0;
     for (int i = 0; i < s.size(); i++)
     {
         int j = 0;
         int count = 1;
         for (j = 0; j < 128; j++)
         {
             hash[j] = false;
         }
         
         hash[s[i]] = true; 
         for (j = i + 1; j < s.size(); j++)
         {
             if (hash[s[j]])
             {
                 break;
             }
             hash[s[j]] = true;
             count++;
         }
         if (count > max)
             max = count;
     }
     return max;
 }
Example #9
0
IceInternal::DynamicLibrary::symbol_type
IceInternal::DynamicLibrary::getSymbol(const string& name)
{
    assert(_hnd != 0);
#ifdef _WIN32
    symbol_type result = GetProcAddress(_hnd, name.c_str());
#else
    symbol_type result = dlsym(_hnd, name.c_str());
#endif

    if(result == 0)
    {
        //
        // Remember the most recent error in _err.
        //
#ifdef _WIN32
        _err = IceUtilInternal::lastErrorToString();
#else
        const char* err = dlerror();
        if(err)
        {
            _err = err;
        }
#endif
    }
    return result;
}
int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	lli t;
	cin>>t;
	while(t--){
		lli x;
		lli dp[27];
		vector<lli> cost;
		cin>>s;
		n = s.length();
		for(int i(0);i<s.length();i++){
			cin>>x;
			cost.push_back(x);
		}
		for(int i(0);i<27;i++){
			dp[i] = 1e18;
		}
		dp[0] = 0;
		for(int i(0);i<n;i++){
			dp[(s[i]-'a')+1] = min(dp[(s[i]-'a')+1],cost[i]+dp[(s[i]-'a')]);
		}
		if(dp[26]!=1e18){
			cout<<dp[26]<<endl;
		}
		else{
			cout<<"Not Possible."<<endl;
		}
	}
	return 0;
}
Example #11
0
bool ThemeLoader::extractTarGz( const string &tarFile, const string &rootDir )
{
    TAR *t;
#if defined( HAVE_LIBTAR_H )
    tartype_t gztype = { (openfunc_t) gzopen_frontend,
                         (closefunc_t) gzclose_frontend,
                         (readfunc_t) gzread_frontend,
                         (writefunc_t) gzwrite_frontend };

    if( tar_open( &t, (char *)tarFile.c_str(), &gztype, O_RDONLY, 0,
                  TAR_GNU ) == -1 )
#else
    if( tar_open( &t, (char *)tarFile.c_str(), O_RDONLY ) == -1 )
#endif
    {
        return false;
    }

    if( tar_extract_all( t, (char *)rootDir.c_str() ) != 0 )
    {
        tar_close( t );
        return false;
    }

    if( tar_close( t ) != 0 )
    {
        return false;
    }

    return true;
}
Example #12
0
 vector<int> findSubstring(string s, vector<string> &words) {
     map<string, int> dict;
     map<string, int> curStr;
     for(int i = 0; i < words.size(); ++i)
         ++dict[words.at(i)];
     int N = words.size();
     vector<int> ret;
     if(N <= 0)   return ret;
     int M = words.at(0).size();
     for(int i = 0; i <= (int)s.size()-N*M; ++i)
     {
         curStr.clear();
         int j = 0;
         for(j = 0; j < N; ++j)
         {
             string w = s.substr(i+j*M, M);
             if(dict.find(w) == dict.end())
                 break;
             ++curStr[w];
             if(curStr[w] > dict[w])
                 break;
         }
         if(j == N)  ret.push_back(i);
     }
     return ret;
 }
Example #13
0
File: var.hpp Project: Zleub/pr-c
	void	parsing(string declaration)
	{
		char *result = strcpy((char*)malloc(declaration.length()+1), declaration.c_str());
		char	*str;

		if (this->pointer == 1)
			str = strtok(result, "*");
		else
			str = strtok(result, "\t");
		while (str != NULL)
		{

			str = trim(str);
			type = str;
			str = strtok (NULL, "\t");
			str = trim(str);
			name = str;
			str = strtok (NULL, "\t");
			// if (str != NULL)
		}

		if (this->pointer)
			var_return = "NULL";
		else
			var_return = "-1";

	}
int longestValidParentheses(string s) {
	if (s.empty()) {
		return 0;
	}
	stack <int> left;
	vector<bool> isMatch(s.length(), false);
	int idx = 0;
	while (idx < s.length()) {
		if (s[idx] == '(') {
			left.push(idx);
		} else {
			if (!left.empty()) {
				isMatch[left.top()] = true;
				isMatch[idx] = true;
				left.pop();
			}
		}
		++idx;
	}
	
	int len = 0;
	int tmpLen = 0;
	for (int i = 0; i < isMatch.size(); ++i) {
		if (!isMatch[i]) {
			len = len < tmpLen ? tmpLen : len;
			tmpLen = 0;
		} else {
			++tmpLen;
		}
	}
	len = len < tmpLen ? tmpLen : len;
	
	return len;
}
Example #15
0
void PnlPlnrLyrRec::StatShr::writeXML(
			pthread_mutex_t* mScr
			, map<ubigint,string>& scr
			, map<string,ubigint>& descr
			, xmlTextWriter* wr
			, string difftag
			, bool shorttags
		) {
	if (difftag.length() == 0) difftag = "StatShrPlnrLyrRec";

	string itemtag;
	if (shorttags) itemtag = "Si";
	else itemtag = "StatitemShrPlnrLyrRec";

	xmlTextWriterStartElement(wr, BAD_CAST difftag.c_str());
		writeStringAttr(wr, itemtag, "sref", "srefIxPlnrVExpstate", VecPlnrVExpstate::getSref(ixPlnrVExpstate));
		writeStringAttr(wr, itemtag, "sref", "scrJrefDetail", Scr::scramble(mScr, scr, descr, jrefDetail));
		writeStringAttr(wr, itemtag, "sref", "scrJref1NBlock", Scr::scramble(mScr, scr, descr, jref1NBlock));
		writeBoolAttr(wr, itemtag, "sref", "pnl1nblockAvail", pnl1nblockAvail);
		writeStringAttr(wr, itemtag, "sref", "scrJref1NReticle", Scr::scramble(mScr, scr, descr, jref1NReticle));
		writeBoolAttr(wr, itemtag, "sref", "pnl1nreticleAvail", pnl1nreticleAvail);
		writeStringAttr(wr, itemtag, "sref", "scrJrefMNStructure", Scr::scramble(mScr, scr, descr, jrefMNStructure));
		writeBoolAttr(wr, itemtag, "sref", "pnlmnstructureAvail", pnlmnstructureAvail);
		writeBoolAttr(wr, itemtag, "sref", "ButRegularizeActive", ButRegularizeActive);
	xmlTextWriterEndElement(wr);
};
void
readFeatureModels ( int argc, char **argv, const std::string &extension, 
		    std::vector< std::vector<float> > &models, const string max_filename = "" )
{  
  char line[ 100 ];
  string tmpname;
  int dim, sample_num;
  std::vector<float> feature;
  std::vector<float> feature_max;
  bool is_normalize = false;

  //* bin normalization parameters
  if( max_filename.size() != 0 ){
    is_normalize = true;
    FILE *fp = fopen( max_filename.c_str(), "r" );
    float val;
    while( fscanf( fp, "%f\n", &val ) != EOF )
      feature_max.push_back( val );
    fclose( fp );
  }
  
  for (int i = 1; i < argc; i++){
    string fname = string (argv[i]);
    // Needs to have the right size
    if (fname.size () <= extension.size ())
      continue;
    transform (fname.begin (), fname.end (), fname.begin (), (int(*)(int))tolower);
    if (fname.compare (fname.size () - extension.size (), extension.size (), extension) == 0){
      FILE *fp = fopen( argv[i], "r" );
      while( 1 ){
	fgets(line,sizeof(line),fp);
	tmpname = string (line);
	if( tmpname.compare (0, 5, "COUNT") == 0 )
	  sscanf( line, "COUNT %d", &dim );
	else if( tmpname.compare (0, 6, "POINTS") == 0 )
	  sscanf( line, "POINTS %d", &sample_num );
	else if( tmpname.compare (0, 4, "DATA") == 0 )
	  break;
      }
      feature.resize( dim );
      if( is_normalize ){
	for(int n=0;n<sample_num;n++){
	  for(int t=0;t<dim;t++){
	    fscanf(fp,"%f ",&(feature[ t ]) );
	    scaling( t, feature, feature_max );
	  }
	  models.push_back ( feature );
	}
      }
      else{
	for(int n=0;n<sample_num;n++){
	  for(int t=0;t<dim;t++)
	    fscanf(fp,"%f ",&(feature[ t ]) );
	  models.push_back ( feature );
	}
      }
      fclose(fp);
    }
  }
}
Example #17
0
 string fun(string str)
 {
     int cnt = 0;
     char c = '0';
     int index = 0;
     int iter = 0;
     string res = "";
     while(iter < str.size())
     {
         c = str[index];
         cnt = 0;
         while((iter < str.size()) && (c == str[iter]))
         {
             ++iter;
             ++cnt;
         }
         if(cnt == 1)
         {
             res += "1";
             res += c;
         }
         else
         {
             res += char(cnt + '0');
             res += c;
         }
         index = iter;
     }
     return res;
 }
Example #18
0
/// \brief Prints residue numbers in alignment
///
/// \relates alignment
void cath::align::write_alignment_as_cath_ssap_legacy_format(const path      &arg_output_file, ///< TODOCUMENT
                                                             const alignment &arg_alignment,   ///< TODOCUMENT
                                                             const protein   &seq_a,           ///< TODOCUMENT
                                                             const protein   &seq_b            ///< TODOCUMENT
                                                             ) {
	ofstream aln_out_stream;
	open_ofstream( aln_out_stream, arg_output_file );

	// Try here to catch any I/O exceptions
	try {
		output_alignment_to_cath_ssap_legacy_format(aln_out_stream, arg_alignment, seq_a, seq_b);

		// Close the file
		aln_out_stream.close();
	}
	// Catch and immediately rethrow any boost::exceptions
	// (so that it won't get caught in the next block if it's a std::exception)
	catch (const boost::exception &ex) {
		throw;
	}
	// Catch any I/O exceptions
	catch (const std::exception &ex) {
		const string error_message("Cannot output alignment to file \"" + arg_output_file.string() + "\" [" + ex.what() + "] ");
		perror(error_message.c_str());
		BOOST_THROW_EXCEPTION(runtime_error_exception(error_message));
	};
}
Example #19
0
/**
 * Sends data to the Web Service.
 *
 * @param InputData
 * A std::string containing all the data, which is going to be submitted as HTTP POST data.
 *
 * @return
 * Returns a pointer to a char array containing the data received from the Web Service.
 * The caller needs to free that pointer.
 */
PCHAR
CWebService::DoRequest(const string& InputData)
{
    const WCHAR szHeaders[] = L"Content-Type: application/x-www-form-urlencoded";

    auto_array_ptr<char> Data;
    DWORD DataLength;

    /* Post our test results to the web service */
    m_hHTTPRequest = HttpOpenRequestW(m_hHTTP, L"POST", szServerFile, NULL, NULL, NULL, INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE, 0);

    if(!m_hHTTPRequest)
        FATAL("HttpOpenRequestW failed\n");

    Data.reset(new char[InputData.size() + 1]);
    strcpy(Data, InputData.c_str());

    if(!HttpSendRequestW(m_hHTTPRequest, szHeaders, wcslen(szHeaders), Data, InputData.size()))
        FATAL("HttpSendRequestW failed\n");

    /* Get the response */
    if(!InternetQueryDataAvailable(m_hHTTPRequest, &DataLength, 0, 0))
        FATAL("InternetQueryDataAvailable failed\n");

    Data.reset(new char[DataLength + 1]);

    if(!InternetReadFile(m_hHTTPRequest, Data, DataLength, &DataLength))
        FATAL("InternetReadFile failed\n");

    Data[DataLength] = 0;

    return Data.release();
}
Example #20
0
bool MyTblFmncQUsgMNUser::loadRecBySQL(
			const string& sqlstr
			, FmncQUsgMNUser** rec
		) {
	MYSQL_RES* dbresult; MYSQL_ROW dbrow; unsigned long* dblengths;
	FmncQUsgMNUser* _rec = NULL;

	bool retval = false;

	if (mysql_real_query(dbs, sqlstr.c_str(), sqlstr.length())) throw DbsException("DbsException / MySQL: error executing query '" + sqlstr + "'\n");

	dbresult = mysql_store_result(dbs);
	if (!dbresult) throw DbsException("DbsException / MySQL: error storing result! (TblFmncQUsgMNUser / loadRecBySQL)\n");

	if (mysql_num_rows(dbresult) == 1) {
		dbrow = mysql_fetch_row(dbresult);
		dblengths = mysql_fetch_lengths(dbresult);

		_rec = new FmncQUsgMNUser();

		if (dbrow[0]) _rec->qref = atoll((char*) dbrow[0]); else _rec->qref = 0;
		if (dbrow[1]) _rec->jref = atoll((char*) dbrow[1]); else _rec->jref = 0;
		if (dbrow[2]) _rec->jnum = atol((char*) dbrow[2]); else _rec->jnum = 0;
		if (dbrow[3]) _rec->mref = atoll((char*) dbrow[3]); else _rec->mref = 0;
		if (dbrow[4]) _rec->ref = atoll((char*) dbrow[4]); else _rec->ref = 0;
		if (dbrow[5]) _rec->ixFmncVUserlevel = atol((char*) dbrow[5]); else _rec->ixFmncVUserlevel = 0;

		retval = true;
	};

	mysql_free_result(dbresult);

	*rec = _rec;
	return retval;
};
Example #21
0
// Add a ChannelClient to the ChannelClientList. return false if aClientPtr
// is NULL or if modes are invalid. (different to 'o' or 'v')
bool Channel::AddChannelClient(Client *aClientPtr, const string &aModes)
{
   // Check we don't get bogus entries.
   if (aClientPtr == NULL || aModes.find(' ') != string::npos || IsChannelClient(aClientPtr->GetNumeric()))
    return false;

   // Only modes o and v are accepted.
   if (aModes.length() > 2)
    return false;

   // only channel modes o and v are accepted. Return false if any other is passed.
   for(unsigned int i = 0; i < aModes.length(); i++)
    if (aModes[i] != 'o' && aModes[i] != 'v')
     return false;

   // create the new channel client.
   ChannelClient *NewChannelClient = new ChannelClient(aClientPtr, aModes);

   // if we couldn't add the client to the client list the return false.
   if (!ChannelClientList.insert(ChannelClientListType::value_type(aClientPtr->GetNumeric(), NewChannelClient)).second) 
   	return false;

   // Add this channel to the channel list of this client.
   aClientPtr->AddChannel(this);

   return true;
}
	string minWindow(string s, string t) {
		int tCount[256] = { 0 };
		int findCount[256] = { 0 };
		int tLen = t.size(), sLen = s.size();
		for (int i = 0; i < tLen; i++)  tCount[t[i]]++;
		int foundCount = 0;
		queue<int> Q;
		int winStart = -1, winEnd = sLen - 1;
		int start = 0;
		for (int i = 0; i < sLen; i++)
			if (tCount[s[i]] > 0)
			{
				Q.push(i);
				findCount[s[i]]++;
				if (findCount[s[i]] <= tCount[s[i]])  foundCount++;
				if (foundCount == tLen)
				{
					int k ;
					do
					{
						k = Q.front();
						Q.pop();
						findCount[s[k]]--;
					} while (findCount[s[k]] >= tCount[s[k]]);
					if (winEnd - winStart > i - k)
					{
						winStart = k;
						winEnd = i;
					}
					foundCount--;
				}
			}
		return winStart != -1 ? s.substr(winStart, winEnd - winStart + 1) : "";
	}
void process_front_page(const string in_file, const string out_file, const string base_url)
{
    //read the file in one line at a time and write it to the output file
    //open the input file
    ifstream ifs(in_file.c_str());
    if(!ifs) error("can't open the input file to process the front page");
    //open the output file
    ofstream ofs(out_file.c_str());
    if(!ofs) error("can't open the output file to process the front page");

    //read each line and write it to output...later we will only write it
    //if there is a regex match in the line
    string line;
    while(ifs) {
        getline(ifs, line);
        string p = "^<li>.+=\"(.+)\">.+</li>$";
        boost::regex pat(p);
        boost::smatch matches;
        if(boost::regex_match(line, matches, pat)) {
            if(matches.size() == 2) {		//we have a match for the capture
                ofs<<base_url<<matches[1]<<endl;	//add the capture to the links file
            }
        }
    }
}
	int strobogrammaticInRange(string low, string high) {
		if (lessThan(high, low))
		{
			return 0;
		}

		int ln = low.size();
		int hn = high.size();

		int l = 0;
		string path(ln, '0');
		strobogrammaticLessThan(path, 0, ln - 1, l, low);

		int r = 0;
		path = string(hn, '0');
		strobogrammaticLessThan(path, 0, hn - 1, r, high);
		if (isStrobogrammatic(high))
		{
			r++;
		}

		int result = 0;
		for (int i = ln; i < hn; i++)
		{
			result += strobogrammaticofSize(i);
		}

		result = result - l + r;
		return result;


	}
Example #25
0
 explicit BigNumber(string v) {
     int i = 0;
     if (v[i] == '-') {
         sign = 1;
         i++;
     }
     while (i < v.size()) {
         if (isdigit(v[i])) {
             integerPart.push_back(v[i]);
         } else {
             if (v[i] != '.')
                 throw std::runtime_error("NaN");
             break;
         }
         i++;
     }
     if (v[i] == '.') {
         i++;
         while (i < v.size()) {
             if (isdigit(v[i]))
                 fractionaryPart.push_back(v[i]);
             else
                 throw std::runtime_error("NaN");
             i++;
         }
     }
     reverse(integerPart.begin(), integerPart.end());
     if (fractionaryPart.size())
         reverse(fractionaryPart.begin(), fractionaryPart.end());
 }
Example #26
0
string findLastWord(const string& s){
    auto first=find_if(s.rbegin(),s.rend(),::isalpha);
    auto last=find_if_not(first,s.rend(),::isalpha);
    string result(first,last);
    reverse(result.begin(),result.end());
    return result;
}
Example #27
0
void BackgroundJob::jobBody() {
    const string threadName = name();
    if (!threadName.empty()) {
        setThreadName(threadName);
    }

    LOG(1) << "BackgroundJob starting: " << threadName;

    try {
        run();
    } catch (const std::exception& e) {
        error() << "backgroundjob " << threadName << " exception: " << redact(e.what());
        throw;
    }

    // We must cache this value so that we can use it after we leave the following scope.
    const bool selfDelete = _selfDelete;

    {
        // It is illegal to access any state owned by this BackgroundJob after leaving this
        // scope, with the exception of the call to 'delete this' below.
        stdx::unique_lock<stdx::mutex> l(_status->mutex);
        _status->state = Done;
        _status->done.notify_all();
    }

    if (selfDelete)
        delete this;
}
Example #28
0
bool wordBreak(string s, int index, unordered_set<string> &dict, vector<int>& mem)
{
    bool ret = false;
    for (int i=index; i<s.size(); i++)
    {
        if (dict.find(s.substr(index, i-index+1)) != dict.end())
        {
            if (i+1 == s.size())
            {
                ret = true;
                break;
            }
            if (mem[i+1] == -1)
            {
                wordBreak(s, i+1, dict, mem);
            }
            if (mem[i+1] == 1)
            {
                ret = true;
                break;
            }
        }
    }
    mem[index] = ret ? 1 : 0;
    return ret;
}
Example #29
0
/// parse command line arguments
void parse_args(int argc, char** argv) {
	try {  
        TCLAP::CmdLine cmd("trace", ' ', "0.0");

        TCLAP::ValueArg<int> resolutionArg("r","resolution","Image resolution",false,0,"int",cmd);
        TCLAP::ValueArg<int> samplesArg("s","samples","Pixel samples",false,0,"int",cmd);
        
        TCLAP::SwitchArg progressiveArg("P","progressive","Progressive Rendering",cmd);
        
        TCLAP::SwitchArg distributionArg("d","distribution_raytrace","Distribution Raytracing",cmd);
        TCLAP::SwitchArg pathtraceArg("p","pathtrace","Pathtracing",cmd);
        
        TCLAP::UnlabeledValueArg<string> filenameScene("scene","Scene filename",true,"","filename",cmd);
        TCLAP::UnlabeledValueArg<string> filenameImage("image","Image filename",false,"","filename",cmd);
        
        cmd.parse( argc, argv );

        if(pathtraceArg.isSet()) pathtrace = pathtraceArg.getValue();
        if(distributionArg.isSet()) distribution = distributionArg.getValue();
        
        if(resolutionArg.isSet()) resolution = resolutionArg.getValue();
        if(samplesArg.isSet()) samples = samplesArg.getValue();
        if(progressiveArg.isSet()) progressive = progressiveArg.getValue();
        
        filename_scene = filenameScene.getValue();
        if(filenameImage.isSet()) filename_image = filenameImage.getValue();
        else { filename_image = filename_scene.substr(0,filename_scene.length()-4)+"png"; }
	} catch (TCLAP::ArgException &e) { 
        std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; 
    }
}
Example #30
0
/// parses command line arguments
void parse_args(int argc, char** argv) {
	try {  
        TCLAP::CmdLine cmd("view", ' ', "0.0");
        
        TCLAP::ValueArg<int> resolutionArg("r","resolution","Image resolution",false,512,"resolution",cmd);
        TCLAP::ValueArg<int> samplesArg("s","samples","Image samples",false,4,"samples",cmd);
        
        TCLAP::SwitchArg hudArg("j","hud","HUD",cmd);
        TCLAP::SwitchArg screenshotAndExitArg("i","screenshotAndExit","Screenshot and exit",cmd);
        TCLAP::ValueArg<float> timeArg("t","time","Time advance (delays screenshot and exit)",false,0,"seconds",cmd);
        
        TCLAP::UnlabeledValueArg<string> filenameScene("scene","Scene filename",true,"","scene",cmd);
        TCLAP::UnlabeledValueArg<string> filenameImage("image","Image filename",false,"","image",cmd);
        
        cmd.parse( argc, argv );
        
        if(resolutionArg.isSet()) draw_opts.res = resolutionArg.getValue();
        if(samplesArg.isSet()) draw_opts.samples = samplesArg.getValue();
        if(hudArg.isSet()) hud = not hudArg.getValue();
        if(screenshotAndExitArg.isSet()) screenshotAndExit = screenshotAndExitArg.getValue();
        if(timeArg.isSet()) time_init_advance = timeArg.getValue();
        
        filename_scene = filenameScene.getValue();
        if(filenameImage.isSet()) filename_image = filenameImage.getValue();
        else { filename_image = filename_scene.substr(0,filename_scene.length()-4)+"png"; }
	} catch (TCLAP::ArgException &e) { 
        std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; 
    }
}