Example #1
0
void IniSetting::ParserCallback::onPopEntry(
    const std::string &key,
    const std::string &value,
    const std::string &offset,
    void *arg) {
  Variant *arr = (Variant*)arg;
  forceToArray(*arr);

  bool oEmpty = offset.empty();
  // Substitution copy or symlink
  // Offset come in like: hhvm.a.b\0c\[email protected]
  // Check for `\0` because it is possible, although unlikely, to have
  // something like hhvm.a.b[[email protected]]. Thus we wouldn't want to make a substitution.
  if (!oEmpty && (offset.size() == 1 || offset[offset.size() - 2] == '\0') &&
      (offset.back() == '@' || offset.back() == ':')) {
    makeSettingSub(key, offset, value, *arr);
  } else {                                 // Normal array value
    String skey(key);
    auto& hash = arr->toArrRef().lvalAt(skey);
    forceToArray(hash);
    if (!oEmpty) {                         // a[b]
      makeArray(hash, offset, value);
    } else {                               // a[]
      hash.toArrRef().append(value);
    }
  }
}
Example #2
0
bool CreditCard::Validate(std::string creditCardNumber)
{
    unsigned int sum=0;
    bool toggle=true;
    unsigned int otherCheckDigit=creditCardNumber.back() - '0';
    unsigned int myCheckDigit=0;

    creditCardNumber.pop_back();

    while(!creditCardNumber.empty())
    {
        unsigned int temp=creditCardNumber.back() - '0'; //saves last digit

        if (toggle)
        {
            temp= temp*2;

            if (temp>=10)
                temp=temp-9;
        }

        sum=sum+temp;

        toggle=!toggle;
        creditCardNumber.pop_back(); //deletes last digit
    }

    myCheckDigit= (sum*9)%10;

    return (otherCheckDigit==myCheckDigit);
}
Example #3
0
long long toNum(std::string str, int type = 0)
{
	int len = str.length();
	long long ret = 0;
	if (len < 1)
		return 0;
	if (canBeNum(str) == false)
		return 0;
	std::stringstream ss;
	bool negative = false;
	if (str.front() == '-')
	{
		str.erase(0, 1);
		negative = true;
		len--;
	}
	else if (str.front() == '+')
	{
		str.erase(0, 1);
		len--;
	}
	switch (type)
	{
		case 0:
			if (len == 0)
				return 0;
			if (str.back() == 'h' || str.back() == 'H')
			{
				str.erase(len - 1, 1);
				ss << std::hex << str;
				ss >> ret;
			}
			else if (str.front() == '0' && len > 1)
	void basic_configuration::set_workspace(std::string path)
	{
		if (path.back() != '/' && path.back() != '\\')
			path.push_back('/');

		pimpl->workspace_path = path;
	}
Example #5
0
bool ConfigReader::parse_obj(const std::string &key, std::string &obj,
		std::string &err)
{
	std::vector<std::string> items;
	std::string okey, oval;
	std::unordered_map<std::string, std::string> map;
	size_t ind;

	/* remove surrounding braces and whitespace */
	obj = obj.substr(1);
	remove_leading(obj);
	while (obj.back() != '}')
		obj.pop_back();
	obj.pop_back();
	while (isspace(obj.back()))
		obj.pop_back();

	utils::split(obj, '\n', items);

	for (std::string s : items) {
		if ((ind = s.find('=')) == std::string::npos) {
			err = "unrecognized token in list -- ";
			for (ind = 0; !isspace(s[ind]); ++ind)
				err += s[ind];
			return false;
		}
		okey = s.substr(0, ind);
		while (isspace(okey.back()))
			okey.pop_back();
		oval = parse_string(s);
		map[okey] = oval;
	}
	olistmap[key].emplace_back(map);
	return true;
}
Example #6
0
void bebopftp::downloadMedia(std::string bebop_ip, std::string download_to, bool erase)
{
    if(download_to.back() != '/' && download_to.back() != '\\')
    {
        download_to.append("/");
    }

    nsFTP::CFTPClient ftpClient;
    nsFTP::CLogonInfo logonInfo(bebop_ip);

    ftpClient.Login(logonInfo);
    nsFTP::TFTPFileStatusShPtrVec list;
    ftpClient.List(BEBOP_MEDIA_LOCATION, list);

    for(nsFTP::TFTPFileStatusShPtrVec::iterator it=list.begin(); it!=list.end(); it++)
    {
        std::cout << "Downloading " << (*it)->Name() << " into " << download_to << std::endl;
        ftpClient.DownloadFile(BEBOP_MEDIA_LOCATION + (*it)->Name(), download_to + (*it)->Name());
        if(erase)
        {
            ftpClient.Delete(BEBOP_MEDIA_LOCATION + (*it)->Name());
        }
    }

    ftpClient.Logout();

    std::cout << "Done." << std::endl;
}
 /*
  *  GetLastPathComponent
  *      @path: Path to get the last component from
  *      @return: Returns the last path component position in the string
  */
 inline std::string::size_type GetLastPathComponent(std::string path)
 {
     // Remove any slash at the end of the string, so our finding can be safe
     while(path.back() == '/' || path.back() == '\\') path.pop_back();
     // Do the search
     size_t pos = path.find_last_of("/\\");
     return (pos == path.npos? 0 : pos + 1);
 }
Example #8
0
std::string getFullPath(const std::string& parentDir, const std::string& name) {
	std::string full = parentDir;
	if (parentDir.back() != '/' && parentDir.back() != '\\') {
		return parentDir + "\\" + name;
	} else {
		return parentDir + name;
	}
}
static void ensure_trailing_separators(std::string& local_path, std::string& remote_path) {
    if (!adb_is_separator(local_path.back())) {
        local_path.push_back(OS_PATH_SEPARATOR);
    }
    if (remote_path.back() != '/') {
        remote_path.push_back('/');
    }
}
Example #10
0
void Talkbot::normalize(std::string& sentence) const
{
	if(not sentence.empty())
	{
		if(std::islower(sentence[0]))
			sentence[0] = std::toupper(sentence[0]);
		if(sentence.back() != '.' and sentence.back() != '!' and sentence.back() != '?')
			sentence.push_back('.');
	}
}
 /*
  *  NormalizePath
  *      Normalizates a path string, so for example:
  *          "somefolder/something" will output "somefolder\\something"
  *          "SOMEfoldER/something/" will output "somefolder\\something"
  *          "somefolder\\something" will output "somefolder\\something"
  *          etc
  */
 inline std::string NormalizePath(std::string path)
 {
     
     std::replace(path.begin(), path.end(), '/', '\\');  // Replace all '/' with '\\'
     tolower(path);                                      // tolower the strings (Windows paths are case insensitive)
     while(path.back() == '/' || path.back() == '\\')    // We don't want a slash at the end of the folder path
         path.pop_back();                                // ..
     trim(path);                                         // Trim the string...
     return path;
 }
Example #12
0
LODEN_CORE_EXPORT std::string joinPath(const std::string &path1, const std::string &path2)
{
    if (path1.empty())
        return path2;
    if (isAbsolutePath(path2))
        return path2;
    if(path1.back() == '/' || path1.back() == '\\')
        return path1 + path2;
    return path1 + "/" + path2;
}
bool GenericSocket::receive(int timeout, std::string &reply, int expected, bool raw)
{
	int length;
	int run;
	struct pollfd pfd = { .fd = fd, .events = POLLIN | POLLERR | POLLHUP, .revents = 0 };
	char buffer[8192];

	reply.clear();

	for(run = 8; run > 0; run--)
	{
		if(poll(&pfd, 1, timeout) != 1)
			return(false);

		if(pfd.revents & (POLLERR | POLLHUP))
			return(false);

		if((length = read(fd, buffer, sizeof(buffer) - 1)) < 0)
			return(false);

		if(length == 0)
		{
			if(reply.length() == 0) // ignore terminating empty udp packed from previous output
				continue;
			else
				break;
		}

		reply.append(buffer, (size_t)length);

		if((expected > 0) && (expected > length))
			expected -= length;
		else
			break;
	}

	if(reply.back() == '\n')
		reply.pop_back();

	if(!raw && (reply.back() == '\r'))
		reply.pop_back();

	return(true);
}

static std::string sha_hash_to_text(const unsigned char *hash)
{
	unsigned int current;
	std::stringstream hash_string;

	for(current = 0; current < SHA_DIGEST_LENGTH; current++)
		hash_string << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)hash[current];

	return(hash_string.str());
}
void SplitGltfAttribute(std::string attribute, std::string *semanticName, DWORD *semanticIndex)
{
    *semanticIndex = 0;

    if (isdigit(attribute.back()))
    {
        *semanticIndex = attribute.back() - '0';

        attribute.pop_back();
        if (attribute.back() == '_')
            attribute.pop_back();
    }

    *semanticName = attribute;
}
Example #15
0
bool attributeHasAnnotation(
    const std::string& annotation,
    const std::string& attributeName,
    std::string* comment) {
    // Unqualified actions must compare directly e.g. we don't want to return a match for 
    // for 'CAPA:suppress' when the annotation is 'CAPA::suppress[foo]'
    if(attributeName.find('[') == std::string::npos) {
        return attributeName == annotation;
    }
    
    // Otherwise, check if the attributeName is a prefix of the annotation
    // We need to check prefix and not equality in case there's a comment
    if(annotation.length() < attributeName.length() ||
        !std::equal(attributeName.begin(), attributeName.end(), annotation.begin())) {
        return false;
    }
    // The attributes match.
    // Try to pick out a comment if we need to
    if(comment != nullptr) {
        const auto commentStart = annotation.find('[', attributeName.length());
    
        if(commentStart != std::string::npos && annotation.back() == ']') {
            *comment =
               annotation.substr(commentStart + 1, annotation.length() - commentStart - 2);
        }
    }
    return true;
}
Example #16
0
		//-----------------------------------------------------------------//
		bool initialize(const std::string& root) {
			root_path_ = root;
			if(!root_path_.empty()) {
				if(root_path_.back() != '/') root_path_ += '/';
				if(!utils::is_directory(root)) {
					std::cerr << "Warrning: fontfile path is not directory (" <<
						root << ")" << std::endl;
					return false;
				}
			} else {
				std::cerr << "Warrning: fontfile root path to empty." << std::endl;
				return false;
			}

			// make home path
			auto p = getenv("HOME");
			if(p != nullptr) {
				home_path_ = p;
				home_path_ += '/';
			}

			FT_Error error = FT_Init_FreeType(&library_);
			if(error) {
				std::cerr << "FT Library init error: " << static_cast<int>(error) << std::endl;
				return false;
			}

			double	angle = (0.0 / 360) * 2.0 * 3.14159265398979;
			matrix_.xx = static_cast<FT_Fixed>( cos( angle ) * 0x10000L );
			matrix_.xy = static_cast<FT_Fixed>(-sin( angle ) * 0x10000L );
			matrix_.yx = static_cast<FT_Fixed>( sin( angle ) * 0x10000L );
			matrix_.yy = static_cast<FT_Fixed>( cos( angle ) * 0x10000L );
			return true;
		}
Example #17
0
 std::string lastDigit(std::string const& encoding) const{
   if(encoding.empty()){
     return "";
   }
   //return encoding.substr(encoding.length()-1);
   return std::string(1, encoding.back());
 }
Example #18
0
bool addon_filename_legal(const std::string& name)
{
	if(name.empty() || name.back() == '.' ||
	   name.find("..") != std::string::npos ||
	   name.size() > 255) {
		return false;
	} else {
		// NOTE: We can't use filesystem::base_name() here, since it returns
		//       the filename up to the *last* dot. "CON.foo.bar" in
		//       "CON.foo.bar.baz" is still redirected to "CON" on Windows;
		//       the base_name() approach would cause the name to not match
		//       any entries on our blacklist.
		//       Do also note that we're relying on the next check after this
		//       to flag the name as illegal if it contains a ':' -- a
		//       trailing colon is a valid way to refer to DOS device names,
		//       meaning that e.g. "CON:" is equivalent to "CON".
		const std::string stem = boost::algorithm::to_upper_copy(name.substr(0, name.find('.')), std::locale::classic());
		if(dos_device_names.find(stem) != dos_device_names.end()) {
			return false;
		}

		const ucs4::string name_ucs4 = unicode_cast<ucs4::string>(name);
		const std::string name_utf8 = unicode_cast<utf8::string>(name_ucs4);
		if(name != name_utf8){ // name is invalid UTF-8
			return false;
		}
		return std::find_if(name_ucs4.begin(), name_ucs4.end(), addon_filename_ucs4char_illegal()) == name_ucs4.end();
	}
}
Example #19
0
bool TRPLoader::Install(std::string dest, bool show)
{
	if (!trp_f.IsOpened())
	{
		return false;
	}

	if (!dest.empty() && dest.back() != '/')
	{
		dest += '/';
	}

	if (!Emu.GetVFS().ExistsDir(dest))
	{
		Emu.GetVFS().CreateDir(dest);
	}

	for (const TRPEntry& entry : m_entries)
	{
		char* buffer = new char [(u32)entry.size];
		trp_f.Seek(entry.offset);
		trp_f.Read(buffer, entry.size);
		vfsFile(dest + entry.name, fom::rewrite).Write(buffer, entry.size);
		delete[] buffer;
	}

	return true;
}
Example #20
0
std::string Model::cleanNamespaceTrailingChars(std::string ns) {
    static const std::set<char> IGNORED_LAST_CHARS = {'#', ':', '/'};
    if ( IGNORED_LAST_CHARS.count(ns.back()) ) {
        ns.pop_back();
    }
    return ns;
}
Example #21
0
 bool check()
 {
     CHECK(value.size() == 300);
     CHECK(value.front() == 'b' && value.back() == 'b');
     CHECK(i_wanna_be_big[0] == 'k' && i_wanna_be_big[50] == 'k');
     return true;
 }
Example #22
0
	bool fortifiedString(const std::string & s)
	{
		if (isDigit(s))
			return true ;
		linbox_check(!s.empty());
		return s.front() == '\"' && s.back() ==  '\"' ;
	}
Example #23
0
std::pair<std::string, std::string> spool_info::add_file(std::string filename,
                                                         uid_t uid) {
  int id = ++num_files;
  if (!free_ids.empty()) {
    // If there's an id in the pool of free ids, use it.
    id = free_ids.back();
    free_ids.pop_back();
  }

  // Make a unique filename based on its id. Appending the id is fine.
  // That's because since ids are unique, two file names will never
  // end in the same character.

  if (filename == "/" || filename.empty()) {
    std::cout << filename << ": X Bad filename" << std::endl;
    return std::make_pair("", "");
  } else if (filename.back() == '/')
    filename.erase(filename.end() - 1);

  auto idx = filename.find_last_of('/');
  if (idx == std::string::npos)
    idx = 0;
  else
    idx++;
  auto unique_filename = filename.substr(idx) + "_" + std::to_string(id);
  files.insert(std::make_pair(std::to_string(id),
                              spool_info::file(unique_filename, uid)));
  return std::make_pair(std::to_string(id), unique_filename);
}
Example #24
0
		uint32_t install_(const std::string& fpath)
		{
			unit_map_cit cit = unit_map_.find(fpath);
			if(cit != unit_map_.end()) {  // find it !, To be not install.
				return 0;
			}

			auto tpath = strip_last_of_delimita_path(fpath);
			auto bpath = get_file_path(tpath);
			bpath += '/';

			unit_map_it it = unit_map_.find(bpath);
			if(it != unit_map_.end()) {
				unit_t& t = it->second;
				std::string name = get_file_name(tpath);
				if(fpath.back() == '/') name += '/';
				t.install_child(name);
			}

			uint32_t hnd = handle_set_.create();
			unit_t u;
			u.set_id(hnd);
			unit_map_.emplace(fpath, u);
			return hnd;
		}
Example #25
0
    std::string InProcClientWrapper::assembleSetResourceUri(std::string uri,
        const QueryParamsMap& queryParams)
    {
        if(uri.back() == '/')
        {
            uri.resize(uri.size()-1);
        }

        ostringstream paramsList;
        if(queryParams.size() > 0)
        {
            paramsList << '?';
        }

        for(auto& param : queryParams)
        {
            paramsList << param.first <<'='<<param.second<<';';
        }

        std::string queryString = paramsList.str();
        if(queryString.back() == ';')
        {
            queryString.resize(queryString.size() - 1);
        }

        std::string ret = uri + queryString;
        return ret;
    }
Example #26
0
char CreditCard::generateCheckSum(std::string numbers)
{
    unsigned int sum=0;
    bool toggle=true;
    unsigned int checkDigit=0;


    while(!numbers.empty())
    {
        unsigned int temp=numbers.back() - '0'; //saves last digit

        if (toggle)
        {
            temp= temp*2;

            if (temp>=10)
                temp=temp-9;
        }

        sum=sum+temp;

        toggle=!toggle;
        numbers.pop_back(); //deletes last digit
    }

    checkDigit= (sum*9)%10;

    return checkDigit+'0';
}
Example #27
0
bool Directory::mkpath(const std::string& path) {
    if(path.empty()) return false;

    /* If path contains trailing slash, strip it */
    if(path.back() == '/')
        return mkpath(path.substr(0, path.size()-1));

    /* If the directory exists, done */
    if(fileExists(path)) return true;

    /* If parent directory doesn't exist, create it */
    const std::string parentPath = Directory::path(path);
    if(!parentPath.empty() && !fileExists(parentPath) && !mkpath(parentPath)) return false;

    /* Create directory, return true if successfully created or already exists */

    /* Unix, Emscripten */
    #if defined(CORRADE_TARGET_UNIX) || defined(CORRADE_TARGET_EMSCRIPTEN)
    const int ret = mkdir(path.data(), 0777);
    return ret == 0;

    /* Windows (not Store/Phone) */
    #elif defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT)
    return CreateDirectory(path.data(), nullptr) != 0 || GetLastError() == ERROR_ALREADY_EXISTS;

    /* Not implemented elsewhere */
    #else
    Warning() << "Utility::Directory::mkdir(): not implemented on this platform";
    return false;
    #endif
}
Example #28
0
bool
OOFEMTXTDataReader :: giveRawLineFromInput(std :: ifstream &stream, int &lineNum, std :: string &line)
{
    //
    // reads one line from inputStream - for private use only.
    //
    do {
        lineNum++;
        std :: getline(stream, line);
        if ( !stream ) {
            return false;
        } if ( line.length() > 0 ) {
            if ( line.back() == '\\' ) {
                std :: string continuedLine;
                do {
                    lineNum++;
                    std :: getline(stream, continuedLine);
                    if ( !stream ) {
                        return false;
                    }
                    line.pop_back();
                    line += continuedLine;
                } while ( continuedLine.back() == '\\' );
            }
        }
    } while ( line.length() == 0 || line [ 0 ] == '#' ); // skip comments
    return true;
}
Example #29
0
void snap::Excerpt::highlight_word(std::string w) {
  if (w.size() == 0 || w == "*" || w == "**") { return; }
  bool pre_wild_card = false; bool post_wild_card = false;
  if (w.front() == '*') { pre_wild_card = true; }
  if (w.back() == '*') { post_wild_card = true; }
  this -> search_strings.push_back(w);
  std::string w_trimmed = boost::algorithm::trim_copy_if(w, boost::algorithm::is_any_of("*"));
  std::transform(w_trimmed.begin(), w_trimmed.end(), w_trimmed.begin(), ::tolower);
  std::string lower_text(text);
  std::transform(lower_text.begin(), lower_text.end(), lower_text.begin(), ::tolower);
  int offset = 0; int left_shift = 24; int right_shift = 7;
  int current_pos = 0;
  while ((current_pos = lower_text.find(w_trimmed, current_pos)) != -1) {
    bool highlight = true;
    if (current_pos != 0 && !pre_wild_card && !(isspace(lower_text[current_pos-1]) || ispunct(lower_text[current_pos-1]))) {
      highlight = false;
    }
    if (current_pos + w_trimmed.length() != lower_text.length() && 
        !post_wild_card && 
        !(isspace(lower_text[current_pos + w_trimmed.length()]) || ispunct(lower_text[current_pos + w_trimmed.length()]))) {
      highlight = false;
    }
    if (highlight) {
      (this -> text).insert(current_pos + offset, "<span style=\"color:red\">");
      offset += left_shift;
      (this -> text).insert(current_pos + w_trimmed.length() + offset, "</span>");
      offset += right_shift;
    }
    current_pos += w_trimmed.size();
  }
}
Example #30
0
void File::write_line(const std::string& line) const {
  if(good()){
    f_->write(line.c_str(), line.size());
    if (line.back() != '\n') 
      f_->write("\n", 1);
  }
}