Example #1
0
int FileCreator::createFile(const string &relPathStr) {
  CHECK(!relPathStr.empty());
  CHECK(relPathStr[0] != '/');
  CHECK(relPathStr.back() != '/');

  std::string path(rootDir_);
  path.append(relPathStr);

  int p = relPathStr.size();
  while (p && relPathStr[p - 1] != '/') {
    --p;
  }
  std::string dir;
  if (p) {
    dir.assign(relPathStr.data(), p);
    if (!createDirRecursively(dir)) {
      // retry with force
      LOG(ERROR) << "failed to create dir " << dir << " recursively, "
                 << "trying to force directory creation";
      if (!createDirRecursively(dir, true /* force */)) {
        LOG(ERROR) << "failed to create dir " << dir << " recursively";
        return -1;
      }
    }
  }
  int openFlags = O_CREAT | O_WRONLY;
  START_PERF_TIMER
  int res = open(path.c_str(), openFlags, 0644);
  if (res < 0) {
    if (dir.empty()) {
      PLOG(ERROR) << "failed creating file " << path;
      return -1;
    }
    PLOG(ERROR) << "failed creating file " << path << ", trying to "
                << "force directory creation";
    if (!createDirRecursively(dir, true /* force */)) {
      LOG(ERROR) << "failed to create dir " << dir << " recursively";
      return -1;
    }
    START_PERF_TIMER
    res = open(path.c_str(), openFlags, 0644);
    if (res < 0) {
      PLOG(ERROR) << "failed creating file " << path;
      return -1;
    }
    RECORD_PERF_RESULT(PerfStatReport::FILE_OPEN)
  } else {
Example #2
0
string answer(string P, int from, int to, const string& S, const map<string, vector<int> > &M) {
    while (P.size() && P[0] != '*') {
        if (P[0] != S[from])
            return "No";
        P.erase(P.begin());
        if (from > to)
            return "No";
        ++from;
    }
    while (P.size() && P[P.size() - 1] != '*') {
        if (P.back() != S[to])
            return "No";
        P.erase(P.begin() + P.size() - 1);
        if (from > to)
            return "No";
        --to;
    }
    if (count(P.begin(), P.end(), '*') == int(P.size())) {
        if (from <= to && P.size() == 0)
            return "No";
        else
            return "Yes";
    }

    while (!P.empty()) {
        if (P[0] == '*') {
            P.erase(P.begin());
            continue;
        }
        string Q;
        while (P[0] != '*') {
            Q += P[0];
            P.erase(P.begin());
        }
        if (M.count(Q) == 0) {
            return "No";
        }
        const vector<int>& vec = M.find(Q)->second;
        auto pos = lower_bound(vec.begin(), vec.end(), from);
        if (pos == vec.end())
            return "No";
        from = *pos + Q.size();
        if (from > to + 1)
            return "No";
    }
    return "Yes";
}
Example #3
0
// static
bool EditableMapObject::ValidateWebsite(string const & site)
{
  if (site.empty())
    return true;

  // Site should contain at least one dot but not at the begining/end.
  if ('.' == site.front() || '.' == site.back())
    return false;

  if (string::npos == site.find("."))
    return false;

  if (string::npos != site.find(".."))
    return false;

  return true;
}
bool parse_address(const char* s, string& addr, string& port) {
	if (!s) {
		return false;
	}
	string str(s);
	size_t i = str.rfind(':');
	if (i == string::npos) {
		return false;
	}
	addr = str.substr(0, i);
	/* ipv6 address */
	if (!addr.empty() && addr.front() == '[' && addr.back() == ']') {
		addr = str.substr(1, i - 2);
	}
	port = str.substr(i + 1);
	return true;
}
Example #5
0
void inode_state::mkdir(const string& pathname) {
    string name;
    if (pathname.back() == '/')
        name = pathname.substr(0, pathname.size() - 1);
    else 
        name = pathname;
    inode_ptr p = resolve_pathname(name);
    if (p == nullptr)
        throw yshell_exn ("mkdir: " + pathname + 
                            ": invalid path");
    directory_ptr dir = directory_ptr_of(p->get_contents());
    size_t found = name.find_last_of("/");
    if (found == string::npos)
        dir->mkdir(name);
    else
        dir->mkdir(name.substr(found+1));
}
Example #6
0
 /**
  * @param n the nth
  * @return the nth sequence
  */
 string solve(const string &str) {
     int num = 1;
     char ch = str[0];
     string st = "";
     for (int i = 1; i < str.length(); i ++) {
         if (str[i] == ch) {
             num ++;
         } else {
             st += to_string(num);
             st += str[i-1];
             num = 1;
             ch = str[i];
         }
     }
     st += to_string(num);
     st += str.back();
     return st;
 }
Example #7
0
void dfs(map<int, set<string>> &result, string &path, vector<string> &maze, int r, int c, const int N)
{
    if (r < 0 || c < 0 || r >= N || c >= N) {
        return;
    }
    if (!path.empty() && path.back() >= maze[r][c]) {
        return;
    }
    path.push_back(maze[r][c]);
    if (path.size() >= LEN) {
        auto &words = result[path.size()];
        words.insert(path);
    }
    for (int i = 0; i < 8; ++i) {
        dfs(result, path, maze, r+RD[i], c+CD[i], N);
    }
    path.pop_back();
}
 void reverseWords(string &s) {
     int ls = s.size();
     int i, j;
     
     i = 0;
     j = 0;
     while (i < ls && s[i] == ' ') {
         ++i;
     }
     while (i < ls) {
         while (i < ls && s[i] != ' ') {
             s[j++] = s[i++];
         }
         if (i == ls) {
             break;
         }
         while (i < ls && s[i] == ' ') {
             ++i;
         }
         s[j++] = ' ';
     }
     s.resize(j);
     ls = s.size();
     
     i = 0;
     while (i < ls) {
         while (i < ls && s[i] == ' ') {
             ++i;
         }
         if (i == ls) {
             break;
         }
         j = i + 1;
         while (j < ls && s[j] != ' ') {
             ++j;
         }
         reverse(s.begin() + i, s.begin() + j);
         i = j;
     }
     while (s.size() > 0 && s.back() == ' ') {
         s.pop_back();
     }
     reverse(s.begin(), s.end());
 }
void dfs(vector<string> &result,string &path, char last,int size,int step){
    if(step >= size)
        return;
    char current = path.back();
    if((current-1 == last || current+1 == last) && step < size){
        string tmp = path;
        tmp.push_back(last);
        result.push_back(tmp);
        //return;
        //pay attention: there is no return here
    }
    path.push_back(current+1);
    dfs(result,path,last,size,step+1);
    path.pop_back();
    path.push_back(current-1);
    dfs(result,path,last,size,step+1);
    path.pop_back();
    return;
}
Example #10
0
void inode_state::lsr(const string& pathname, ostream& out) {
    string suffix;
    inode_ptr p; 
    if (pathname.back() == '/')
        suffix = "";
    else
        suffix = "/";
    p = resolve_pathname(pathname + suffix);
    if (p == nullptr)
        throw yshell_exn ("lsr: " + pathname +
                         ": No such file or directory");
    ls(pathname, out);
    directory_ptr dir = directory_ptr_of(p->contents);
    vector<inode_ptr> subdirs (dir->subdirs());
    for (size_t i = 0;
                i < subdirs.size();
                i++)
        lsr(pathname + suffix + subdirs.at(i)->get_name() + '/', out);
}
Example #11
0
catalog_manager::catalog_manager(const string &_base_addr) 
    : base_addr(_base_addr.back() == '/' ? _base_addr : _base_addr + "/") 
{
    assert( base_addr.back() == '/' );

    ifstream in(base_addr + "catalog");

    string tmp;
    if (in.is_open()) {
        while (in >> tmp) {
            relations[tmp] = new catalog(base_addr + tmp + "/catalog");
            int count;
            in >> count;
            relations[tmp]->set_size(count);
        }
    }

    in.close();
}
Example #12
0
bool getline(FILE *f, string& line) {
  if (feof(f)) return (line.clear(), false);

  size_t offset = 0;
  bool eof;
  line.resize(128);
  while (line.back() = '\1', eof = !fgets((char *) line.data() + offset, line.size() - offset, f), !eof && line.back() == '\0') {
    offset = line.size() - 1;
    if (line[offset-1] == '\n') break;
    line.resize(2 * line.size());
  }
  if (eof && !offset) return (line.clear(), false);

  int len = offset + strlen(line.data() + offset);
  if (len && line[len - 1] == '\n') len--;
  line.resize(len);

  return true;
}
Example #13
0
 int romanToInt(string s) {
     
     unordered_map<char, int> M = { //build an unordered map to map the roman number
         {'I', 1},
         {'V', 5},
         {'X', 10},
         {'L', 50},
         {'C', 100},
         {'D', 500},
         {'M', 1000}
     };
     
     int results = M[s.back()];
     for(int i = s.size()-2; i >= 0; --i){
         if(M[s[i]] < M[s[i+1]]) results -= M[s[i]];
         else results += M[s[i]];
     }
     return results;
 }
Example #14
0
 bool check(string cur) {
     if (mp.find(cur) != mp.end()) {
         return mp[cur];
     }
     if (cur.size() == init.size()) {
         mp[cur] = (cur == init);
         return mp[cur];
     }
     mp[cur] = false;
     if (cur.back() == 'A') {
         mp[cur] = mp[cur] || check(cur.substr(0, cur.size() - 1));
     }
     if (cur[0] == 'B') {
         string t = cur.substr(1, cur.size() - 1);
         reverse(t.begin(), t.end());
         mp[cur] = mp[cur] || check(t);
     }
     return mp[cur];
 }
Example #15
0
int main(){
	freopen("pattern.in","r",stdin);
	freopen("pattern.out","w",stdout);

	ios::sync_with_stdio(false);
	cin>>A>>B; N = B.size(); B = B+B;
	string sA;
	for( int i=0; i<A.size(); i++){
		if( i && A[i-1] == '*' && A[i] == '*' ) continue;
		sA.push_back( A[i] );
	}
	sA.swap( A );
	if( A.size() == 1 ){
		if( A[0] == '*' ){
			printf("%d\n",N);
			return 0;
		}else{
			if( B.size() == 1 && B[0] == A[0] )
				printf("1\n");
			else
				printf("0\n");
			return 0;
		}
	}
	
	ls = ( A[0] == '*' ); rs = ( A.back() == '*' );
	stringstream ass(A); string cs;
	while( getline( ass, cs, '*') ){
		if( cs.size() == 0 ) continue;
		len[cn] = cs.size();
		kmp( B, cs, cn++ );
	}	

	int ans = 0;
	for(int i=0; i<N; i++){
		if( dec( i ) ) ans++;
	}
	printf("%d\n",ans);
	fclose( stdin );
	fclose( stdout );
	return 0;
}
Example #16
0
//problem #1
bool isPalindrome(const string& input) 
{     
          
      if( input.length() == 0 || input.length() == 1 )
      {
      	    cout<< "true" << endl;
            return true;
      }
      else if( input.front() == input.back() )
      {  
          //input.substr(1, input.length() - 2);
          return isPalindrome(input.substr(1,input.length() - 2));                         
      }
      else
      {    
          cout << "false" << endl;
      	  return false;
      }

}	
 void reverseWords(string &s) {
     bool flag=0;
     for (int i=0;i<s.size();i++) {
         if (s[i]==' ') 
             if (!flag) flag=1;
             else {s.erase(i,1);i--;}
         else flag=0;
         }
     if ( !s.empty() && s[0]==' ') s.erase(0,1);
     if (!s.empty() && s.back()==' ') s.erase(s.size()-1,1);
     if (s.size()>2) {
     reverseString(s,0,s.size()-1);
     int prev=0;
     for (int i=0;i<s.size();i++) {
         if (s[i]==' ') {reverseString(s,prev,i-1);prev=i+1;}
         
     }
     reverseString(s,prev,s.size()-1);
     }
 }
void dicTree::traverse(node * current,string pre)
{
 char* local;
 for(int i=0;i<CHAR;i++){
 	if(current->child[i]->count){
		pre+=char(i+'a');
		local=&pre.back();
 		traverse(current->child[i],pre);
 		if(current->end){
 			cout<<pre;
 		*local='\0';
 		
 		
 		cout<<endl;}
 		}
 		
 		
 	}
 	
}
Example #19
0
		static void getDir(string directory, vector<string> &files) {
			DIR *d;
			struct dirent *df;
			struct stat ds;

			if((d = opendir(directory.c_str())) != NULL) {
				while((df = readdir(d)) != NULL) {
					//ignore directories
					if(df->d_name[0] == '.') continue;
					if(directory.back() != '/') directory += "/";
					stat((directory + string(df->d_name)).c_str(), &ds);
					if(S_ISDIR(ds.st_mode)) continue;

					//push to files
					files.push_back(directory + string(df->d_name));
				}
			}

			closedir(d);
		}
Example #20
0
void dfs(string sequence, int terms)
{
    if (sequence.front() == '[') sequence.erase(sequence.begin());
    if (sequence.back() == ']') sequence.erase(sequence.end() - 1);
    
    string number, remainder;
    char operators;
    
    for (int i = 0; i < sequence.length(); i++)
        if (sequence[i] != '+' && sequence[i] != '*')
            number += sequence[i];
        else
        {
            remainder = sequence.substr(i + 1);
            operators = sequence[i];
            break;
        }   

    if (operators == '+' || operators == '*')
    {
        dfs(remainder, terms);
        
        if (operators == '+')
        {
            result.insert(result.begin(), number);
            for (int i = 1; i < terms; i++)
                result[i] = add(result[i], result[i - 1]);
        }
        else
        {
            result.front() = multiplicate(number, result.front());
            for (int i = 1; i < terms; i++)
                result[i] = multiplicate(result[i], result[i - 1]);
        }
    }
    else
    {        
        for (int i = 0; i < terms; i++)
            result.push_back(number);
    }
}
bool NameDialog::AskForName(QWidget *parent, const QString &title,
		const QString &text, string &str, const QString &placeHolder)
{
	NameDialog dialog(parent);
	dialog.setWindowTitle(title);
	dialog.ui->label->setText(text);
	dialog.ui->userText->setText(placeHolder);
	dialog.ui->userText->selectAll();

	bool accepted = (dialog.exec() == DialogCode::Accepted);
	if (accepted) {
		str = dialog.ui->userText->text().toStdString();

		while (str.size() && IsWhitespace(str.back()))
			str.erase(str.end() - 1);
		while (str.size() && IsWhitespace(str.front()))
			str.erase(str.begin());
	}

	return accepted;
}
Example #22
0
string getContentType(string filename){
	string filetype;
	char c=filename.back();
	switch(c){
	case 'l' :
		filetype="text/html";
		break;
	case 't':
		filetype="text/plain";
		break;
	case 'f':
		filetype="image/gif";
		break;
	case 'g':
		filetype="image/jpg";
		break;
	default :
		filetype="invalid";
	}
	return filetype;
}
Example #23
0
int FileCreator::openExistingFile(const string &relPathStr) {
  // This should have been validated earlier and errored out
  // instead of crashing here
  WDT_CHECK(!relPathStr.empty());
  WDT_CHECK(relPathStr[0] != '/');
  WDT_CHECK(relPathStr.back() != '/');

  string path(rootDir_);
  path.append(relPathStr);

  int openFlags = O_WRONLY;
  START_PERF_TIMER
  int res = open(path.c_str(), openFlags, 0644);
  RECORD_PERF_RESULT(PerfStatReport::FILE_OPEN)
  if (res < 0) {
    PLOG(ERROR) << "failed opening file " << path;
    return -1;
  }
  VLOG(1) << "successfully opened file " << path;
  return res;
}
Example #24
0
BundlePtr BundleQueue::getMergeBundle(const string& aTarget) const noexcept {
	// Returns a bundle that is in a parent directory (or in the same location), in which we can merge to
	// File bundles with the exact target will be returned as well

	// In case it's a file bundle
	auto filePath = Util::getFilePath(aTarget);

	for(const auto& compareBundle: bundles | map_values) {
		dcassert(aTarget.back() != PATH_SEPARATOR || !AirUtil::isSubLocal(compareBundle->getTarget(), filePath));

		if (compareBundle->isFileBundle()) {
			// Adding the same file again?
			if (Util::stricmp(aTarget, compareBundle->getTarget()) == 0) {
				return compareBundle;
			}
		} else if (AirUtil::isParentOrExactLocal(compareBundle->getTarget(), filePath)) {
			return compareBundle;
		}
	}
	return nullptr;
}
Example #25
0
// // or ///, empty, ....
string Normalize(string input)
{
    if(input.back()!='/')
        input += '/';
    vector<string> result;
    int prev = 0;
    int cur = input.find('/', prev);
    while(cur != string::npos)
    {
        string component = input.substr(prev, cur-prev);
        result.push_back(component);
        prev = cur + 1;
        cur = input.find('/', prev);
    }
    
    
    string s = Output(result);
    if(input[0]!='/')
        s.erase(0, 1);
    return s;
}
Example #26
0
static void parse_lng_line(const string_view str, string& label, string& data, bool& have_data)
{
	have_data = false;

	//-- //[Label]
	if (starts_with(str, L"//["sv) && ends_with(str, L"]"sv))
	{
		const auto LabelView = str.substr(3, str.size() - 3 - 1);
		//-- //[Label=0]
		assign(label, LabelView.substr(0, LabelView.find(L'=')));
		return;
	}

	//-- "Text"
	if (starts_with(str, L'"'))
	{
		have_data = true;
		assign(data, str.substr(1));
		if (!data.empty() && data.back() == L'"')
			data.pop_back();
		return;
	}

	//-- MLabel="Text"
	if (!str.empty() && str.back() == L'"')
	{
		const auto eq_pos = str.find(L'=');
		if (eq_pos != string::npos && InRange(L'A', upper(str[0]), L'Z'))
		{
			assign(data, trim(str.substr(eq_pos + 1)));
			if (data.size() > 1 && data[0] == L'"')
			{
				assign(label, trim(str.substr(0, eq_pos)));
				have_data = true;
				data.pop_back();
				data.erase(0, 1);
			}
		}
	}
}
Example #27
0
    void search(vector<vector<char>>& board, int i, int j, TrieTree& trie, string& word, vector<string>& result) {
        word.push_back(board[i][j]);
        board[i][j] = '\0';

        if (trie.hasWord(word)) {
            result.push_back(word);
            trie.erase(word);
        }

        if (trie.startsWith(word)) {
            for (int t = 0; t < 4; t++) {
                int ii = i + di[t];
                int jj = j + dj[t];
                if (0 <= ii && ii < m && 0 <= jj && jj < n && board[ii][jj]) {
                    search(board, ii, jj, trie, word, result);
                }
            }
        }

        board[i][j] = word.back();
        word.pop_back();
    }
Example #28
0
void inode_state::rmr(const string& pathname) {
    string target_name, pname;
    if (pathname.back() == '/') {
        pname = pathname.substr(0, pathname.size() - 1);
    } else { 
        pname = pathname;
    }
    inode_ptr p = resolve_pathname(pname);
    size_t found = pname.find_last_of("/");
    if (found == string::npos)
        target_name = pname;
    else
        target_name = pathname.substr(found + 1);
    directory_ptr dir = directory_ptr_of(p->contents);
    p = dir->lookup(target_name);
    if (p == nullptr)
        throw yshell_exn ("rmr: " + pathname 
                + ": No such file or directory");
    if (p->type == PLAIN_INODE)
        throw yshell_exn ("rmr: " + pathname + ": is not a directory");
    dir->remove_r(target_name, pathname);
}
Example #29
0
// static
bool EditableMapObject::ValidateWebsite(string const & site)
{
  if (site.empty())
    return true;

  auto const startPos = GetProtocolNameLength(site);

  if (startPos >= site.size())
    return false;

  // Site should contain at least one dot but not at the begining/end.
  if ('.' == site[startPos] || '.' == site.back())
    return false;

  if (string::npos == site.find("."))
    return false;

  if (string::npos != site.find(".."))
    return false;

  return true;
}
Example #30
0
int RomanToInterger(const string &s) {
    unordered_map<char, int> R{
        {'I', 1}, 
        {'V', 5}, 
        {'X', 10}, 
        {'L', 50},
        {'C', 100},
        {'D', 500},
        {'M', 1000},
    };

    int sum = R[s.back()];

    for (int i = s.size() -2; i >= 0; i--) {
        if (R[s[i]] < R[s[i+1]]) {
            sum -= R[s[i]];
        } else {
            sum += R[s[i]];
        }
    }

    return sum;
}