Beispiel #1
0
static inline uint16_t bind_port(util::csview scheme, const uint16_t port_from_uri) noexcept {
  static const std::vector<std::pair<util::csview, uint16_t>> port_table
  {
    {"ftp",    21U},
    {"http",   80U},
    {"https",  443U},
    {"irc",    6667U},
    {"ldap",   389U},
    {"nntp",   119U},
    {"rtsp",   554U},
    {"sip",    5060U},
    {"sips",   5061U},
    {"smtp",   25U},
    {"ssh",    22U},
    {"telnet", 23U},
    {"ws",     80U},
    {"wss",    443U},
    {"xmpp",   5222U},
  };

  if (port_from_uri not_eq 0) return port_from_uri;

  const auto it = std::find_if(port_table.cbegin(), port_table.cend(), [scheme](const auto& _) {
      return icase_equal(_.first, scheme);
  });

  return (it not_eq port_table.cend()) ? it->second : 0xFFFFU;
}
Beispiel #2
0
void test_singletons(CompareT cmp, std::vector<T> values, direction M)
{
    std::cout << "Test singletons" << std::endl;

    die_unless(cmp(cmp.min_value(), cmp.max_value()));

    size_t pos_compares = 0;
    size_t neg_compares = 0;

    for (auto i1 = values.cbegin(); i1 != values.cend(); ++i1) {
        die_unless(!cmp(*i1, *i1));
        die_unless(cmp(*i1, cmp.max_value()));
        die_unless(cmp(cmp.min_value(), *i1));

        for (auto i2 = values.cbegin(); i2 != values.cend(); ++i2) {
            const bool expected = (M == direction::Less) ? (*i1 < *i2) : (*i1 > *i2);
            const bool compared = cmp(*i1, *i2);

            pos_compares += compared;
            neg_compares += !compared;

            die_unless(expected == compared);
        }
    }

    die_unless(pos_compares + values.size() == neg_compares);
}
Beispiel #3
0
/** A specialisation for bool to allow more, better values. */
bool CommandSystem::parseArgument(std::string &message, bool *result)
{
	const static std::vector<std::string> trueValues = { "on", "true", "yes", "1" };
	const static std::vector<std::string> allValues = { "on", "true", "yes", "1",
		"off", "false", "no", "0" };

	std::vector<std::string> possible = chooseWord(allValues, message);
	if (possible.empty())
		return false;

	// Look what possibilities were found
	bool foundTrue = false;
	bool foundFalse = false;
	for (const auto &p : possible)
	{
		if (std::find(trueValues.cbegin(), trueValues.cend(), p) != trueValues.cend())
			foundTrue = true;
		else
			foundFalse = true;
	}

	if (foundTrue && foundFalse)
		return false;
	*result = foundTrue;
	return true;
}
Beispiel #4
0
/**
 * Wyświetla informacje na ekranie.
 */
void printUI(unsigned int step,
             const std::vector<Conveyor *>& conveyors,
             const std::vector<Tank *>& tanks)
{
    using namespace std;
    clearScreen();
    cout << "Krok symulacji: " << step << '\n';

    // Wyświetl kilka przenosników
    cout << "Przenośniki:\n";
    int num = 15;
    for (auto it = conveyors.cbegin(); it != conveyors.cend() && num > 0; ++it) {
        Conveyor *c = *it;
        cout << setw(10) << c->name()
             << " (Q_we: " << setw(4) << c->m_chwilowaWydajnoscNaWejsciu << " t/h) ";
        (*it)->printMaterialDistribution(100); // Wyświetl odcinkami po 100 [m]
        cout << " (Q_wy: " << setw(4) << c->m_chwilowaWydajnoscNaWyjsciu << " t/h)\n";
        --num;
    }

    cout << endl;
    // Wyświetl kilka zbiorników
    cout << "Zbiorniki:\n";
    num = 5;
    for (auto it = tanks.cbegin(); it != tanks.cend() && num > 0; ++it) {
        cout << setw(10) << (*it)->name() << ' ';
        (*it)->printMaterialDistribution();
        --num;
    }
}
Beispiel #5
0
/** Add a keyword from it's definition
 *
 * @param  _lines : lines which define the keyword
 * @return keyword
 *
 * Returns a nullptr if keyword the keyword
 */
std::shared_ptr<Keyword>
KeyFile::add_keyword(const std::vector<std::string>& _lines,
                     int64_t _line_index)
{

  // find keyword name
  const auto it =
    std::find_if(_lines.cbegin(), _lines.cend(), [](const std::string& line) {
      return (line.size() > 0 && line[0] == '*');
    });

  if (it == _lines.cend())
    throw(std::invalid_argument(
      "Can not find keyword definition (line must begin with *)"));

  // determine type
  auto kw_type = Keyword::determine_keyword_type(*it);

  // do the thing
  auto kw = create_keyword(_lines, kw_type, _line_index);
  if (kw)
    keywords[kw->get_keyword_name()].push_back(kw);

  return kw;
}
Beispiel #6
0
SourceLocation VirtualCallsFromCTOR::containsVirtualCall(clang::CXXRecordDecl *classDecl, clang::Stmt *stmt, std::vector<Stmt*> &processedStmts)
{
    if (stmt == nullptr)
        return {};

    // already processed ? we don't want recurring calls
    if (std::find(processedStmts.cbegin(), processedStmts.cend(), stmt) != processedStmts.cend())
        return {};

    processedStmts.push_back(stmt);

    std::vector<CXXMemberCallExpr*> memberCalls;
    Utils::getChilds2<CXXMemberCallExpr>(stmt, memberCalls);

    for (CXXMemberCallExpr *callExpr : memberCalls) {
        CXXMethodDecl *memberDecl = callExpr->getMethodDecl();
        if (memberDecl == nullptr || dyn_cast<CXXThisExpr>(callExpr->getImplicitObjectArgument()) == nullptr)
            continue;

        if (memberDecl->getParent() == classDecl) {
            if (memberDecl->isPure()) {
                return callExpr->getLocStart();
            } else {
                if (containsVirtualCall(classDecl, memberDecl->getBody(), processedStmts).isValid())
                    return callExpr->getLocStart();
            }
        }
    }

    return {};
}
std::vector<uint8_t> fromBitsToBytes(const std::vector<uint8_t>& bitVec)
{
    std::vector<uint8_t> byteVec{};
    if (bitVec.size() % 8  != 0)  // The number of bits is not a multiple of 8
        return byteVec;

    // We make sure that each element is either a one or a zero
    auto it = std::find_if_not(bitVec.cbegin(), bitVec.cend(), [](uint8_t x) {
        return x == 0 || x == 1;
    });
    if (it == bitVec.cend())
    {
        // All the values were 0 or 1
        for(auto it8 = bitVec.cbegin(); it8 < bitVec.cend(); it8 += 8)
        {
            // We get all the bits one by one
            uint8_t tmp{};
            for(auto index = 0 ; index < 8; ++index)
            {
                tmp |= (*(it8 + index)) << index;
            }
            byteVec.push_back(tmp);
        }
    }


    return byteVec;
}
Beispiel #8
0
std::string getCommonParentPath(const std::vector<std::string> &paths)
{
	if(paths.size() == 0)
		return std::string();

	std::size_t maxCommonSize =
	        string_utils::getMaxCommonSize(paths.cbegin(), paths.cend());

	const char *refStart = paths.back().c_str();
	const char *refEnd = refStart + maxCommonSize;

	while(refStart != refEnd)
	{
		bool same = true;
		for(auto it = paths.cbegin(); it != paths.cend() - 1; ++it)
		{
			if(!std::equal(refStart, refEnd, it->c_str()))
			{
				same = false;
				break;
			}
		}

		if(same)
			break;

		--refEnd;
	}

	if(refStart == refEnd)
		return std::string();
	return std::string(refStart, refEnd);
}
types::DiscoveryEntryWithMetaInfo QosArbitrationStrategyFunction::select(
        const std::map<std::string, types::CustomParameter> customParameters,
        const std::vector<types::DiscoveryEntryWithMetaInfo>& discoveryEntries) const
{
    std::ignore = customParameters;
    auto selectedDiscoveryEntryIt = discoveryEntries.cend();
    std::int64_t highestPriority = types::ProviderQos().getPriority(); // get default value

    for (auto it = discoveryEntries.cbegin(); it != discoveryEntries.cend(); ++it) {
        const types::ProviderQos& providerQos = it->getQos();
        JOYNR_LOG_TRACE(logger(), "Looping over discoveryEntry: {}", it->toString());

        if (providerQos.getPriority() >= highestPriority) {
            selectedDiscoveryEntryIt = it;
            JOYNR_LOG_TRACE(logger(),
                            "setting selectedParticipantId to {}",
                            selectedDiscoveryEntryIt->getParticipantId());
            highestPriority = providerQos.getPriority();
        }
    }

    if (selectedDiscoveryEntryIt == discoveryEntries.cend()) {
        std::stringstream errorMsg;
        errorMsg << "There was more than one entry in capabilitiesEntries, but none of the "
                    "compatible entries had a priority >= " << types::ProviderQos().getPriority();
        JOYNR_LOG_WARN(logger(), errorMsg.str());
        throw exceptions::DiscoveryException(errorMsg.str());
    }

    return *selectedDiscoveryEntryIt;
}
void QEvalTmpResultCore::cartProductSorted(std::vector<std::pair<idx_t, idx_t>>& result, const std::vector<idx_t>& left, const std::vector<idx_t>& right)
{
	result.reserve(left.size()*right.size());
	std::vector<idx_t>::const_iterator lIter, rIter;
	for (lIter = left.cbegin(); lIter != left.cend(); lIter++) {
		for (rIter = right.cbegin(); rIter != right.cend(); rIter++) {
			result.push_back(std::make_pair(*lIter, *rIter));
		}
	}
	std::sort(result.begin(), result.end());
}
std::size_t
colidx(const std::vector<std::string> & colnames, const std::string & name)
{
    std::vector<std::string>::const_iterator found = std::find(colnames.cbegin(), colnames.cend(), name);
    if (found == colnames.cend())
    {
        std::cerr << "Bad column name: " << name << std::endl;
    }
    assert(found != colnames.cend());
    return found - colnames.cbegin();
}
Beispiel #12
0
        void broadcast_impl(std::vector<hpx::id_type> ids,
            hpx::util::function<void(hpx::id_type)> fun, std::size_t fan_out)
        {
            // Call some action for the fan_out first ids here ...
            std::vector<hpx::future<void> > broadcast_futures;
            broadcast_futures.reserve((std::min)(ids.size(), fan_out));
            for(std::size_t i = 0; i < (std::min)(fan_out, ids.size()); ++i)
            {
                broadcast_futures.push_back(
                    hpx::async(fun, ids[i])
                );
            }

            if(ids.size() > fan_out)
            {
                typedef std::vector<hpx::id_type>::const_iterator iterator;
                iterator begin = ids.cbegin() + fan_out;

                for(std::size_t i = 0; i < fan_out; ++i)
                {
                    std::size_t next_dist = (ids.size() - fan_out)/fan_out + 1;
                    iterator end
                        = ((i == fan_out-1) || ((std::distance(ids.cbegin() +
                            fan_out, begin) + next_dist) >= ids.size()))
                        ? ids.cend()
                        : begin + next_dist;

                    std::vector<hpx::id_type> next(begin, end);
                    if(next.size() > 0)
                    {
                        hpx::id_type dst = hpx::naming::get_locality_from_id(next[0]);

                        broadcast_futures.push_back(
                            hpx::async<broadcast_impl_action>(dst, std::move(next),
                                fun, fan_out)
                        );
                        /*
                        hpx::apply<broadcast_impl_action>(dst, std::move(next),
                        fun, fan_out);
                        */
                    }

                    if(end == ids.cend()) break;

                    begin = end;
                }
            }


            if(broadcast_futures.size() > 0)
            {
                hpx::wait_all(broadcast_futures);
            }
        }
std::vector<LogicalSessionId> LogicalSessionCacheImpl::listIds(
    const std::vector<SHA256Block>& userDigests) const {
    stdx::lock_guard<stdx::mutex> lk(_cacheMutex);
    std::vector<LogicalSessionId> ret;
    for (const auto& it : _activeSessions) {
        if (std::find(userDigests.cbegin(), userDigests.cend(), it.first.getUid()) !=
            userDigests.cend()) {
            ret.push_back(it.first);
        }
    }
    return ret;
}
Beispiel #14
0
std::vector<tpoint>
intersection(const std::vector<tpoint>& lhs, const std::vector<tpoint>& rhs)
{
	std::vector<tpoint> result;
	std::set_intersection(lhs.cbegin(),
						  lhs.cend(),
						  rhs.cbegin(),
						  rhs.cend(),
						  std::back_inserter(result));

	return result;
}
Beispiel #15
0
	boost::optional<const User&> find(const std::string & nick) const
	{
		auto result = std::find_if(
			users_alpha_.cbegin(),
			users_alpha_.cend(),
			[&nick, this](const User* u){
			return this->locale_(nick, u->nick);
		});
		if (result != users_alpha_.cend())
			return boost::optional<const User&>(*(*result));
		return boost::none;
	}
Beispiel #16
0
    void Mapper::setNames(const std::vector<std::string>& inNames, const std::vector<std::string>& outNames) {

        inToOutMapping_.clear();
        inSize_ = inNames.size();
        outSize_ = outNames.size();

        for (const auto& in : inNames) {
            auto it(std::find(outNames.cbegin(), outNames.cend(), in));
            if (it != outNames.cend())
                inToOutMapping_.push_back(std::distance(outNames.cbegin(), it));
            else inToOutMapping_.push_back(-1);
        }
    }
Beispiel #17
0
LocalToGlobalIndexMap::LocalToGlobalIndexMap(
    std::vector<MeshLib::MeshSubset>&& mesh_subsets,
    std::vector<int> const& global_component_ids,
    std::vector<int> const& variable_component_offsets,
    std::vector<MeshLib::Element*> const& elements,
    NumLib::MeshComponentMap&& mesh_component_map,
    LocalToGlobalIndexMap::ConstructorTag)
    : _mesh_subsets(std::move(mesh_subsets)),
      _mesh_component_map(std::move(mesh_component_map)),
      _variable_component_offsets(variable_component_offsets)
{
    // Each subset in the mesh_subsets represents a single component.
    if (_mesh_subsets.size() != global_component_ids.size())
        OGS_FATAL(
            "Number of mesh subsets is not equal to number of components. "
            "There are %d mesh subsets and %d components.",
            _mesh_subsets.size(), global_component_ids.size());

    for (int i = 0; i < static_cast<int>(global_component_ids.size()); ++i)
    {
        auto const& ms = _mesh_subsets[i];

        // For all MeshSubset in mesh_subsets and each element of that
        // MeshSubset save a line of global indices.
        std::size_t const mesh_id = ms.getMeshID();

        findGlobalIndices(elements.cbegin(), elements.cend(), ms.getNodes(),
                          mesh_id, global_component_ids[i], i);
    }
}
Beispiel #18
0
rcl_interfaces::msg::ListParametersResult
Node::list_parameters(
  const std::vector<std::string> & prefixes, uint64_t depth) const
{
  std::lock_guard<std::mutex> lock(mutex_);
  rcl_interfaces::msg::ListParametersResult result;

  // TODO(esteve): define parameter separator, use "." for now
  for (auto & kv : parameters_) {
    if (std::any_of(prefixes.cbegin(), prefixes.cend(), [&kv, &depth](const std::string & prefix) {
      if (kv.first == prefix) {
        return true;
      } else if (kv.first.find(prefix + ".") == 0) {
        size_t length = prefix.length();
        std::string substr = kv.first.substr(length);
        // Cast as unsigned integer to avoid warning
        return static_cast<uint64_t>(std::count(substr.begin(), substr.end(), '.')) < depth;
      }
      return false;
    }))
    {
      result.names.push_back(kv.first);
      size_t last_separator = kv.first.find_last_of('.');
      if (std::string::npos != last_separator) {
        std::string prefix = kv.first.substr(0, last_separator);
        if (std::find(result.prefixes.cbegin(), result.prefixes.cend(), prefix) ==
          result.prefixes.cend())
        {
          result.prefixes.push_back(prefix);
        }
      }
    }
  }
  return result;
}
Beispiel #19
0
    catchment_t run(parameter_t param) {
        catchment_t catchment_discharge(time_axis, 0.0);
        //shyft::time_axis::fixed_dt
        auto state_time_axis=time_axis;
        state_time_axis.n++;//add room for end-state
        size_t i = 0;
        for_each(model_cells.cbegin(), model_cells.cend(), [this, &i, &param, &catchment_discharge,&state_time_axis] (PTGSKCell d) {
            StateCollector<timeaxis> sc(state_time_axis);
            DischargeCollector<timeaxis> rc(1000*1000, time_axis);
            pt_gs_k::state_t s = state(i++);
            pt_gs_k::response_t r;

            pt_gs_k::run_pt_gs_k<shyft::timeseries::direct_accessor,pt_gs_k::response_t>(
                d.geo_cell_info(),
                param,
                time_axis,0,0,
                d.temperature(),
                d.precipitation(),
                d.wind_speed(),
                d.rel_hum(),
                d.radiation(),
                s,
                sc,
                rc);
            d.add_discharge(rc.avg_discharge, catchment_discharge, time_axis); // Aggregate discharge into the catchment
        });
        return catchment_discharge;
    }
/* Constructeur de chargement.*/
Joueur::Joueur(std::vector<int> const &id_armes_depart, Coordonnees pos_depart) : super(pos_depart), m_compteur_recharge(0), m_points_de_vie(100)
{
	// Initialisation des attributs.
	// Attributs hérités.
	m_vitesse_max = 4;
	// Attributs privés.
	for(int i = 0; i < NB_ACTIONS; i++)
	{
		m_actions[i] = false;
	}
	
	// Chargement des images du joueur.
	m_textures[HAUT] = new Texture("rsc/img/jeu/entites/joueur/joueur_haut.bmp");
	m_textures[HAUT_DROITE] = new Texture("rsc/img/jeu/entites/joueur/joueur_haut_droite.bmp");
	m_textures[DROITE] = new Texture("rsc/img/jeu/entites/joueur/joueur_droite.bmp");
	m_textures[BAS_DROITE] = new Texture("rsc/img/jeu/entites/joueur/joueur_bas_droite.bmp");
	m_textures[BAS] = new Texture("rsc/img/jeu/entites/joueur/joueur_bas.bmp");
	m_textures[BAS_GAUCHE] = new Texture("rsc/img/jeu/entites/joueur/joueur_bas_gauche.bmp");
	m_textures[GAUCHE] = new Texture("rsc/img/jeu/entites/joueur/joueur_gauche.bmp");
	m_textures[HAUT_GAUCHE] = new Texture("rsc/img/jeu/entites/joueur/joueur_haut_gauche.bmp");
	
	// Attribution de l'image de départ par défaut.
	m_image = m_textures[BAS];
	
	// Récupération des armes correspondants aux id donnés.
	for(std::vector<int>::const_iterator it = id_armes_depart.cbegin(); it != id_armes_depart.cend(); ++it)
	{
		m_armes_portees.emplace_back(Jeu::getArmeDepuisID(*it));
	}
	
	// Sélection automatique de la première arme portée.
	m_num_arme_selectionnee = 0;
	m_arme_selectionnee = &m_armes_portees.at(m_num_arme_selectionnee);
}
void verify_retry_results(wa::storage::retry_policy policy, web::http::status_code primary_status_code, web::http::status_code secondary_status_code, wa::storage::location_mode mode, std::function<std::chrono::milliseconds (int)> allowed_delta, std::vector<wa::storage::retry_info> expected_retry_info_list)
{
    auto initial_location = get_initial_location(mode);
    auto next_location = get_next_location(mode, initial_location);

    wa::storage::operation_context op_context;
    wa::storage::request_result result(utility::datetime::utc_now(),
        initial_location,
        web::http::http_response(initial_location == wa::storage::storage_location::secondary ? secondary_status_code : primary_status_code),
        false);

    int retry_count = 0;
    for (auto iter = expected_retry_info_list.cbegin(); iter != expected_retry_info_list.cend(); ++iter)
    {
        auto retry_info = policy.evaluate(wa::storage::retry_context(retry_count++, result, next_location, mode), op_context);

        CHECK(retry_info.should_retry());
        CHECK(iter->target_location() == retry_info.target_location());
        CHECK(iter->updated_location_mode() == retry_info.updated_location_mode());
        CHECK_CLOSE(iter->retry_interval().count(), retry_info.retry_interval().count(), allowed_delta(retry_count).count());

        std::this_thread::sleep_for(retry_info.retry_interval());

        result = wa::storage::request_result(utility::datetime::utc_now(),
            retry_info.target_location(),
            web::http::http_response(retry_info.target_location() == wa::storage::storage_location::secondary ? secondary_status_code : primary_status_code),
            false);
        mode = retry_info.updated_location_mode();
        next_location = get_next_location(mode, next_location);
    }

    auto retry_info = policy.evaluate(wa::storage::retry_context(retry_count++, result, next_location, mode), op_context);
    CHECK(!retry_info.should_retry());
}
 tmp_pipes(int nb_pipes):
 tmpdir_(create_tmp_dir()),
 pipes_(create_pipes(tmpdir_, nb_pipes))
 {
   for(auto it = pipes_.cbegin(); it != pipes_.cend(); ++it)
     pipes_paths_.push_back(it->c_str());
 }
Beispiel #23
0
// TODO: refactor
DirectoryDescriptorIterator FileSystem::getLastPathElementHandle(const std::vector<std::string> &path, bool isAbsolute)
{
    descriptorIndex_tp currentHandle = isAbsolute ? header().rootDirectoryDescriptor : currentDirectory();

    // TODO: symbolic link and check symbolic link loop

//    for(const string &currentName: path) {
    for(auto currentName = path.cbegin(); ; ++currentName) {
        DirectoryDescriptorIterator dIt = getDirectoryDescriptorIterator(currentHandle);
        if(currentName == path.cend()) {
            return dIt;
        }
        bool found = false;
        while(dIt.hasNext()) {
            ++dIt;
            if(dIt->name(header().filenameLength) == *currentName) {
                found = true;
                currentHandle = dIt->descriptor;
                break;
            }
        }
        if(!found) {
            throw file_system_exception("No such file or directory.");
        }
    }
}
Beispiel #24
0
void min_heap::print() {
  cout << "\nElements : [ ";
  for(auto itr = _elements.cbegin(); itr != _elements.cend(); ++itr) {
    cout << *itr << ",";
  }
  cout << "\b ]" << endl;
}
Beispiel #25
0
PLUGIN_EXPORT void Initialize(void** data, void* rm)
{
	MeasureData* measure = new MeasureData(RmGetMeasureName(rm));
	*data = measure;
	g_Measures.push_back(measure);

	void* skin = RmGetSkin(rm);

	LPCWSTR str = RmReadString(rm, L"Folder", L"", FALSE);
	if (*str == L'[')
	{
		int len = wcslen(str);
		for (auto iter = g_Measures.cbegin(); iter != g_Measures.cend(); ++iter)
		{
			if ((*iter)->folder &&
				(*iter)->folder->GetSkin() == skin &&
				wcsncmp(&str[1], (*iter)->section, len - 2) == 0)
			{
				measure->folder = (*iter)->folder;
				measure->folder->AddInstance();
				return;
			}
		}
	}

	measure->folder = new CFolderInfo(skin);
	measure->parent = true;
}
Beispiel #26
0
void FileUtils::setSearchResolutionsOrder(const std::vector<std::string>& searchResolutionsOrder)
{
    bool existDefault = false;
    _fullPathCache.clear();
    _searchResolutionsOrderArray.clear();
    for(auto iter = searchResolutionsOrder.cbegin(); iter != searchResolutionsOrder.cend(); ++iter)
    {
        std::string resolutionDirectory = *iter;
        if (!existDefault && resolutionDirectory == "")
        {
            existDefault = true;
        }
        
        if (resolutionDirectory.length() > 0 && resolutionDirectory[resolutionDirectory.length()-1] != '/')
        {
            resolutionDirectory += "/";
        }
        
        _searchResolutionsOrderArray.push_back(resolutionDirectory);
    }
    if (!existDefault)
    {
        _searchResolutionsOrderArray.push_back("");
    }
}
Beispiel #27
0
void FileUtils::setSearchPaths(const std::vector<std::string>& searchPaths)
{
    bool existDefaultRootPath = false;
    
    _fullPathCache.clear();
    _searchPathArray.clear();
    for (auto iter = searchPaths.cbegin(); iter != searchPaths.cend(); ++iter)
    {
        std::string prefix;
        std::string path;
        
        if (!isAbsolutePath(*iter))
        { // Not an absolute path
            prefix = _defaultResRootPath;
        }
        path = prefix + (*iter);
        if (path.length() > 0 && path[path.length()-1] != '/')
        {
            path += "/";
        }
        if (!existDefaultRootPath && path == _defaultResRootPath)
        {
            existDefaultRootPath = true;
        }
        _searchPathArray.push_back(path);
    }
    
    if (!existDefaultRootPath)
    {
        //CCLOG("Default root path doesn't exist, adding it.");
        _searchPathArray.push_back(_defaultResRootPath);
    }
}
int32_t  TDvbDb::InsertDescriptor(const char* tableName, const int64_t& fkey, const std::vector<TMpegDescriptor>& descList)
{
  std::lock_guard<std::mutex> lock(DbMutex);
  int32_t rc(-1);

  if (tableName && fkey > 0 && !descList.empty()) {
    // Using 'INSERT OR IGNORE' so duplicate entries do not trigger an exception or error.
    string cmdStr("INSERT OR IGNORE INTO ");
    string tableStr(tableName);
    cmdStr += tableStr;
    cmdStr += " (fkey, descriptor_id, descriptor) VALUES (?, ?, ?);";
    try {
      for (auto it = descList.cbegin(); it != descList.cend(); ++it) {
        const TMpegDescriptor& md = *it;
        command cmd(Sqlite3ppWrapper, cmdStr.c_str());
        cmd.binder() << static_cast<long long int>(fkey) << static_cast<uint8_t>(md.GetDescriptorTag());
        const std::vector<uint8_t>& descData = md.GetDescriptorData();
        cmd.bind(3, static_cast<const void*>(descData.data()), descData.size());
        cmd.execute();
        rc = 0;
      }
    }
    catch (exception& ex) {
      OS_LOG(DVB_DEBUG, "<%s> - Exception: %s cmd: %s\n", __FUNCTION__, ex.what(), cmdStr.c_str());
    }
    catch (...) {
      OS_LOG(DVB_ERROR,  "<%s> - Unknown Exception: cmd: %s\n", __FUNCTION__, cmdStr.c_str());
    }
  }
  return rc;
}
Beispiel #29
0
int main() {
	try {
		lua::State state;
		lua::callback::registerFunctions(state, funcTable.cbegin(), funcTable.cend());

		std::string i1;
		double d1;
		float f1;
		boost::optional<int> optInt;
		lua::types::AnyRef r;

		state.doFile("../test.lua");
		//state.setGlobal("phasor_version", 202);
		lua::Caller<std::string, double, float, lua::types::AnyRef, boost::optional<some_random_type>> c(state);
		boost::optional<some_random_type> vo;
		std::tie(i1, d1, f1, r, vo) = c.call<lua::Push, MyPop>("test_func", std::make_tuple(1, 2, 3));
		if (!c.hasError()) {
			cout << i1 << " " << d1 << " " << f1 << endl;
			if (optInt) cout << "opt: " << *optInt << endl;

			c.call<lua::Push, MyPop>("test_func1", std::make_tuple(std::ref(r)));
		} else {
			cout << "return values ignored" << endl;
		}
	} catch (std::exception& e) {
		cout << e.what() << endl;
	}
	//std::tuple<int, int> a;
	//std::get<0>(a) = 4;
	//std::tuple_element<0, std::tuple<int, int>>::type b = "15";
	//cout << std::get<1>(a);	
}
void blob_service_test_base_with_objects_to_delete::check_container_list(const std::vector<azure::storage::cloud_blob_container>& list, const utility::string_t& prefix, bool check_found)
{
    auto container_list_sorted = std::is_sorted(list.cbegin(), list.cend(), [](const azure::storage::cloud_blob_container& a, const azure::storage::cloud_blob_container& b)
    {
        return a.name() < b.name();
    });
    CHECK(container_list_sorted);

    std::vector<azure::storage::cloud_blob_container> containers(m_containers_to_delete);

    for (auto list_iter = list.begin(); list_iter != list.end(); ++list_iter)
    {
        bool found = false;
        for (auto iter = containers.begin(); iter != containers.end(); ++iter)
        {
            if (iter->name() == list_iter->name())
            {
                auto index_str = list_iter->metadata().find(U("index"));
                CHECK(index_str != list_iter->metadata().end());
                CHECK_UTF8_EQUAL(iter->name(), prefix + index_str->second);
                containers.erase(iter);
                found = true;
                break;
            }
        }
        if (check_found)
        {
            CHECK(found);
        }
    }
    CHECK(containers.empty());
}