コード例 #1
0
/**
 * Insert the name(s) of an element into its data structures
 * after performing some sanitation and validity checking.
 *
 * @param id node, way, or relation id (determined by element_type)
 * @param element_type element type to notify if name belongs to a node, way, or relation
 * @param realworld_type real-world type of element to process
 * @param name_set a collection of key-value pairs of names such as "name:de=Oskars Schleussen"
 */
void insertNames(uint64_t id, OSMElement::ElementType element_type, OSMElement::RealWorldType realworld_type, const std::map<std::string, std::string> &name_set) {
    bool first_name = true;
    std::string best_name; ///< if multiple names are available, record the 'best' name
    const OSMElement element(id, element_type, realworld_type);
    std::set<std::string> known_names; ///< track names to avoid duplicate insertions
    static const std::set<std::string> ignored_country_codes = {"ab", "ace", "af", "ak", "als", "am", "an", "ang", "ar", "arc", "arz", "ast", "ay", "az", "ba", "bar", "bat-smg", "bcl", "be", "be-tarask", "bg", "bi", "bm", "bn", "bo", "bpy", "br", "bs", "bxr", "ca", "cdo", "ce", "ceb", "chr", "chy", "ckb", "co", "crh", "cs", "csb", "cu", "cv", "cy", "da", "de", "diq", "dsb", "dv", "dz", "ee", "el", "en", "eo", "es", "et", "eu", "ext", "fa", "ff", "fi", "fiu-vro", "fo", "fr", "frp", "frr", "fur", "fy", "ga", "gag", "gan", "gd", "gl", "gn", "gu", "gv", "ha", "hak", "haw", "he", "hi", "hif", "hr", "hsb", "ht", "hu", "hy", "ia", "id", "ie", "ig", "ilo", "io", "is", "it", "iu", "ja", "jbo", "jv", "ka", "kaa", "kab", "kbd", "kg", "ki", "kk", "kl", "km", "kn", "ko", "koi", "krc", "ks", "ksh", "ku", "kv", "kw", "ky", "la", "lad", "lb", "lez", "lg", "li", "lij", "lmo", "ln", "lo", "lt", "ltg", "lv", "mdf", "mg", "mhr", "mi", "mk", "ml", "mn", "mr", "mrj", "ms", "mt", "my", "myv", "mzn", "na", "nah", "nan", "nap", "nb", "nds", "nds-nl", "ne", "new", "nl", "nn", "no", "nov", "nrm", "nv", "oc", "om", "or", "os", "pa", "pag", "pam", "pap", "pcd", "pdc", "pih", "pl", "pms", "pnb", "pnt", "ps", "pt", "qu", "rm", "rmy", "rn", "ro", "roa-rup", "roa-tara", "ru", "rue", "rw", "sa", "sah", "sc", "scn", "sco", "se", "sg", "sh", "si", "simple", "sk", "sl", "sm", "sme", "sn", "so", "sq", "sr", "sr-Latn", "srn", "ss", "st", "stq", "su", "sw", "szl", "ta", "te", "tet", "tg", "th", "ti", "tk", "tl", "to", "tpi", "tr", "ts", "tt", "tw", "tzl", "udm", "ug", "uk", "ur", "uz", "vec", "vep", "vi", "vls", "vo", "wa", "war", "wo", "wuu", "xal", "xmf", "yi", "yo", "yue", "za", "zea", "zh", "zh-classical", "zh-min-nan", "zh_pinyin", "zh_py", "zh_pyt", "zh-simplified", "zh-yue", "zu"};

    for (auto name_pair : name_set) {
        auto const &name_key = name_pair.first;
        auto const &name_value = name_pair.second;
        /// Consider only names of length 2 or longer
        if (name_value.length() < 2) continue;

        if (first_name && element_type == OSMElement::Node) {
            node2Coord->increaseCounter(id);
            first_name = false;
        }

        if (name_key.find(":") != std::string::npos) {
            /// Name has components, split and check
            std::vector<std::string> name_key_components;
            split(name_key, ':', name_key_components);
            if (name_key_components.size() >= 2) {
                const auto components_back(name_key_components.back());
                if (ignored_country_codes.find(components_back) != ignored_country_codes.cend()) {
                    /// This is a language-specific name, such as 'name:en', but not 'name:sv' (Swedish), so skip it
                    continue;
                }
            }
        }

        /// Only unique names
        if (known_names.find(name_value) != known_names.cend())
            continue;
        else
            known_names.insert(name_value);

        if (best_name.empty())
            best_name = name_value;
        else if (name_key == "name")
            best_name = name_value;

        const bool result = swedishTextTree->insert(name_value, element);
        if (!result)
            Error::warn("Cannot insert %s=%s for id=%llu", name_key.c_str(), name_value.c_str(), id);
    }

    if (!best_name.empty()) {
        bool result = false;
        switch (element_type) {
        case OSMElement::Node: result = nodeNames->insert(id, WriteableString(best_name)); break;
        case OSMElement::Way: result = wayNames->insert(id, WriteableString(best_name)); break;
        case OSMElement::Relation: result = relationNames->insert(id, WriteableString(best_name)); break;
        case OSMElement::UnknownElementType: break;
        }
        if (!result)
            Error::warn("Cannot insert name %s for %s", best_name.c_str(), element.operator std::string().c_str());
    }
}
コード例 #2
0
    inline NodeId(
        const Input &input, const Input &end
    ): NodeTextOrError<E>(input, end) {
        static const std::set<std::string> keywords = {
            "div", "mod", "shl", "shr", "ushr", "rol", "ror",
            "or", "xor", "and", "not", "is", "in", "out", "var"
        };

        succeed = keywords.find(std::string(input, end)) == keywords.cend();
    }
コード例 #3
0
ファイル: index-io.cpp プロジェクト: daboyuka/PIQUE
bool IndexPartitionIO::read_regions(const std::set< region_id_t > &regions_to_read, std::map< region_id_t, boost::shared_ptr< RegionEncoding > > &regions) {
	// Validate all regions to read
	const region_count_t num_regions = get_num_regions();
	for (auto it = regions_to_read.cbegin(); it != regions_to_read.cend(); it++) {
		const region_id_t region = *it;
		if (region >= num_regions)
			return false;
	}

	// Read the missing bins, fail if this fails
	return read_regions_impl(regions_to_read, regions);
}
コード例 #4
0
void BlackListWindow::RefreshBlackList()
{
	m_black_list->RemoveAll();

	const std::set<std::string> black_list = MuteBlackService::GetInstance()->GetBlackList();
	std::list<std::string> account_list(black_list.cbegin(), black_list.cend());

	std::list<nim::UserNameCard> uinfos;
	UserService::GetInstance()->GetUserInfos(account_list, uinfos);
	for (auto iter = uinfos.cbegin(); iter != uinfos.cend(); iter++)
		AddBlackListMember(*iter);
}
コード例 #5
0
ファイル: Detector.cpp プロジェクト: bponyk/OpticSensors
void Detector::CollisionDetected(const std::set<std::shared_ptr<IObject>>& i_objects)
  {
  std::for_each(i_objects.cbegin(), i_objects.cend(), [this](ObjectPtr i_object)
    {
    if (typeid(*i_object.get()) == typeid(Ray))
      {
      m_detector_state = DetectorState::DS_Active;
      m_elapsed_time = 0;
      m_body_color = Color(250, 0, 0, 250);
      }
    });
  }
コード例 #6
0
ファイル: euler.hpp プロジェクト: jemele/projecteuler
std::map<T,std::size_t> factors(T n, const std::set<T> & p)
{
    std::map<T,std::size_t> f;
    auto bound = std::sqrt(n) + 1;
    for (auto i = p.cbegin(); (i != p.cend()) || (*i > bound); ++i) {
        const auto prime = *i;
        std::size_t order = 0;
        for (auto d = n; (d % prime) == 0; d /= prime) {
            ++order;
        }
        if (order) {
            f[prime] = order;
        }
    }
    return f;
}
コード例 #7
0
ファイル: pass.hpp プロジェクト: gartenriese2/glengine
		void addObjects(std::set<unsigned long> set) { m_objects.insert(set.cbegin(), set.cend()); }
コード例 #8
0
ファイル: iterator.pass.cpp プロジェクト: Aj0Ay/libcxx
int main()
{
    {
        typedef int V;
        V ar[] =
        {
            1,
            1,
            1,
            2,
            2,
            2,
            3,
            3,
            3,
            4,
            4,
            4,
            5,
            5,
            5,
            6,
            6,
            6,
            7,
            7,
            7,
            8,
            8,
            8
        };
        std::set<int> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
        assert(std::distance(m.begin(), m.end()) == m.size());
        assert(std::distance(m.rbegin(), m.rend()) == m.size());
        std::set<int>::iterator i;
        i = m.begin();
        std::set<int>::const_iterator k = i;
        assert(i == k);
        for (int j = 1; j <= m.size(); ++j, ++i)
            assert(*i == j);
    }
    {
        typedef int V;
        V ar[] =
        {
            1,
            1,
            1,
            2,
            2,
            2,
            3,
            3,
            3,
            4,
            4,
            4,
            5,
            5,
            5,
            6,
            6,
            6,
            7,
            7,
            7,
            8,
            8,
            8
        };
        const std::set<int> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
        assert(std::distance(m.begin(), m.end()) == m.size());
        assert(std::distance(m.cbegin(), m.cend()) == m.size());
        assert(std::distance(m.rbegin(), m.rend()) == m.size());
        assert(std::distance(m.crbegin(), m.crend()) == m.size());
        std::set<int>::const_iterator i;
        i = m.begin();
        for (int j = 1; j <= m.size(); ++j, ++i)
            assert(*i == j);
    }
#if TEST_STD_VER >= 11
    {
        typedef int V;
        V ar[] =
        {
            1,
            1,
            1,
            2,
            2,
            2,
            3,
            3,
            3,
            4,
            4,
            4,
            5,
            5,
            5,
            6,
            6,
            6,
            7,
            7,
            7,
            8,
            8,
            8
        };
        std::set<int, std::less<int>, min_allocator<int>> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
        assert(std::distance(m.begin(), m.end()) == m.size());
        assert(std::distance(m.rbegin(), m.rend()) == m.size());
        std::set<int, std::less<int>, min_allocator<int>>::iterator i;
        i = m.begin();
        std::set<int, std::less<int>, min_allocator<int>>::const_iterator k = i;
        assert(i == k);
        for (int j = 1; j <= m.size(); ++j, ++i)
            assert(*i == j);
    }
    {
        typedef int V;
        V ar[] =
        {
            1,
            1,
            1,
            2,
            2,
            2,
            3,
            3,
            3,
            4,
            4,
            4,
            5,
            5,
            5,
            6,
            6,
            6,
            7,
            7,
            7,
            8,
            8,
            8
        };
        const std::set<int, std::less<int>, min_allocator<int>> m(ar, ar+sizeof(ar)/sizeof(ar[0]));
        assert(std::distance(m.begin(), m.end()) == m.size());
        assert(std::distance(m.cbegin(), m.cend()) == m.size());
        assert(std::distance(m.rbegin(), m.rend()) == m.size());
        assert(std::distance(m.crbegin(), m.crend()) == m.size());
        std::set<int, std::less<int>, min_allocator<int>>::const_iterator i;
        i = m.begin();
        for (int j = 1; j <= m.size(); ++j, ++i)
            assert(*i == j);
    }
#endif
#if _LIBCPP_STD_VER > 11
    { // N3644 testing
        typedef std::set<int> C;
        C::iterator ii1{}, ii2{};
        C::iterator ii4 = ii1;
        C::const_iterator cii{};
        assert ( ii1 == ii2 );
        assert ( ii1 == ii4 );

        assert (!(ii1 != ii2 ));

        assert ( (ii1 == cii ));
        assert ( (cii == ii1 ));
        assert (!(ii1 != cii ));
        assert (!(cii != ii1 ));
    }
#endif
}
コード例 #9
0
template <typename PointInT, typename PointOutT> void
pcl::ROPSEstimation <PointInT, PointOutT>::computeLRF (const PointInT& point, const std::set <unsigned int>& local_triangles, Eigen::Matrix3f& lrf_matrix) const
{
  const unsigned int number_of_triangles = static_cast <unsigned int> (local_triangles.size ());

  std::vector<Eigen::Matrix3f, Eigen::aligned_allocator<Eigen::Matrix3f> > scatter_matrices (number_of_triangles);
  std::vector <float> triangle_area (number_of_triangles);
  std::vector <float> distance_weight (number_of_triangles);

  float total_area = 0.0f;
  const float coeff = 1.0f / 12.0f;
  const float coeff_1_div_3 = 1.0f / 3.0f;

  Eigen::Vector3f feature_point (point.x, point.y, point.z);

  unsigned int i_triangle = 0;
  for (auto it = local_triangles.cbegin (); it != local_triangles.cend (); it++, i_triangle++)
  {
    Eigen::Vector3f pt[3];
    for (unsigned int i_vertex = 0; i_vertex < 3; i_vertex++)
    {
      const unsigned int index = triangles_[*it].vertices[i_vertex];
      pt[i_vertex] (0) = surface_->points[index].x;
      pt[i_vertex] (1) = surface_->points[index].y;
      pt[i_vertex] (2) = surface_->points[index].z;
    }

    const float curr_area = ((pt[1] - pt[0]).cross (pt[2] - pt[0])).norm ();
    triangle_area[i_triangle] = curr_area;
    total_area += curr_area;

    distance_weight[i_triangle] = std::pow (support_radius_ - (feature_point - (pt[0] + pt[1] + pt[2]) * coeff_1_div_3).norm (), 2.0f);

    Eigen::Matrix3f curr_scatter_matrix;
    curr_scatter_matrix.setZero ();
    for (const auto &i_pt : pt)
    {
      Eigen::Vector3f vec = i_pt - feature_point;
      curr_scatter_matrix += vec * (vec.transpose ());
      for (const auto &j_pt : pt)
        curr_scatter_matrix += vec * ((j_pt - feature_point).transpose ());
    }
    scatter_matrices[i_triangle] = coeff * curr_scatter_matrix;
  }

  if (std::abs (total_area) < std::numeric_limits <float>::epsilon ())
    total_area = 1.0f / total_area;
  else
    total_area = 1.0f;

  Eigen::Matrix3f overall_scatter_matrix;
  overall_scatter_matrix.setZero ();
  std::vector<float> total_weight (number_of_triangles);
  const float denominator = 1.0f / 6.0f;
  for (unsigned int i_triangle = 0; i_triangle < number_of_triangles; i_triangle++)
  {
    float factor = distance_weight[i_triangle] * triangle_area[i_triangle] * total_area;
    overall_scatter_matrix += factor * scatter_matrices[i_triangle];
    total_weight[i_triangle] = factor * denominator;
  }

  Eigen::Vector3f v1, v2, v3;
  computeEigenVectors (overall_scatter_matrix, v1, v2, v3);

  float h1 = 0.0f;
  float h3 = 0.0f;
  i_triangle = 0;
  for (auto it = local_triangles.cbegin (); it != local_triangles.cend (); it++, i_triangle++)
  {
    Eigen::Vector3f pt[3];
    for (unsigned int i_vertex = 0; i_vertex < 3; i_vertex++)
    {
      const unsigned int index = triangles_[*it].vertices[i_vertex];
      pt[i_vertex] (0) = surface_->points[index].x;
      pt[i_vertex] (1) = surface_->points[index].y;
      pt[i_vertex] (2) = surface_->points[index].z;
    }

    float factor1 = 0.0f;
    float factor3 = 0.0f;
    for (const auto &i_pt : pt)
    {
      Eigen::Vector3f vec = i_pt - feature_point;
      factor1 += vec.dot (v1);
      factor3 += vec.dot (v3);
    }
    h1 += total_weight[i_triangle] * factor1;
    h3 += total_weight[i_triangle] * factor3;
  }

  if (h1 < 0.0f) v1 = -v1;
  if (h3 < 0.0f) v3 = -v3;

  v2 = v3.cross (v1);

  lrf_matrix.row (0) = v1;
  lrf_matrix.row (1) = v2;
  lrf_matrix.row (2) = v3;
}
コード例 #10
0
ファイル: MDHistoWorkspace.cpp プロジェクト: liyulun/mantid
/** Obtain coordinates for a line plot through a MDWorkspace.
 * Cross the workspace from start to end points, recording the signal along the
 *lin at either bin boundaries, or halfway between bin boundaries (which is bin
 *centres if the line is dimension aligned). If recording halfway values then
 *omit points in masked bins.
 *
 * @param start :: coordinates of the start point of the line
 * @param end :: coordinates of the end point of the line
 * @param normalize :: how to normalize the signal
 * @returns :: LinePlot with x as the boundaries of the bins, relative
 * to start of the line, y set to the normalized signal for each bin with
 * Length = length(x) - 1 and e as the error vector for each bin.
 * @param bin_centres :: if true then record points halfway between bin
 *boundaries, otherwise record on bin boundaries
 */
IMDWorkspace::LinePlot MDHistoWorkspace::getLinePoints(
    const Mantid::Kernel::VMD &start, const Mantid::Kernel::VMD &end,
    Mantid::API::MDNormalization normalize, const bool bin_centres) const {
  LinePlot line;

  size_t nd = this->getNumDims();
  if (start.getNumDims() != nd)
    throw std::runtime_error("Start point must have the same number of "
                             "dimensions as the workspace.");
  if (end.getNumDims() != nd)
    throw std::runtime_error(
        "End point must have the same number of dimensions as the workspace.");

  // Unit-vector of the direction
  VMD dir = end - start;
  const auto length = dir.normalize();

// Vector with +1 where direction is positive, -1 where negative
#define sgn(x) ((x < 0) ? -1.0f : ((x > 0.) ? 1.0f : 0.0f))
  VMD dirSign(nd);
  for (size_t d = 0; d < nd; d++) {
    dirSign[d] = sgn(dir[d]);
  }
  const size_t BADINDEX = size_t(-1);

  // Dimensions of the workspace
  boost::scoped_array<size_t> index(new size_t[nd]);
  boost::scoped_array<size_t> numBins(new size_t[nd]);
  for (size_t d = 0; d < nd; d++) {
    IMDDimension_const_sptr dim = this->getDimension(d);
    index[d] = BADINDEX;
    numBins[d] = dim->getNBins();
  }

  const std::set<coord_t> boundaries =
      getBinBoundariesOnLine(start, end, nd, dir, length);

  if (boundaries.empty()) {
    this->makeSinglePointWithNaN(line.x, line.y, line.e);

    // Require x.size() = y.size()+1 if recording bin boundaries
    if (!bin_centres)
      line.x.push_back(length);

    return line;
  } else {
    // Get the first point
    std::set<coord_t>::iterator it;
    it = boundaries.cbegin();

    coord_t lastLinePos = *it;
    VMD lastPos = start + (dir * lastLinePos);
    if (!bin_centres) {
      line.x.push_back(lastLinePos);
    }

    ++it;
    coord_t linePos = 0;
    for (; it != boundaries.cend(); ++it) {
      // This is our current position along the line
      linePos = *it;

      // This is the full position at this boundary
      VMD pos = start + (dir * linePos);

      // Position in the middle of the bin
      VMD middle = (pos + lastPos) * 0.5;

      // Find the signal in this bin
      const auto linearIndex =
          this->getLinearIndexAtCoord(middle.getBareArray());

      if (bin_centres && !this->getIsMaskedAt(linearIndex)) {
        coord_t bin_centrePos =
            static_cast<coord_t>((linePos + lastLinePos) * 0.5);
        line.x.push_back(bin_centrePos);
      } else if (!bin_centres)
        line.x.push_back(linePos);

      if (linearIndex < m_length) {

        auto normalizer = getNormalizationFactor(normalize, linearIndex);
        // And add the normalized signal/error to the list too
        auto signal = this->getSignalAt(linearIndex) * normalizer;
        if (boost::math::isinf(signal)) {
          // The plotting library (qwt) doesn't like infs.
          signal = std::numeric_limits<signal_t>::quiet_NaN();
        }
        if (!bin_centres || !this->getIsMaskedAt(linearIndex)) {
          line.y.push_back(signal);
          line.e.push_back(this->getErrorAt(linearIndex) * normalizer);
        }
        // Save the position for next bin
        lastPos = pos;
      } else {
        // Invalid index. This shouldn't happen
        line.y.push_back(std::numeric_limits<signal_t>::quiet_NaN());
        line.e.push_back(std::numeric_limits<signal_t>::quiet_NaN());
      }

      lastLinePos = linePos;

    } // for each unique boundary

    // If all bins were masked
    if (line.x.size() == 0) {
      this->makeSinglePointWithNaN(line.x, line.y, line.e);
    }
  }
  return line;
}
コード例 #11
0
void garbageCollectInternalArgumentVectors() {
	for (auto i=lists.cbegin(); i!=lists.cend(); ++i) {
		delete(*i);
	}
	lists.clear();
}
コード例 #12
0
ファイル: filter.cpp プロジェクト: inphos42/osmpbf
void KeyMultiValueTagFilter::setValues(const std::set<std::string> & values)
{
	setValues(values.cbegin(), values.cend());
}
コード例 #13
0
ファイル: dhtnode.cpp プロジェクト: gvsurenderreddy/opendht
void cmd_loop(DhtRunner& dht, dht_params& params)
{
    print_node_info(dht, params);
    std::cout << " (type 'h' or 'help' for a list of possible commands)" << std::endl << std::endl;

    // using the GNU History API
    using_history();

    while (true)
    {
        // using the GNU Readline API
        std::string line = readLine();
        if (!line.empty() && line[0] == '\0')
            break;

        std::istringstream iss(line);
        std::string op, idstr, value;
        iss >> op >> idstr;

        if (op == "x" || op == "q" || op == "exit" || op == "quit") {
            break;
        } else if (op == "h" || op == "help") {
            print_help();
            continue;
        } else if (op == "ll") {
            print_node_info(dht, params);
            unsigned good4, dubious4, cached4, incoming4;
            unsigned good6, dubious6, cached6, incoming6;
            dht.getNodesStats(AF_INET, &good4, &dubious4, &cached4, &incoming4);
            dht.getNodesStats(AF_INET6, &good6, &dubious6, &cached6, &incoming6);
            std::cout << "IPv4 nodes : " << good4 << " good, " << dubious4 << " dubious, " << incoming4 << " incoming." << std::endl;
            std::cout << "IPv6 nodes : " << good6 << " good, " << dubious6 << " dubious, " << incoming6 << " incoming." << std::endl;
            continue;
        } else if (op == "lr") {
            std::cout << "IPv4 routing table:" << std::endl;
            std::cout << dht.getRoutingTablesLog(AF_INET) << std::endl;
            std::cout << "IPv6 routing table:" << std::endl;
            std::cout << dht.getRoutingTablesLog(AF_INET6) << std::endl;
            continue;
        } else if (op == "ld") {
            std::cout << dht.getStorageLog() << std::endl;
            continue;
        } else if (op == "ls") {
            std::cout << "Searches:" << std::endl;
            std::cout << dht.getSearchesLog() << std::endl;
            continue;
        } else if (op == "la")  {
            std::cout << "Reported public addresses:" << std::endl;
            auto addrs = dht.getPublicAddressStr();
            for (const auto& addr : addrs)
                std::cout << addr << std::endl;
            continue;
        } else if (op == "b") {
            try {
                auto addr = splitPort(idstr);
                if (not addr.first.empty() and addr.second.empty()){
                    std::stringstream ss;
                    ss << DHT_DEFAULT_PORT;
                    addr.second = ss.str();
                }
                dht.bootstrap(addr.first.c_str(), addr.second.c_str());
            } catch (const std::exception& e) {
                std::cerr << e.what() << std::endl;
            }
            continue;
        } else if (op == "log") {
            params.log = !params.log;
            if (params.log)
                log::enableLogging(dht);
            else
                log::disableLogging(dht);
            continue;
        }

        if (op.empty())
            continue;

        dht::InfoHash id {idstr};
        static const std::set<std::string> VALID_OPS {"g", "l", "p", "s", "e", "a"};
        if (VALID_OPS.find(op) == VALID_OPS.cend()) {
            std::cout << "Unknown command: " << op << std::endl;
            std::cout << " (type 'h' or 'help' for a list of possible commands)" << std::endl;
            continue;
        }
        static constexpr dht::InfoHash INVALID_ID {};
        if (id == INVALID_ID) {
            std::cout << "Syntax error: invalid InfoHash." << std::endl;
            continue;
        }

        auto start = std::chrono::high_resolution_clock::now();
        if (op == "g") {
            dht.get(id, [start](std::shared_ptr<Value> value) {
                auto now = std::chrono::high_resolution_clock::now();
                std::cout << "Get: found value (after " << print_dt(now-start) << "s)" << std::endl;
                std::cout << "\t" << *value << std::endl;
                return true;
            }, [start](bool ok) {
                auto end = std::chrono::high_resolution_clock::now();
                std::cout << "Get: " << (ok ? "completed" : "failure") << " (took " << print_dt(end-start) << "s)" << std::endl;
            });
        }
        else if (op == "l") {
            dht.listen(id, [](std::shared_ptr<Value> value) {
                std::cout << "Listen: found value:" << std::endl;
                std::cout << "\t" << *value << std::endl;
                return true;
            });
        }
        else if (op == "p") {
            std::string v;
            iss >> v;
            dht.put(id, dht::Value {
                dht::ValueType::USER_DATA.id,
                std::vector<uint8_t> {v.begin(), v.end()}
            }, [start](bool ok) {
                auto end = std::chrono::high_resolution_clock::now();
                std::cout << "Put: " << (ok ? "success" : "failure") << " (took " << print_dt(end-start) << "s)" << std::endl;
            });
        }
        else if (op == "s") {
コード例 #14
0
ファイル: GCode.hpp プロジェクト: alexrj/Slic3r
 void set_extruders(const std::set<T> &extruder_ids) {
     this->set_extruders(extruder_ids.cbegin(), extruder_ids.cend());
 }
コード例 #15
0
ファイル: tracks.hpp プロジェクト: autosquid/openMVG
  /**
   * @brief Find the shared tracks between some images ids.
   *
   * @param[in] image_ids: images id to consider
   * @param[out] tracks: tracks shared by the input images id
   */
  bool GetTracksInImages
  (
    const std::set<uint32_t> & image_ids,
    STLMAPTracks & tracks
  )
  {
    tracks.clear();
    if (image_ids.empty())
      return false;

    // Collect the shared tracks ids by the views
    std::set<uint32_t> common_track_ids;
    {
      // Compute the intersection of all the track ids of the view's track ids.
      // 1. Initialize the track_id with the view first tracks
      // 2. Iteratively collect the common id of the remaining requested view
      auto image_index_it = image_ids.cbegin();
      if (track_ids_per_view_.count(*image_index_it))
      {
        common_track_ids = track_ids_per_view_[*image_index_it];
      }
      bool merged = false;
      std::advance(image_index_it, 1);
      while (image_index_it != image_ids.cend())
      {
        if (track_ids_per_view_.count(*image_index_it))
        {
          const auto ids_per_view_it = track_ids_per_view_.find(*image_index_it);
          const auto & track_ids = ids_per_view_it->second;

          std::set<uint32_t> tmp;
          std::set_intersection(
            common_track_ids.cbegin(), common_track_ids.cend(),
            track_ids.cbegin(), track_ids.cend(),
            std::inserter(tmp, tmp.begin()));
          common_track_ids.swap(tmp);
          merged = true;
        }
        std::advance(image_index_it, 1);
      }
      if (image_ids.size() > 1 && !merged)
      {
        // If more than one image id is required and no merge operation have been done
        //  we need to reset the common track id
        common_track_ids.clear();
      }
    }

    // Collect the selected {img id, feat id} data for the shared track ids
    for (const auto track_ids_it : common_track_ids)
    {
      const auto track_it = tracks_.find(track_ids_it);
      const auto & track = track_it->second;
      // Find the corresponding output track and update it
      submapTrack& trackFeatsOut = tracks[track_it->first];
      for (const auto img_index: image_ids)
      {
        const auto track_view_info = track.find(img_index);
        trackFeatsOut[img_index] = track_view_info->second;
      }
    }
    return !tracks.empty();
  }
コード例 #16
0
ファイル: dhtnode.cpp プロジェクト: AlexSnet/opendht
int
main(int argc, char **argv)
{
    DhtRunner dht;
    try {
        auto params = parseArgs(argc, argv);
        if (params.help) {
            print_usage();
            return 0;
        }

        // TODO: remove with GnuTLS >= 3.3
        int rc = gnutls_global_init();
        if (rc != GNUTLS_E_SUCCESS)
            throw std::runtime_error(std::string("Error initializing GnuTLS: ")+gnutls_strerror(rc));

        dht::crypto::Identity crt {};
        if (params.generate_identity) {
            auto ca_tmp = dht::crypto::generateIdentity("DHT Node CA");
            crt = dht::crypto::generateIdentity("DHT Node", ca_tmp);
        }
    
        dht.run(params.port, crt, true, params.is_bootstrap_node);

        if (params.log)
            enableLogging(dht);

        if (not params.bootstrap.first.empty()) {
            std::cout << "Bootstrap: " << params.bootstrap.first << ":" << params.bootstrap.second << std::endl;
            dht.bootstrap(params.bootstrap.first.c_str(), params.bootstrap.second.c_str());
        }

        print_node_info(dht, params);
        std::cout << " (type 'h' or 'help' for a list of possible commands)" << std::endl << std::endl;

        // using the GNU History API
        using_history();

        while (true)
        {
            // using the GNU Readline API
            std::string line = readLine();
            if (!line.empty() && line[0] == '\0')
                break;

            std::istringstream iss(line);
            std::string op, idstr, value;
            iss >> op >> idstr;

            if (op == "x" || op == "q" || op == "exit" || op == "quit") {
                break;
            } else if (op == "h" || op == "help") {
                print_help();
                continue;
            } else if (op == "ll") {
                print_node_info(dht, params);
                unsigned good4, dubious4, cached4, incoming4;
                unsigned good6, dubious6, cached6, incoming6;
                dht.getNodesStats(AF_INET, &good4, &dubious4, &cached4, &incoming4);
                dht.getNodesStats(AF_INET6, &good6, &dubious6, &cached6, &incoming6);
                std::cout << "IPv4 nodes : " << good4 << " good, " << dubious4 << " dubious, " << incoming4 << " incoming." << std::endl;
                std::cout << "IPv6 nodes : " << good6 << " good, " << dubious6 << " dubious, " << incoming6 << " incoming." << std::endl;
                continue;
            } else if (op == "lr") {
                std::cout << "IPv4 routing table:" << std::endl;
                std::cout << dht.getRoutingTablesLog(AF_INET) << std::endl;
                std::cout << "IPv6 routing table:" << std::endl;
                std::cout << dht.getRoutingTablesLog(AF_INET6) << std::endl;
                continue;
            } else if (op == "ld") {
                std::cout << dht.getStorageLog() << std::endl;
                continue;
            } else if (op == "ls") {
                std::cout << "Searches:" << std::endl;
                std::cout << dht.getSearchesLog() << std::endl;
                continue;
            } else if (op == "la")  {
                std::cout << "Reported public addresses:" << std::endl;
                auto addrs = dht.getPublicAddressStr();
                for (const auto& addr : addrs)
                    std::cout << addr << std::endl;
                continue;
            } else if (op == "b") {
                try {
                    auto addr = splitPort(idstr);
                    if (not addr.first.empty() and addr.second.empty())
                        addr.second = std::to_string(DHT_DEFAULT_PORT);
                    dht.bootstrap(addr.first.c_str(), addr.second.c_str());
                } catch (const std::exception& e) {
                    std::cout << e.what() << std::endl;
                }
                continue;
            } else if (op == "log") {
                params.log = !params.log;
                if (params.log)
                    enableLogging(dht);
                else
                    disableLogging(dht);
                continue;
            }

            if (op.empty())
                continue;

            dht::InfoHash id {idstr};
            static const std::set<std::string> VALID_OPS {"g", "l", "p", "s", "e", "a"};
            if (VALID_OPS.find(op) == VALID_OPS.cend()) {
                std::cout << "Unknown command: " << op << std::endl;
                std::cout << " (type 'h' or 'help' for a list of possible commands)" << std::endl;
                continue;
            }
            static constexpr dht::InfoHash INVALID_ID {};
            if (id == INVALID_ID) {
                std::cout << "Syntax error: invalid InfoHash." << std::endl;
                continue;
            }

            auto start = std::chrono::high_resolution_clock::now();
            if (op == "g") {
                dht.get(id, [start](std::shared_ptr<Value> value) {
                    auto now = std::chrono::high_resolution_clock::now();
                    std::cout << "Get: found value (after " << print_dt(now-start) << "s)" << std::endl;
                    std::cout << "\t" << *value << std::endl;
                    return true;
                }, [start](bool ok) {
                    auto end = std::chrono::high_resolution_clock::now();
                    std::cout << "Get: " << (ok ? "completed" : "failure") << " (took " << print_dt(end-start) << "s)" << std::endl;
                });
            }
            else if (op == "l") {
                std::cout << id << std::endl;
                dht.listen(id, [](std::shared_ptr<Value> value) {
                    std::cout << "Listen: found value:" << std::endl;
                    std::cout << "\t" << *value << std::endl;
                    return true;
                });
            }
            else if (op == "p") {
                std::string v;
                iss >> v;
                dht.put(id, dht::Value {
                    dht::ValueType::USER_DATA.id,
                    std::vector<uint8_t> {v.begin(), v.end()}
                }, [start](bool ok) {
                    auto end = std::chrono::high_resolution_clock::now();
                    std::cout << "Put: " << (ok ? "success" : "failure") << " (took " << print_dt(end-start) << "s)" << std::endl;
                });
            }
            else if (op == "s") {
                if (not params.generate_identity) {
                    print_id_req();
                    continue;
                }
                std::string v;
                iss >> v;
                dht.putSigned(id, dht::Value {
                    dht::ValueType::USER_DATA.id,
                    std::vector<uint8_t> {v.begin(), v.end()}
                }, [start](bool ok) {
                    auto end = std::chrono::high_resolution_clock::now();
                    std::cout << "Put signed: " << (ok ? "success" : "failure") << " (took " << print_dt(end-start) << "s)" << std::endl;
                });
            }
            else if (op == "e") {