<commit_before>#include <algorithm>
#include <set>
#include <list>
#include <iterator>

#include "otc/otcli.h"
#include "otc/tree_operations.h"
#include "otc/tree_iter.h"
using namespace otc;
using std::vector;
using std::unique_ptr;
using std::set;
using std::list;
using std::map;
using std::string;
using namespace otc;

typedef TreeMappedWithSplits Tree_t;

template <typename T>
std::ostream& operator<<(std::ostream& o, const std::set<T>& s)
{
  auto it = s.begin();
  o<<*it++;
  for(; it != s.end(); it++)
    o<<" "<<*it;
  return o;
}

template <typename T>
std::ostream& operator<<(std::ostream& o, const std::list<T>& s)
{
  auto it = s.begin();
  o<<*it++;
  for(; it != s.end(); it++)
    o<<" "<<*it;
  return o;
}

struct RSplit
{
  set<long> in;
  set<long> out;
  set<long> all;
  RSplit() = default;
  RSplit(const set<long>& i, const set<long>& a)
    :in(i),all(a)
  {
    out = set_difference_as_set(all,in);
    assert(in.size() + out.size() == all.size());
  }
};

std::ostream& operator<<(std::ostream& o, const RSplit& s)
{
  o<<s.in<<" | "<<s.out;
  return o;
}

/// Merge components c1 and c2 and return the component name that survived
long merge_components(long c1, long c2, map<long,long>& component, map<long,list<long>>& elements)
{
  if (elements[c2].size() > elements[c1].size())
    std::swap(c1,c2);

  for(long i:elements[c2])
    component[i] = c1;

  elements[c1].splice(elements[c1].begin(), elements[c2]);

  return c1;
}

bool empty_intersection(const set<long>& x, const set<long>& y)
{
  std::set<long>::const_iterator i = x.begin();
  std::set<long>::const_iterator j = y.begin();
  while (i != x.end() && j != y.end())
  {
    if (*i == *j)
      return false;
    else if (*i < *j)
      ++i;
    else
      ++j;
  }
  return true;
}

/// Construct a tree with all the splits mentioned, and return a null pointer if this is not possible
unique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits)
{
  std::unique_ptr<Tree_t> tree(new Tree_t());
  tree->createRoot();

  // 1. First handle trees of size 1 and 2
  if (tips.size() == 1)
  {
    tree->getRoot()->setOttId(*tips.begin());
    return tree;
  }
  else if (tips.size() == 2)
  {
    auto Node1a = tree->createChild(tree->getRoot());
    auto Node1b = tree->createChild(tree->getRoot());
    auto it = tips.begin();
    Node1a->setOttId(*it++);
    Node1b->setOttId(*it++);
    return tree;
  }

  // 2. Initialize the mapping from elements to components
  map<long,long> component;      // element   -> component
  map<long,list<long>> elements; // component -> elements
  for(long i: tips)
  {
    component[i] = i;
    elements[i].push_back(i);
  }

  // 3. For each split, all the leaves in the include group must be in the same component
  for(const auto& split: splits)
  {
    long c1 = -1;
    for(long i: split.in)
    {
      long c2 = component[i];
      if (c1 != -1 and c1 != c2)
	merge_components(c1,c2,component,elements);
      c1 = component[i];
    }
  }

  // 4. If we can't subdivide the leaves in any way, then the splits are not consistent, so return failure
  long first = *tips.begin();
  if (elements[component[first]].size() == tips.size())
    return {};

  // 5. Create the set of tips in each connected component
  map<long,set<long>> subtips;
  for(long c: tips)
  {
    if (c != component[c]) continue;

    set<long>& s = subtips[c];
    for(long l: elements[c])
      s.insert(l);
  }

  // 6. Determine the splits that are not satisfied yet and go into each component
  map<long,vector<RSplit>> subsplits;
  for(const auto& split: splits)
  {
    long first = *split.in.begin();
    long c = component[first];

    // if none of the exclude group are in the component, then the split is satisfied by the top-level partition.
    if (empty_intersection(split.out, subtips[c])) continue;

    subsplits[c].push_back(split);
  }

  // 7. Recursively solve the sub-problems of the partition components
  for(const auto& x: subtips)
  {
    auto subtree = BUILD(x.second, subsplits[x.first]);
    if (not subtree) return {};

    tree->addSubtree(tree->getRoot(), *subtree);
  }

  return tree;
}

/// Run the BUILD algorithm on the first n splits
unique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits, int n)
{
  vector<RSplit> splits2;
  for(int i=0;i<n;i++)
    splits2.push_back(splits[i]);
  return BUILD(tips,splits2);
}

/// Copy node names from taxonomy to tree based on ott ids, and copy the root name also
void add_names(unique_ptr<Tree_t>& tree, const unique_ptr<Tree_t>& taxonomy)
{
  map<long,string> names;

  // 1. Determine the names for each ottid
  for(auto nd: iter_post(*taxonomy))
    if (nd->isTip())
      names[nd->getOttId()] = nd->getName();

  // 2. Set the names of nodes based on their ottid
  for(auto nd: iter_post(*tree))
    if (nd->hasOttId())
      nd->setName( names[nd->getOttId()] );

  // 3. Name the root node too
  string rootname = taxonomy->getRoot()->getName();
  tree->getRoot()->setName(rootname);
}

/// Get the list of splits, and add them one at a time if they are consistent with previous splits
unique_ptr<Tree_t> combine(const vector<unique_ptr<Tree_t>>& trees)
{
  // Standardize names to 0..n-1 for this subproblem
  const auto& taxonomy = trees.back();
  auto all_leaves = taxonomy->getRoot()->getData().desIds;

  // 1. Find splits in order of input trees
  vector<RSplit> splits;
  for(const auto& tree: trees)
  {
    auto root = tree->getRoot();
    const auto leafTaxa = root->getData().desIds;

    for(const auto& leaf: set_difference_as_set(leafTaxa, all_leaves))
      throw OTCError()<<"OTT Id "<<leaf<<" not in taxonomy!";

    for(auto nd: iter_post_const(*tree))
    {
      const auto& descendants = nd->getData().desIds;
      RSplit split{descendants, leafTaxa};
      if (split.in.size()>1 and split.out.size())
      	splits.push_back(split);
    }
  }

  // 2. Add splits sequentially if they are consistent with previous splits.
  vector<RSplit> consistent;
  for(const auto& split: splits)
  {
    consistent.push_back(split);
    auto result = BUILD(all_leaves, consistent);
    if (not result)
    {
      consistent.pop_back();
      LOG(DEBUG)<<"Reject: "<<split<<"\n";
    }
    else
      LOG(DEBUG)<<"Keep:   "<<split<<"\n";
  }

  // 3. Construct final tree and add names
  auto tree = BUILD(all_leaves, consistent);
  add_names(tree, taxonomy);
  return tree;
}

bool handleRequireOttIds(OTCLI & otCLI, const std::string & arg)
{
  if (arg == "true" or arg == "yes" or arg == "True" or arg == "Yes")
    otCLI.getParsingRules().requireOttIds = true;
  else if (arg == "false" or arg == "no" or arg == "False" or arg == "no")
    otCLI.getParsingRules().requireOttIds = false;
  else
    return false;

  return true;
}

bool handlePruneUnrecognizedTips(OTCLI & otCLI, const std::string & arg)
{
  if (arg == "true" or arg == "yes" or arg == "True" or arg == "Yes")
    otCLI.getParsingRules().pruneUnrecognizedInputTips = true;
  else if (arg == "false" or arg == "no" or arg == "False" or arg == "no")
    otCLI.getParsingRules().pruneUnrecognizedInputTips = false;
  else
    return false;

  return true;
}

bool synthesize_taxonomy = false;

bool handleSynthesizeTaxonomy(OTCLI &, const std::string & arg)
{
  if (arg == "true" or "yes" or "True" or "Yes")
    synthesize_taxonomy = true;
  else if (arg == "false" or "no" or "False" or "no")
    synthesize_taxonomy = false;
  else
    return false;

  return true;
}

unique_ptr<Tree_t> make_unresolved_tree(const vector<unique_ptr<Tree_t>>& trees, bool use_ids)
{
  std::unique_ptr<Tree_t> tree(new Tree_t());
  tree->createRoot();

  if (use_ids)
  {
    map<long,string> names;
    for(const auto& tree: trees)
      for(auto nd: iter_pre_const(*tree))
	if (nd->isTip())
	{
	  long id = nd->getOttId();
	  auto it = names.find(id);
	  if (it == names.end())
	    names[id] = nd->getName();
	}

    for(const auto& n: names)
    {
      auto node = tree->createChild(tree->getRoot());
      node->setOttId(n.first);
      node->setName(n.second);
    }
    clearAndfillDesIdSets(*tree);
  }
  else
  {
    set<string> names;
    for(const auto& tree: trees)
      for(auto nd: iter_pre_const(*tree))
	if (nd->isTip())
	  names.insert(nd->getName());

    for(const auto& n: names)
    {
      auto node = tree->createChild(tree->getRoot());
      node->setName(n);
    }
  }

  return tree;
}

string newick(const Tree_t &t)
{
  std::ostringstream s;
  writeTreeAsNewick(s, t);
  return s.str();
}

int main(int argc, char *argv[]) {
    OTCLI otCLI("otc-solve-subproblem",
                "takes at series of tree files. Each is treated as a subproblem.\n",
		"subproblem.tre");

    otCLI.addFlag('o',
		  "Require OTT ids.  Defaults to true",
		  handleRequireOttIds,
		  true);
    otCLI.addFlag('p',
		  "Prune unrecognized tips.  Defaults to false",
		  handlePruneUnrecognizedTips,
		  true);
    otCLI.addFlag('T',
		  "Synthesize unresolved taxonomy from all mentioned taxa.  Defaults to false",
		  handleSynthesizeTaxonomy,
		  false);

    vector<unique_ptr<Tree_t>> trees;
    auto get = [&trees](OTCLI &, unique_ptr<Tree_t> nt) {trees.push_back(std::move(nt)); return true;};

    if (argc < 2)
	throw OTCError("No subproblem provided!");

    // I think multiple subproblem files are essentially concatenated.
    // Is it possible to read a single subproblem from cin?
    if (treeProcessingMain<Tree_t>(otCLI, argc, argv, get, nullptr, 1))
      std::exit(1);

    bool requireOttIds = otCLI.getParsingRules().requireOttIds;
    if (synthesize_taxonomy)
    {
      trees.push_back(make_unresolved_tree(trees,requireOttIds));
      LOG(DEBUG)<<"taxonomy = "<<newick(*trees.back())<<"\n";
    }

    // Add fake Ott Ids to tips and compute desIds
    if (not requireOttIds)
    {
      auto& taxonomy = trees.back();

      // 1. Compute mapping from name -> id
      long id = 1;
      map<string,long> name_to_id;
      for(auto nd: iter_pre(*taxonomy))
	if (nd->isTip())
	{
	  string name = nd->getName();
	  if (not name.size())
	    throw OTCError()<<"Taxonomy tip has no label or OTT id!";
	  auto it = name_to_id.find(name);
	  if (it != name_to_id.end())
	    throw OTCError()<<"Tip label '"<<name<<"' occurs twice in taxonomy!";
	  name_to_id[name] = id++;
	}

      // 2. Set ids
      for(auto& tree: trees)
	for(auto nd: iter_post(*tree))
	  if (nd->isTip())
	  {
	    string name = nd->getName();
	    if (not name.size())
	      throw OTCError()<<"Tip has no label or OTT id!";
	    auto it = name_to_id.find(name);
	    if (it == name_to_id.end())
	      throw OTCError()<<"Can't find label '"<<name<<"' in taxonomy!";
	    auto id = it->second;
	    nd->setOttId(id);
	  }

      // 3. Compute DesIds.
      for(auto& tree: trees)
	clearAndfillDesIdSets(*tree);
    }

    auto tree = combine(trees);

    writeTreeAsNewick(std::cout, *tree);
    std::cout<<"\n";
}
<commit_msg>Impute names to internal nodes based on taxonomy clades.<commit_after>#include <algorithm>
#include <set>
#include <list>
#include <iterator>

#include "otc/otcli.h"
#include "otc/tree_operations.h"
#include "otc/tree_iter.h"
using namespace otc;
using std::vector;
using std::unique_ptr;
using std::set;
using std::list;
using std::map;
using std::string;
using namespace otc;

typedef TreeMappedWithSplits Tree_t;

template <typename T>
std::ostream& operator<<(std::ostream& o, const std::set<T>& s)
{
  auto it = s.begin();
  o<<*it++;
  for(; it != s.end(); it++)
    o<<" "<<*it;
  return o;
}

template <typename T>
std::ostream& operator<<(std::ostream& o, const std::list<T>& s)
{
  auto it = s.begin();
  o<<*it++;
  for(; it != s.end(); it++)
    o<<" "<<*it;
  return o;
}

struct RSplit
{
  set<long> in;
  set<long> out;
  set<long> all;
  RSplit() = default;
  RSplit(const set<long>& i, const set<long>& a)
    :in(i),all(a)
  {
    out = set_difference_as_set(all,in);
    assert(in.size() + out.size() == all.size());
  }
};

std::ostream& operator<<(std::ostream& o, const RSplit& s)
{
  o<<s.in<<" | "<<s.out;
  return o;
}

/// Merge components c1 and c2 and return the component name that survived
long merge_components(long c1, long c2, map<long,long>& component, map<long,list<long>>& elements)
{
  if (elements[c2].size() > elements[c1].size())
    std::swap(c1,c2);

  for(long i:elements[c2])
    component[i] = c1;

  elements[c1].splice(elements[c1].begin(), elements[c2]);

  return c1;
}

bool empty_intersection(const set<long>& x, const set<long>& y)
{
  std::set<long>::const_iterator i = x.begin();
  std::set<long>::const_iterator j = y.begin();
  while (i != x.end() && j != y.end())
  {
    if (*i == *j)
      return false;
    else if (*i < *j)
      ++i;
    else
      ++j;
  }
  return true;
}

/// Construct a tree with all the splits mentioned, and return a null pointer if this is not possible
unique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits)
{
  std::unique_ptr<Tree_t> tree(new Tree_t());
  tree->createRoot();

  // 1. First handle trees of size 1 and 2
  if (tips.size() == 1)
  {
    tree->getRoot()->setOttId(*tips.begin());
    return tree;
  }
  else if (tips.size() == 2)
  {
    auto Node1a = tree->createChild(tree->getRoot());
    auto Node1b = tree->createChild(tree->getRoot());
    auto it = tips.begin();
    Node1a->setOttId(*it++);
    Node1b->setOttId(*it++);
    return tree;
  }

  // 2. Initialize the mapping from elements to components
  map<long,long> component;      // element   -> component
  map<long,list<long>> elements; // component -> elements
  for(long i: tips)
  {
    component[i] = i;
    elements[i].push_back(i);
  }

  // 3. For each split, all the leaves in the include group must be in the same component
  for(const auto& split: splits)
  {
    long c1 = -1;
    for(long i: split.in)
    {
      long c2 = component[i];
      if (c1 != -1 and c1 != c2)
	merge_components(c1,c2,component,elements);
      c1 = component[i];
    }
  }

  // 4. If we can't subdivide the leaves in any way, then the splits are not consistent, so return failure
  long first = *tips.begin();
  if (elements[component[first]].size() == tips.size())
    return {};

  // 5. Create the set of tips in each connected component
  map<long,set<long>> subtips;
  for(long c: tips)
  {
    if (c != component[c]) continue;

    set<long>& s = subtips[c];
    for(long l: elements[c])
      s.insert(l);
  }

  // 6. Determine the splits that are not satisfied yet and go into each component
  map<long,vector<RSplit>> subsplits;
  for(const auto& split: splits)
  {
    long first = *split.in.begin();
    long c = component[first];

    // if none of the exclude group are in the component, then the split is satisfied by the top-level partition.
    if (empty_intersection(split.out, subtips[c])) continue;

    subsplits[c].push_back(split);
  }

  // 7. Recursively solve the sub-problems of the partition components
  for(const auto& x: subtips)
  {
    auto subtree = BUILD(x.second, subsplits[x.first]);
    if (not subtree) return {};

    tree->addSubtree(tree->getRoot(), *subtree);
  }

  return tree;
}

/// Run the BUILD algorithm on the first n splits
unique_ptr<Tree_t> BUILD(const std::set<long>& tips, const vector<RSplit>& splits, int n)
{
  vector<RSplit> splits2;
  for(int i=0;i<n;i++)
    splits2.push_back(splits[i]);
  return BUILD(tips,splits2);
}

/// Copy node names from taxonomy to tree based on ott ids, and copy the root name also
void add_names(unique_ptr<Tree_t>& tree, const unique_ptr<Tree_t>& taxonomy)
{
  clearAndfillDesIdSets(*tree);

  for(auto n1: iter_post(*tree))
    for(auto n2: iter_post(*taxonomy))
      if (n1->getData().desIds == n2->getData().desIds)
	n1->setName( n2->getName());
}

/// Get the list of splits, and add them one at a time if they are consistent with previous splits
unique_ptr<Tree_t> combine(const vector<unique_ptr<Tree_t>>& trees)
{
  // Standardize names to 0..n-1 for this subproblem
  const auto& taxonomy = trees.back();
  auto all_leaves = taxonomy->getRoot()->getData().desIds;

  // 1. Find splits in order of input trees
  vector<RSplit> splits;
  for(const auto& tree: trees)
  {
    auto root = tree->getRoot();
    const auto leafTaxa = root->getData().desIds;

    for(const auto& leaf: set_difference_as_set(leafTaxa, all_leaves))
      throw OTCError()<<"OTT Id "<<leaf<<" not in taxonomy!";

    for(auto nd: iter_post_const(*tree))
    {
      const auto& descendants = nd->getData().desIds;
      RSplit split{descendants, leafTaxa};
      if (split.in.size()>1 and split.out.size())
      	splits.push_back(split);
    }
  }

  // 2. Add splits sequentially if they are consistent with previous splits.
  vector<RSplit> consistent;
  for(const auto& split: splits)
  {
    consistent.push_back(split);
    auto result = BUILD(all_leaves, consistent);
    if (not result)
    {
      consistent.pop_back();
      LOG(DEBUG)<<"Reject: "<<split<<"\n";
    }
    else
      LOG(DEBUG)<<"Keep:   "<<split<<"\n";
  }

  // 3. Construct final tree and add names
  auto tree = BUILD(all_leaves, consistent);
  add_names(tree, taxonomy);
  return tree;
}

bool handleRequireOttIds(OTCLI & otCLI, const std::string & arg)
{
  if (arg == "true" or arg == "yes" or arg == "True" or arg == "Yes")
    otCLI.getParsingRules().requireOttIds = true;
  else if (arg == "false" or arg == "no" or arg == "False" or arg == "no")
    otCLI.getParsingRules().requireOttIds = false;
  else
    return false;

  return true;
}

bool handlePruneUnrecognizedTips(OTCLI & otCLI, const std::string & arg)
{
  if (arg == "true" or arg == "yes" or arg == "True" or arg == "Yes")
    otCLI.getParsingRules().pruneUnrecognizedInputTips = true;
  else if (arg == "false" or arg == "no" or arg == "False" or arg == "no")
    otCLI.getParsingRules().pruneUnrecognizedInputTips = false;
  else
    return false;

  return true;
}

bool synthesize_taxonomy = false;

bool handleSynthesizeTaxonomy(OTCLI &, const std::string & arg)
{
  if (arg == "true" or "yes" or "True" or "Yes")
    synthesize_taxonomy = true;
  else if (arg == "false" or "no" or "False" or "no")
    synthesize_taxonomy = false;
  else
    return false;

  return true;
}

unique_ptr<Tree_t> make_unresolved_tree(const vector<unique_ptr<Tree_t>>& trees, bool use_ids)
{
  std::unique_ptr<Tree_t> tree(new Tree_t());
  tree->createRoot();

  if (use_ids)
  {
    map<long,string> names;
    for(const auto& tree: trees)
      for(auto nd: iter_pre_const(*tree))
	if (nd->isTip())
	{
	  long id = nd->getOttId();
	  auto it = names.find(id);
	  if (it == names.end())
	    names[id] = nd->getName();
	}

    for(const auto& n: names)
    {
      auto node = tree->createChild(tree->getRoot());
      node->setOttId(n.first);
      node->setName(n.second);
    }
    clearAndfillDesIdSets(*tree);
  }
  else
  {
    set<string> names;
    for(const auto& tree: trees)
      for(auto nd: iter_pre_const(*tree))
	if (nd->isTip())
	  names.insert(nd->getName());

    for(const auto& n: names)
    {
      auto node = tree->createChild(tree->getRoot());
      node->setName(n);
    }
  }

  return tree;
}

string newick(const Tree_t &t)
{
  std::ostringstream s;
  writeTreeAsNewick(s, t);
  return s.str();
}

int main(int argc, char *argv[]) {
    OTCLI otCLI("otc-solve-subproblem",
                "takes at series of tree files. Each is treated as a subproblem.\n",
		"subproblem.tre");

    otCLI.addFlag('o',
		  "Require OTT ids.  Defaults to true",
		  handleRequireOttIds,
		  true);
    otCLI.addFlag('p',
		  "Prune unrecognized tips.  Defaults to false",
		  handlePruneUnrecognizedTips,
		  true);
    otCLI.addFlag('T',
		  "Synthesize unresolved taxonomy from all mentioned taxa.  Defaults to false",
		  handleSynthesizeTaxonomy,
		  false);

    vector<unique_ptr<Tree_t>> trees;
    auto get = [&trees](OTCLI &, unique_ptr<Tree_t> nt) {trees.push_back(std::move(nt)); return true;};

    if (argc < 2)
	throw OTCError("No subproblem provided!");

    // I think multiple subproblem files are essentially concatenated.
    // Is it possible to read a single subproblem from cin?
    if (treeProcessingMain<Tree_t>(otCLI, argc, argv, get, nullptr, 1))
      std::exit(1);

    bool requireOttIds = otCLI.getParsingRules().requireOttIds;
    if (synthesize_taxonomy)
    {
      trees.push_back(make_unresolved_tree(trees,requireOttIds));
      LOG(DEBUG)<<"taxonomy = "<<newick(*trees.back())<<"\n";
    }

    // Add fake Ott Ids to tips and compute desIds
    if (not requireOttIds)
    {
      auto& taxonomy = trees.back();

      // 1. Compute mapping from name -> id
      long id = 1;
      map<string,long> name_to_id;
      for(auto nd: iter_pre(*taxonomy))
	if (nd->isTip())
	{
	  string name = nd->getName();
	  if (not name.size())
	    throw OTCError()<<"Taxonomy tip has no label or OTT id!";
	  auto it = name_to_id.find(name);
	  if (it != name_to_id.end())
	    throw OTCError()<<"Tip label '"<<name<<"' occurs twice in taxonomy!";
	  name_to_id[name] = id++;
	}

      // 2. Set ids
      for(auto& tree: trees)
	for(auto nd: iter_post(*tree))
	  if (nd->isTip())
	  {
	    string name = nd->getName();
	    if (not name.size())
	      throw OTCError()<<"Tip has no label or OTT id!";
	    auto it = name_to_id.find(name);
	    if (it == name_to_id.end())
	      throw OTCError()<<"Can't find label '"<<name<<"' in taxonomy!";
	    auto id = it->second;
	    nd->setOttId(id);
	  }

      // 3. Compute DesIds.
      for(auto& tree: trees)
	clearAndfillDesIdSets(*tree);
    }

    auto tree = combine(trees);

    writeTreeAsNewick(std::cout, *tree);
    std::cout<<"\n";
}
<|endoftext|>


<commit_before>#include "ResourcePath.h"

std::string resourcePath()
{
	return "..\\..\\";
}
<commit_msg>Delete ResourcePathWindows.cpp<commit_after><|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/keypoints/uniform_sampling.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

using namespace std;
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

double default_radius = 0.01;

Eigen::Vector4f    translation;
Eigen::Quaternionf orientation;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -radius X = use a leaf size of X,X,X to uniformly select 1 point per leaf (default: ");
  print_value ("%f", default_radius); print_info (")\n");
}

bool
loadCloud (const string &filename, sensor_msgs::PointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud, translation, orientation) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
  print_info ("Available dimensions: "); print_value ("%s\n", getFieldsList (cloud).c_str ());

  return (true);
}

void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
         double radius)
{
  // Convert data to PointCloud<T>
  PointCloud<PointXYZ>::Ptr xyz (new PointCloud<PointXYZ>);
  fromROSMsg (*input, *xyz);

  // Estimate
  TicToc tt;
  tt.tic ();

  print_highlight (stderr, "Computing ");

  UniformSampling<PointXYZ> us;
  us.setInputCloud (xyz);
  us.setRadiusSearch (radius);
  PointCloud<int> subsampled_indices;
  us.compute (subsampled_indices);

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", subsampled_indices.width * subsampled_indices.height); print_info (" points]\n");

  // Convert data back
  copyPointCloud (*input, subsampled_indices.points, output);
}

void
saveCloud (const string &filename, const sensor_msgs::PointCloud2 &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  PCDWriter w;
  w.writeBinaryCompressed (filename, output, translation, orientation);

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Uniform subsampling using UniformSampling. For more information, use: %s -h\n", argv[0]);

  if (argc < 3)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Command line parsing
  double radius = default_radius;
  parse_argument (argc, argv, "-radius", radius);
  print_info ("Extracting uniform points with a leaf size of: ");
  print_value ("%f\n", radius);

  // Load the first file
  sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
  if (!loadCloud (argv[p_file_indices[0]], *cloud))
    return (-1);

  // Perform the keypoint estimation
  sensor_msgs::PointCloud2 output;
  compute (cloud, output, radius);

  // Save into the second file
  saveCloud (argv[p_file_indices[1]], output);
}

<commit_msg>sort indices before saving to disk<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2012-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <sensor_msgs/PointCloud2.h>
#include <pcl/io/pcd_io.h>
#include <pcl/keypoints/uniform_sampling.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>

using namespace std;
using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

double default_radius = 0.01;

Eigen::Vector4f    translation;
Eigen::Quaternionf orientation;

void
printHelp (int, char **argv)
{
  print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]);
  print_info ("  where options are:\n");
  print_info ("                     -radius X = use a leaf size of X,X,X to uniformly select 1 point per leaf (default: ");
  print_value ("%f", default_radius); print_info (")\n");
}

bool
loadCloud (const string &filename, sensor_msgs::PointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud, translation, orientation) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
  print_info ("Available dimensions: "); print_value ("%s\n", getFieldsList (cloud).c_str ());

  return (true);
}

void
compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output,
         double radius)
{
  // Convert data to PointCloud<T>
  PointCloud<PointXYZ>::Ptr xyz (new PointCloud<PointXYZ>);
  fromROSMsg (*input, *xyz);

  // Estimate
  TicToc tt;
  tt.tic ();

  print_highlight (stderr, "Computing ");

  UniformSampling<PointXYZ> us;
  us.setInputCloud (xyz);
  us.setRadiusSearch (radius);
  PointCloud<int> subsampled_indices;
  us.compute (subsampled_indices);
  std::sort (subsampled_indices.points.begin (), subsampled_indices.points.end ());

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", subsampled_indices.width * subsampled_indices.height); print_info (" points]\n");

  // Convert data back
  copyPointCloud (*input, subsampled_indices.points, output);
}

void
saveCloud (const string &filename, const sensor_msgs::PointCloud2 &output)
{
  TicToc tt;
  tt.tic ();

  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());

  PCDWriter w;
  w.writeBinaryCompressed (filename, output, translation, orientation);

  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", output.width * output.height); print_info (" points]\n");
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Uniform subsampling using UniformSampling. For more information, use: %s -h\n", argv[0]);

  if (argc < 3)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd files
  vector<int> p_file_indices;
  p_file_indices = parse_file_extension_argument (argc, argv, ".pcd");
  if (p_file_indices.size () != 2)
  {
    print_error ("Need one input PCD file and one output PCD file to continue.\n");
    return (-1);
  }

  // Command line parsing
  double radius = default_radius;
  parse_argument (argc, argv, "-radius", radius);
  print_info ("Extracting uniform points with a leaf size of: ");
  print_value ("%f\n", radius);

  // Load the first file
  sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2);
  if (!loadCloud (argv[p_file_indices[0]], *cloud))
    return (-1);

  // Perform the keypoint estimation
  sensor_msgs::PointCloud2 output;
  compute (cloud, output, radius);

  // Save into the second file
  saveCloud (argv[p_file_indices[1]], output);
}

<|endoftext|>


<commit_before>
#include <widgetzeug/ColorSchemeControlWidget.h>

#include <assert.h>

#include <widgetzeug/ColorScheme.h>
#include <widgetzeug/ColorSchemePresets.h>
#include <widgetzeug/ColorSchemePresetsWidget.h>
#include <widgetzeug/ColorSchemeWidget.h>
#include <widgetzeug/DataLinkWidget.h>

#include "util.hpp"

namespace widgetzeug
{

ColorSchemeControlWidget::ColorSchemeControlWidget(
    const QString & title, QWidget * parent, const Qt::WindowFlags flags)
:   DockableScrollAreaWidget(title, parent, flags)
,   m_colorSchemeWidget{new ColorSchemeWidget{}}
,   m_colorSchemePresetsWidget{new ColorSchemePresetsWidget{}}
,   m_dataLinkWidget{new DataLinkWidget{}}
{
    m_dataLinkWidget->setReadOnly(true);
    m_dataLinkWidget->setWindowTitle(QObject::tr("Color Scheme Presets File"));
    m_dataLinkWidget->setFilter(QObject::tr("Color Scheme Presets Files") + " (*.json);;" + QObject::tr("All Files") + " (*.*)");

    const auto enabled = false;

    m_colorSchemeWidget->setEnabled(enabled);
    m_colorSchemePresetsWidget->setEnabled(enabled);

    addWidget(m_colorSchemeWidget);
    addWidget(m_colorSchemePresetsWidget);
    addWidget(m_dataLinkWidget);

    connect(m_colorSchemeWidget, &ColorSchemeWidget::classesChanged
        , this, &ColorSchemeControlWidget::classesChanged);

    connect(m_colorSchemeWidget, &ColorSchemeWidget::invertedChanged
        , this, &ColorSchemeControlWidget::invertedChanged);

    connect(m_colorSchemePresetsWidget, &ColorSchemePresetsWidget::selectedChanged
        , this, &ColorSchemeControlWidget::onSelectedChanged);

    connect(m_dataLinkWidget, &DataLinkWidget::fileChanged
        , this, &ColorSchemeControlWidget::onFileChanged);
}

ColorSchemeControlWidget::ColorSchemeControlWidget(
    QWidget * parent, const Qt::WindowFlags flags)
:   ColorSchemeControlWidget("", parent, flags)
{
}

void ColorSchemeControlWidget::addFileName(const QString & fileName, bool active)
{
    m_dataLinkWidget->addFileName(fileName, active);
}
void ColorSchemeControlWidget::setFileName(const QString & fileName)
{
    m_dataLinkWidget->setFileName(fileName);
}
const QString & ColorSchemeControlWidget::fileName() const
{
    return m_presets->fileName();
}

QStringList ColorSchemeControlWidget::fileNames() const
{
    return m_dataLinkWidget->fileNames();
}

void ColorSchemeControlWidget::setFileLinked(const bool linked)
{
    m_dataLinkWidget->setFileLinked(linked);
}
bool ColorSchemeControlWidget::fileLinked() const
{
    return m_dataLinkWidget->fileLinked();
}

const ColorSchemePresets * ColorSchemeControlWidget::presets() const
{
    return m_presets.get();
}

void ColorSchemeControlWidget::setScheme(const QString & identifier)
{
    m_colorSchemePresetsWidget->setSelected(identifier);
}

void ColorSchemeControlWidget::setScheme(const ColorScheme & scheme)
{
    m_colorSchemePresetsWidget->setSelected(scheme);
}
const ColorScheme * ColorSchemeControlWidget::scheme() const
{
    return m_colorSchemePresetsWidget->selected();
}

void ColorSchemeControlWidget::setTypeFilter(const ColorScheme::ColorSchemeTypes & types)
{
    m_colorSchemePresetsWidget->setTypeFilter(types);
}

ColorScheme::ColorSchemeTypes ColorSchemeControlWidget::typeFilter() const
{
    return m_colorSchemePresetsWidget->typeFilter();
}

void ColorSchemeControlWidget::setClasses(const uint classes)
{
    m_colorSchemeWidget->setClasses(classes);
}

uint ColorSchemeControlWidget::classes() const
{
    return m_colorSchemeWidget->classes();
}

void ColorSchemeControlWidget::setInverted(const bool invert)
{
    m_colorSchemeWidget->setInverted(invert);
}
bool ColorSchemeControlWidget::inverted() const
{
    return m_colorSchemeWidget->inverted();
}

void ColorSchemeControlWidget::setClassesFilter(const uint classes)
{
    m_colorSchemePresetsWidget->setClassesFilter(classes);
}

uint ColorSchemeControlWidget::classesFilter() const
{
    return m_colorSchemePresetsWidget->classesFilter();
}

void ColorSchemeControlWidget::setDeficiency(const ColorVisionDeficiency deficiency)
{
    m_colorSchemePresetsWidget->setDeficiency(deficiency);
}

ColorVisionDeficiency ColorSchemeControlWidget::deficiency() const
{
    return m_colorSchemePresetsWidget->deficiency();
}

void ColorSchemeControlWidget::onSelectedChanged(const ColorScheme * scheme)
{
    m_colorSchemeWidget->setScheme(scheme);
    emit schemeChanged(scheme);
}

void ColorSchemeControlWidget::onFileChanged(const QString & fileName)
{
    // this slot should be called by data link widget's file changes

    auto presets = make_unique<ColorSchemePresets>(fileName);
    m_dataLinkWidget->setFileIssue(!presets->isValid());

    if (!presets->isValid())
        return;

    m_lastPresetsFileName = fileName;
    const auto selected = m_colorSchemePresetsWidget->selected() ?
        m_colorSchemePresetsWidget->selected()->identifier() : "";

    m_presets = std::move(presets);

    const auto enabled = static_cast<bool>(m_presets.get());
    assert(enabled);

    m_colorSchemeWidget->setScheme(nullptr);
    m_colorSchemeWidget->setEnabled(false);
    m_colorSchemePresetsWidget->setEnabled(enabled);

    if (!enabled)
        return;

    m_colorSchemePresetsWidget->setPresets(*m_presets);

    const auto scheme = m_presets->scheme(selected);
    if (scheme)
        setScheme(*scheme);
    else
        setScheme(*m_presets->first()->first());

    m_colorSchemePresetsWidget->setEnabled(true);
}

} // namespace widgetzeug
<commit_msg>Fix CID #51219<commit_after>
#include <widgetzeug/ColorSchemeControlWidget.h>

#include <assert.h>

#include <widgetzeug/ColorScheme.h>
#include <widgetzeug/ColorSchemePresets.h>
#include <widgetzeug/ColorSchemePresetsWidget.h>
#include <widgetzeug/ColorSchemeWidget.h>
#include <widgetzeug/DataLinkWidget.h>

#include "util.hpp"

namespace widgetzeug
{

ColorSchemeControlWidget::ColorSchemeControlWidget(
    const QString & title, QWidget * parent, const Qt::WindowFlags flags)
:   DockableScrollAreaWidget(title, parent, flags)
,   m_colorSchemeWidget{new ColorSchemeWidget{}}
,   m_colorSchemePresetsWidget{new ColorSchemePresetsWidget{}}
,   m_dataLinkWidget{new DataLinkWidget{}}
{
    m_dataLinkWidget->setReadOnly(true);
    m_dataLinkWidget->setWindowTitle(QObject::tr("Color Scheme Presets File"));
    m_dataLinkWidget->setFilter(QObject::tr("Color Scheme Presets Files") + " (*.json);;" + QObject::tr("All Files") + " (*.*)");

    const auto enabled = false;

    m_colorSchemeWidget->setEnabled(enabled);
    m_colorSchemePresetsWidget->setEnabled(enabled);

    addWidget(m_colorSchemeWidget);
    addWidget(m_colorSchemePresetsWidget);
    addWidget(m_dataLinkWidget);

    connect(m_colorSchemeWidget, &ColorSchemeWidget::classesChanged
        , this, &ColorSchemeControlWidget::classesChanged);

    connect(m_colorSchemeWidget, &ColorSchemeWidget::invertedChanged
        , this, &ColorSchemeControlWidget::invertedChanged);

    connect(m_colorSchemePresetsWidget, &ColorSchemePresetsWidget::selectedChanged
        , this, &ColorSchemeControlWidget::onSelectedChanged);

    connect(m_dataLinkWidget, &DataLinkWidget::fileChanged
        , this, &ColorSchemeControlWidget::onFileChanged);
}

ColorSchemeControlWidget::ColorSchemeControlWidget(
    QWidget * parent, const Qt::WindowFlags flags)
:   ColorSchemeControlWidget("", parent, flags)
{
}

void ColorSchemeControlWidget::addFileName(const QString & fileName, bool active)
{
    m_dataLinkWidget->addFileName(fileName, active);
}
void ColorSchemeControlWidget::setFileName(const QString & fileName)
{
    m_dataLinkWidget->setFileName(fileName);
}
const QString & ColorSchemeControlWidget::fileName() const
{
    return m_presets->fileName();
}

QStringList ColorSchemeControlWidget::fileNames() const
{
    return m_dataLinkWidget->fileNames();
}

void ColorSchemeControlWidget::setFileLinked(const bool linked)
{
    m_dataLinkWidget->setFileLinked(linked);
}
bool ColorSchemeControlWidget::fileLinked() const
{
    return m_dataLinkWidget->fileLinked();
}

const ColorSchemePresets * ColorSchemeControlWidget::presets() const
{
    return m_presets.get();
}

void ColorSchemeControlWidget::setScheme(const QString & identifier)
{
    m_colorSchemePresetsWidget->setSelected(identifier);
}

void ColorSchemeControlWidget::setScheme(const ColorScheme & scheme)
{
    m_colorSchemePresetsWidget->setSelected(scheme);
}
const ColorScheme * ColorSchemeControlWidget::scheme() const
{
    return m_colorSchemePresetsWidget->selected();
}

void ColorSchemeControlWidget::setTypeFilter(const ColorScheme::ColorSchemeTypes & types)
{
    m_colorSchemePresetsWidget->setTypeFilter(types);
}

ColorScheme::ColorSchemeTypes ColorSchemeControlWidget::typeFilter() const
{
    return m_colorSchemePresetsWidget->typeFilter();
}

void ColorSchemeControlWidget::setClasses(const uint classes)
{
    m_colorSchemeWidget->setClasses(classes);
}

uint ColorSchemeControlWidget::classes() const
{
    return m_colorSchemeWidget->classes();
}

void ColorSchemeControlWidget::setInverted(const bool invert)
{
    m_colorSchemeWidget->setInverted(invert);
}
bool ColorSchemeControlWidget::inverted() const
{
    return m_colorSchemeWidget->inverted();
}

void ColorSchemeControlWidget::setClassesFilter(const uint classes)
{
    m_colorSchemePresetsWidget->setClassesFilter(classes);
}

uint ColorSchemeControlWidget::classesFilter() const
{
    return m_colorSchemePresetsWidget->classesFilter();
}

void ColorSchemeControlWidget::setDeficiency(const ColorVisionDeficiency deficiency)
{
    m_colorSchemePresetsWidget->setDeficiency(deficiency);
}

ColorVisionDeficiency ColorSchemeControlWidget::deficiency() const
{
    return m_colorSchemePresetsWidget->deficiency();
}

void ColorSchemeControlWidget::onSelectedChanged(const ColorScheme * scheme)
{
    m_colorSchemeWidget->setScheme(scheme);
    emit schemeChanged(scheme);
}

void ColorSchemeControlWidget::onFileChanged(const QString & fileName)
{
    // this slot should be called by data link widget's file changes

    auto presets = make_unique<ColorSchemePresets>(fileName);
    m_dataLinkWidget->setFileIssue(!presets->isValid());

    if (!presets->isValid())
        return;

    m_lastPresetsFileName = fileName;
    const auto selected = m_colorSchemePresetsWidget->selected() ?
        m_colorSchemePresetsWidget->selected()->identifier() : "";

    m_presets = std::move(presets);

    const auto enabled = static_cast<bool>(m_presets.get());
    assert(enabled);

    m_colorSchemeWidget->setScheme(nullptr);
    m_colorSchemeWidget->setEnabled(false);
    m_colorSchemePresetsWidget->setEnabled(enabled);

    //if (!enabled) // before: assert(enabled)
    //    return;

    m_colorSchemePresetsWidget->setPresets(*m_presets);

    const auto scheme = m_presets->scheme(selected);
    if (scheme)
        setScheme(*scheme);
    else
        setScheme(*m_presets->first()->first());

    m_colorSchemePresetsWidget->setEnabled(true);
}

} // namespace widgetzeug
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_GRID_WALKER_HH
#define DUNE_STUFF_GRID_WALKER_HH

#include <vector>
#include <memory>
#include <type_traits>
#include <functional>

#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE
# include <dune/grid/utility/partitioning/ranged.hh>
# include <dune/stuff/common/parallel/threadmanager.hh>
#endif

#if HAVE_TBB
# include <tbb/blocked_range.h>
# include <tbb/parallel_reduce.h>
# include <tbb/tbb_stddef.h>
#endif

#include <dune/stuff/grid/entity.hh>
#include <dune/stuff/grid/intersection.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/common/parallel/threadmanager.hh>
#include <dune/stuff/common/ranges.hh>

#include "walker/functors.hh"
#include "walker/apply-on.hh"
#include "walker/wrapper.hh"

namespace Dune {
namespace Stuff {
namespace Grid {

template< class GridViewImp >
class Walker
  : public Functor::Codim0And1< GridViewImp >
{
  typedef Walker< GridViewImp > ThisType;
public:
  typedef GridViewImp GridViewType;
  typedef typename Stuff::Grid::Entity< GridViewType >::Type       EntityType;
  typedef typename Stuff::Grid::Intersection< GridViewType >::Type IntersectionType;

  explicit Walker(GridViewType grd_vw)
    : grid_view_(grd_vw)
  {}

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  void add(std::function< void(const EntityType&) > lambda,
           const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
  {
    codim0_functors_.emplace_back(new internal::Codim0LambdaWrapper< GridViewType >(lambda, where));
  }

  void add(Functor::Codim0< GridViewType >& functor,
           const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
  {
    codim0_functors_.emplace_back(
          new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0< GridViewType > >(functor, where));
  }

  void add(Functor::Codim1< GridViewType >& functor,
           const ApplyOn::WhichIntersection< GridViewType >* where = new ApplyOn::AllIntersections< GridViewType >())
  {
    codim1_functors_.emplace_back(
          new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim1< GridViewType > >(functor, where));
  }

  void add(Functor::Codim0And1< GridViewType >& functor,
           const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >(),
           const ApplyOn::WhichIntersection< GridViewType >* which_intersections
              = new ApplyOn::AllIntersections< GridViewType >())
  {
    codim0_functors_.emplace_back(
          new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor,
                                                                                which_entities));
    codim1_functors_.emplace_back(
          new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor,
                                                                                which_intersections));
  }

  void add(Functor::Codim0And1< GridViewType >& functor,
           const ApplyOn::WhichIntersection< GridViewType >* which_intersections,
           const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >())
  {
    codim0_functors_.emplace_back(
          new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor,
                                                                                which_entities));
    codim1_functors_.emplace_back(
          new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor,
                                                                                which_intersections));
  }

  void add(ThisType& other,
           const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >(),
           const ApplyOn::WhichIntersection< GridViewType >* which_intersections
              = new ApplyOn::AllIntersections< GridViewType >())
  {
    if (&other == this)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not add a Walker to itself!");
    codim0_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_entities));
    codim1_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_intersections));
  } // ... add(...)

  void add(ThisType& other,
           const ApplyOn::WhichIntersection< GridViewType >* which_intersections,
           const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >())
  {
    if (&other == this)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not add a Walker to itself!");
    codim0_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_entities));
    codim1_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_intersections));
  } // ... add(...)

  void clear()
  {
    codim0_functors_.clear();
    codim1_functors_.clear();
  } // ... clear()

  virtual void prepare()
  {
    for (auto& functor : codim0_functors_)
      functor->prepare();
    for (auto& functor : codim1_functors_)
      functor->prepare();
  } // ... prepare()

  bool apply_on(const EntityType& entity) const
  {
    for (const auto& functor : codim0_functors_)
      if (functor->apply_on(grid_view_, entity))
        return true;
    return false;
  } // ... apply_on(...)

  bool apply_on(const IntersectionType& intersection) const
  {
    for (const auto& functor : codim1_functors_)
      if (functor->apply_on(grid_view_, intersection))
        return true;
    return false;
  } // ... apply_on(...)

  virtual void apply_local(const EntityType& entity)
  {
    for (auto& functor : codim0_functors_)
      if (functor->apply_on(grid_view_, entity))
        functor->apply_local(entity);
  } // ... apply_local(...)

  virtual void apply_local(const IntersectionType& intersection,
                           const EntityType& inside_entity,
                           const EntityType& outside_entity)
  {
    for (auto& functor : codim1_functors_)
      if (functor->apply_on(grid_view_, intersection))
        functor->apply_local(intersection, inside_entity, outside_entity);
  } // ... apply_local(...)

  virtual void finalize()
  {
    for (auto& functor : codim0_functors_)
      functor->finalize();
    for (auto& functor : codim1_functors_)
      functor->finalize();
  } // ... finalize()

  void walk(const bool use_tbb = false)
  {
#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE
    if (use_tbb) {
      const auto num_partitions = threadManager().current_threads();
      RangedPartitioning< GridViewType, 0 > partitioning(grid_view_, num_partitions);
      this->walk(partitioning);
      return;
    }
#else
    const auto DUNE_UNUSED(no_warning_for_use_tbb) = use_tbb;
#endif
    // prepare functors
    prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      walk_range(DSC::entityRange(grid_view_));
    } // only do something, if we have to

    // finalize functors
    finalize();
  } // ... walk(...)

#if HAVE_TBB

protected:
  template< class PartioningType, class WalkerType >
  struct Body
  {
    Body(WalkerType& walker, PartioningType& partitioning)
      : walker_(walker)
      , partitioning_(partitioning)
    {}

    Body(Body& other, tbb::split /*split*/)
      : walker_(other.walker_)
      , partitioning_(other.partitioning_)
    {}

    void operator()(const tbb::blocked_range< std::size_t > &range) const
    {
      // for all partitions in tbb-range
      for(std::size_t p = range.begin(); p != range.end(); ++p) {
        auto partition = partitioning_.partition(p);
        walker_.walk_range(partition);
      }
    }

    void join(Body& /*other*/)
    {}

    WalkerType& walker_;
    const PartioningType& partitioning_;
  }; // struct Body

public:
  template< class PartioningType >
  void walk(PartioningType& partitioning)
  {
    // prepare functors
    prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      tbb::blocked_range< std::size_t > range(0, partitioning.partitions());
      Body< PartioningType, ThisType > body(*this, partitioning);
      tbb::parallel_reduce(range, body);
    }

    // finalize functors
    finalize();
  } // ... tbb_walk(...)

#endif // HAVE_TBB

protected:
  template< class EntityRange >
  void walk_range(const EntityRange& entity_range)
  {
#ifdef __INTEL_COMPILER
    const auto it_end = entity_range.end();
    for (auto it = entity_range.begin(); it != it_end; ++it) {
      const EntityType& entity = *it;
#else
    for (const EntityType& entity : entity_range) {
#endif
      // apply codim0 functors
      apply_local(entity);

      // only walk the intersections, if there are codim1 functors present
      if (codim1_functors_.size() > 0) {
        // walk the intersections
        const auto intersection_it_end = grid_view_.iend(entity);
        for (auto intersection_it = grid_view_.ibegin(entity);
             intersection_it != intersection_it_end;
             ++intersection_it) {
          const auto& intersection = *intersection_it;

          // apply codim1 functors
          if (intersection.neighbor()) {
            const auto neighbor_ptr = intersection.outside();
            const auto& neighbor = *neighbor_ptr;
            apply_local(intersection, entity, neighbor);
          } else
            apply_local(intersection, entity, entity);

        } // walk the intersections
      } // only walk the intersections, if there are codim1 functors present
    }
  } // ... walk_range(...)

  const GridViewType grid_view_;
  std::vector< std::unique_ptr< internal::Codim0Object<GridViewType> > > codim0_functors_;
  std::vector< std::unique_ptr< internal::Codim1Object<GridViewType> > > codim1_functors_;
}; // class Walker

} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_GRID_WALKER_HH
<commit_msg>[grid.walker] re-adds functor clearing that was lost in TBB changes<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_GRID_WALKER_HH
#define DUNE_STUFF_GRID_WALKER_HH

#include <vector>
#include <memory>
#include <type_traits>
#include <functional>

#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE
# include <dune/grid/utility/partitioning/ranged.hh>
# include <dune/stuff/common/parallel/threadmanager.hh>
#endif

#if HAVE_TBB
# include <tbb/blocked_range.h>
# include <tbb/parallel_reduce.h>
# include <tbb/tbb_stddef.h>
#endif

#include <dune/stuff/grid/entity.hh>
#include <dune/stuff/grid/intersection.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/stuff/common/parallel/threadmanager.hh>
#include <dune/stuff/common/ranges.hh>

#include "walker/functors.hh"
#include "walker/apply-on.hh"
#include "walker/wrapper.hh"

namespace Dune {
namespace Stuff {
namespace Grid {

template< class GridViewImp >
class Walker
  : public Functor::Codim0And1< GridViewImp >
{
  typedef Walker< GridViewImp > ThisType;
public:
  typedef GridViewImp GridViewType;
  typedef typename Stuff::Grid::Entity< GridViewType >::Type       EntityType;
  typedef typename Stuff::Grid::Intersection< GridViewType >::Type IntersectionType;

  explicit Walker(GridViewType grd_vw)
    : grid_view_(grd_vw)
  {}

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  void add(std::function< void(const EntityType&) > lambda,
           const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
  {
    codim0_functors_.emplace_back(new internal::Codim0LambdaWrapper< GridViewType >(lambda, where));
  }

  void add(Functor::Codim0< GridViewType >& functor,
           const ApplyOn::WhichEntity< GridViewType >* where = new ApplyOn::AllEntities< GridViewType >())
  {
    codim0_functors_.emplace_back(
          new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0< GridViewType > >(functor, where));
  }

  void add(Functor::Codim1< GridViewType >& functor,
           const ApplyOn::WhichIntersection< GridViewType >* where = new ApplyOn::AllIntersections< GridViewType >())
  {
    codim1_functors_.emplace_back(
          new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim1< GridViewType > >(functor, where));
  }

  void add(Functor::Codim0And1< GridViewType >& functor,
           const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >(),
           const ApplyOn::WhichIntersection< GridViewType >* which_intersections
              = new ApplyOn::AllIntersections< GridViewType >())
  {
    codim0_functors_.emplace_back(
          new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor,
                                                                                which_entities));
    codim1_functors_.emplace_back(
          new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor,
                                                                                which_intersections));
  }

  void add(Functor::Codim0And1< GridViewType >& functor,
           const ApplyOn::WhichIntersection< GridViewType >* which_intersections,
           const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >())
  {
    codim0_functors_.emplace_back(
          new internal::Codim0FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor,
                                                                                which_entities));
    codim1_functors_.emplace_back(
          new internal::Codim1FunctorWrapper<GridViewType, Functor::Codim0And1< GridViewType > >(functor,
                                                                                which_intersections));
  }

  void add(ThisType& other,
           const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >(),
           const ApplyOn::WhichIntersection< GridViewType >* which_intersections
              = new ApplyOn::AllIntersections< GridViewType >())
  {
    if (&other == this)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not add a Walker to itself!");
    codim0_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_entities));
    codim1_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_intersections));
  } // ... add(...)

  void add(ThisType& other,
           const ApplyOn::WhichIntersection< GridViewType >* which_intersections,
           const ApplyOn::WhichEntity< GridViewType >* which_entities = new ApplyOn::AllEntities< GridViewType >())
  {
    if (&other == this)
      DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong, "Do not add a Walker to itself!");
    codim0_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_entities));
    codim1_functors_.emplace_back(new internal::WalkerWrapper< GridViewType, ThisType >(other, which_intersections));
  } // ... add(...)

  void clear()
  {
    codim0_functors_.clear();
    codim1_functors_.clear();
  } // ... clear()

  virtual void prepare()
  {
    for (auto& functor : codim0_functors_)
      functor->prepare();
    for (auto& functor : codim1_functors_)
      functor->prepare();
  } // ... prepare()

  bool apply_on(const EntityType& entity) const
  {
    for (const auto& functor : codim0_functors_)
      if (functor->apply_on(grid_view_, entity))
        return true;
    return false;
  } // ... apply_on(...)

  bool apply_on(const IntersectionType& intersection) const
  {
    for (const auto& functor : codim1_functors_)
      if (functor->apply_on(grid_view_, intersection))
        return true;
    return false;
  } // ... apply_on(...)

  virtual void apply_local(const EntityType& entity)
  {
    for (auto& functor : codim0_functors_)
      if (functor->apply_on(grid_view_, entity))
        functor->apply_local(entity);
  } // ... apply_local(...)

  virtual void apply_local(const IntersectionType& intersection,
                           const EntityType& inside_entity,
                           const EntityType& outside_entity)
  {
    for (auto& functor : codim1_functors_)
      if (functor->apply_on(grid_view_, intersection))
        functor->apply_local(intersection, inside_entity, outside_entity);
  } // ... apply_local(...)

  virtual void finalize()
  {
    for (auto& functor : codim0_functors_)
      functor->finalize();
    for (auto& functor : codim1_functors_)
      functor->finalize();
  } // ... finalize()

  void walk(const bool use_tbb = false)
  {
#if DUNE_VERSION_NEWER(DUNE_COMMON,3,9) //EXADUNE
    if (use_tbb) {
      const auto num_partitions = threadManager().current_threads();
      RangedPartitioning< GridViewType, 0 > partitioning(grid_view_, num_partitions);
      this->walk(partitioning);
      return;
    }
#else
    const auto DUNE_UNUSED(no_warning_for_use_tbb) = use_tbb;
#endif
    // prepare functors
    prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      walk_range(DSC::entityRange(grid_view_));
    } // only do something, if we have to

    // finalize functors
    finalize();
  } // ... walk(...)

#if HAVE_TBB

protected:
  template< class PartioningType, class WalkerType >
  struct Body
  {
    Body(WalkerType& walker, PartioningType& partitioning)
      : walker_(walker)
      , partitioning_(partitioning)
    {}

    Body(Body& other, tbb::split /*split*/)
      : walker_(other.walker_)
      , partitioning_(other.partitioning_)
    {}

    void operator()(const tbb::blocked_range< std::size_t > &range) const
    {
      // for all partitions in tbb-range
      for(std::size_t p = range.begin(); p != range.end(); ++p) {
        auto partition = partitioning_.partition(p);
        walker_.walk_range(partition);
      }
    }

    void join(Body& /*other*/)
    {}

    WalkerType& walker_;
    const PartioningType& partitioning_;
  }; // struct Body

public:
  template< class PartioningType >
  void walk(PartioningType& partitioning)
  {
    // prepare functors
    prepare();

    // only do something, if we have to
    if ((codim0_functors_.size() + codim1_functors_.size()) > 0) {
      tbb::blocked_range< std::size_t > range(0, partitioning.partitions());
      Body< PartioningType, ThisType > body(*this, partitioning);
      tbb::parallel_reduce(range, body);
    }

    // finalize functors
    finalize();
    clear();
  } // ... tbb_walk(...)

#endif // HAVE_TBB

protected:
  template< class EntityRange >
  void walk_range(const EntityRange& entity_range)
  {
#ifdef __INTEL_COMPILER
    const auto it_end = entity_range.end();
    for (auto it = entity_range.begin(); it != it_end; ++it) {
      const EntityType& entity = *it;
#else
    for (const EntityType& entity : entity_range) {
#endif
      // apply codim0 functors
      apply_local(entity);

      // only walk the intersections, if there are codim1 functors present
      if (codim1_functors_.size() > 0) {
        // walk the intersections
        const auto intersection_it_end = grid_view_.iend(entity);
        for (auto intersection_it = grid_view_.ibegin(entity);
             intersection_it != intersection_it_end;
             ++intersection_it) {
          const auto& intersection = *intersection_it;

          // apply codim1 functors
          if (intersection.neighbor()) {
            const auto neighbor_ptr = intersection.outside();
            const auto& neighbor = *neighbor_ptr;
            apply_local(intersection, entity, neighbor);
          } else
            apply_local(intersection, entity, entity);

        } // walk the intersections
      } // only walk the intersections, if there are codim1 functors present
    }
  } // ... walk_range(...)

  const GridViewType grid_view_;
  std::vector< std::unique_ptr< internal::Codim0Object<GridViewType> > > codim0_functors_;
  std::vector< std::unique_ptr< internal::Codim1Object<GridViewType> > > codim1_functors_;
}; // class Walker

} // namespace Grid
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_GRID_WALKER_HH
<|endoftext|>


<commit_before>#ifndef BULL_NETWORK_SOCKET_UNIX_SOCKETPOLLERIMPLUNIX_HPP
#define BULL_NETWORK_SOCKET_UNIX_SOCKETPOLLERIMPLUNIX_HPP

#include <Bull/Network/Socket/SocketPollerImpl.hpp>

namespace Bull
{
    namespace prv
    {
        struct SocketPollerImplUnix : public SocketPollerImpl
        {
            static constexpr int SocketError = -1;

            /*! \brief Poll sockets
             *
             * \param sockets Sockets to poll
             * \param timeout The time before the function fail
             *
             * \return The number of sockets updated during the poll, SocketError if an error occurred
             *
             */
            int poll(std::vector<SocketPollDescriptor>& sockets, int timeout) const;
        };
    }
}

#endif // BULL_NETWORK_SOCKET_UNIX_SOCKETPOLLERIMPLUNIX_HPP
<commit_msg>[Network/SocketPollerImplUnix] Add missing override on poll method<commit_after>#ifndef BULL_NETWORK_SOCKET_UNIX_SOCKETPOLLERIMPLUNIX_HPP
#define BULL_NETWORK_SOCKET_UNIX_SOCKETPOLLERIMPLUNIX_HPP

#include <Bull/Network/Socket/SocketPollerImpl.hpp>

namespace Bull
{
    namespace prv
    {
        struct SocketPollerImplUnix : public SocketPollerImpl
        {
            static constexpr int SocketError = -1;

            /*! \brief Poll sockets
             *
             * \param sockets Sockets to poll
             * \param timeout The time before the function fail
             *
             * \return The number of sockets updated during the poll, SocketError if an error occurred
             *
             */
            int poll(std::vector<SocketPollDescriptor>& sockets, int timeout) const override;
        };
    }
}

#endif // BULL_NETWORK_SOCKET_UNIX_SOCKETPOLLERIMPLUNIX_HPP
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: DAVProperties.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kso $ $Date: 2001-05-17 09:15:49 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <string.h>

#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif

using namespace webdav_ucp;

const ::rtl::OUString DAVProperties::CREATIONDATE =
                ::rtl::OUString::createFromAscii( "DAV:creationdate" );
const ::rtl::OUString DAVProperties::DISPLAYNAME =
                ::rtl::OUString::createFromAscii( "DAV:displayname" );
const ::rtl::OUString DAVProperties::GETCONTENTLANGUAGE =
                ::rtl::OUString::createFromAscii( "DAV:getcontentlanguage" );
const ::rtl::OUString DAVProperties::GETCONTENTLENGTH =
                ::rtl::OUString::createFromAscii( "DAV:getcontentlength" );
const ::rtl::OUString DAVProperties::GETCONTENTTYPE =
                ::rtl::OUString::createFromAscii( "DAV:getcontenttype" );
const ::rtl::OUString DAVProperties::GETETAG =
                ::rtl::OUString::createFromAscii( "DAV:getetag" );
const ::rtl::OUString DAVProperties::GETLASTMODIFIED =
                ::rtl::OUString::createFromAscii( "DAV:getlastmodified" );
const ::rtl::OUString DAVProperties::LOCKDISCOVERY =
                ::rtl::OUString::createFromAscii( "DAV:lockdiscovery" );
const ::rtl::OUString DAVProperties::RESOURCETYPE =
                ::rtl::OUString::createFromAscii( "DAV:resourcetype" );
const ::rtl::OUString DAVProperties::SOURCE =
                ::rtl::OUString::createFromAscii( "DAV:source" );
const ::rtl::OUString DAVProperties::SUPPORTEDLOCK =
                ::rtl::OUString::createFromAscii( "DAV:supportedlock" );

const ::rtl::OUString DAVProperties::EXECUTABLE =
                ::rtl::OUString::createFromAscii(
                                "http://apache.org/dav/props/executable" );

// -------------------------------------------------------------------
// static
void DAVProperties::createNeonPropName( const rtl::OUString & rFullName,
                                        NeonPropName & rName )
{
    if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM( "DAV:" ) ) == 0 )
    {
        rName.nspace = "DAV:";
        rName.name
            = strdup( rtl::OUStringToOString(
                        rFullName.copy( RTL_CONSTASCII_LENGTH( "DAV:" ) ),
                                        RTL_TEXTENCODING_UTF8 ) );
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "http://apache.org/dav/props/" ) ) == 0 )
    {
        rName.nspace = "http://apache.org/dav/props/";
        rName.name
            = strdup( rtl::OUStringToOString(
                        rFullName.copy(
                            RTL_CONSTASCII_LENGTH(
                                "http://apache.org/dav/props/" ) ),
                            RTL_TEXTENCODING_UTF8 ) );
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "http://ucb.openoffice.org/dav/props/" ) ) == 0 )
    {
        rName.nspace = "http://ucb.openoffice.org/dav/props/";
        rName.name
            = strdup( rtl::OUStringToOString(
                        rFullName.copy(
                            RTL_CONSTASCII_LENGTH(
                                "http://ucb.openoffice.org/dav/props/" ) ),
                            RTL_TEXTENCODING_UTF8 ) );
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "<prop:" ) ) == 0 )
    {
        // Support for 3rd party namespaces/props

        rtl::OString aFullName
            = rtl::OUStringToOString( rFullName, RTL_TEXTENCODING_UTF8 );

        // Format: <prop:the_propname xmlns:prop="the_namespace">

        sal_Int32 nStart = RTL_CONSTASCII_LENGTH( "<prop:" );
        sal_Int32 nLen = aFullName.indexOf( ' ' ) - nStart;
        rName.name = strdup( aFullName.copy( nStart, nLen ) );

        nStart = aFullName.indexOf( '=', nStart + nLen ) + 2; // after ="
        nLen = aFullName.getLength() - RTL_CONSTASCII_LENGTH( "\">" ) - nStart;
        rName.nspace = strdup( aFullName.copy( nStart, nLen ) );
    }
    else
    {
        // Add our namespace to our own properties.
        rName.nspace = "http://ucb.openoffice.org/dav/props/";
        rName.name
            = strdup( rtl::OUStringToOString( rFullName,
                                              RTL_TEXTENCODING_UTF8 ) );
    }
}

// -------------------------------------------------------------------
// static
void DAVProperties::createUCBPropName( const char * nspace,
                                       const char * name,
                                       rtl::OUString & rFullName )
{
    rtl::OUString aNameSpace
        = rtl::OStringToOUString( nspace, RTL_TEXTENCODING_UTF8 );
    rtl::OUString aName
        = rtl::OStringToOUString( name,   RTL_TEXTENCODING_UTF8 );

    // Note: Concatenating strings BEFORE comparing against known namespaces
    //       is important. See RFC 2815 ( 23.4.2 Meaning of Qualified Names ).
    rFullName  = aNameSpace;
    rFullName += aName;

    if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "DAV:" ) ) == 0 )
    {
        // Okay, Just concat strings.
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "http://apache.org/dav/props/" ) ) == 0 )
    {
        // Okay, Just concat strings.
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "http://ucb.openoffice.org/dav/props/" ) ) == 0 )
    {
        // Remove namespace from our own properties.
        rFullName = rFullName.copy(
                        RTL_CONSTASCII_LENGTH(
                            "http://ucb.openoffice.org/dav/props/" ) );
    }
    else
    {
        // Create property name that encodes, namespace and name ( XML ).
        rFullName  = rtl::OUString::createFromAscii( "<prop:" );
        rFullName += aName;
        rFullName += rtl::OUString::createFromAscii( " xmlns:prop=\"" );
        rFullName += aNameSpace;
        rFullName += rtl::OUString::createFromAscii( "\">" );
    }
}

// -------------------------------------------------------------------
// static
bool DAVProperties::isUCBDeadProperty( const NeonPropName & rName )
{
    return ( rtl_str_compareIgnoreAsciiCase(
                rName.nspace, "http://ucb.openoffice.org/dav/props/" ) == 0 );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.282); FILE MERGED 2005/09/05 18:45:31 rt 1.3.282.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DAVProperties.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 16:06:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <string.h>

#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif

using namespace webdav_ucp;

const ::rtl::OUString DAVProperties::CREATIONDATE =
                ::rtl::OUString::createFromAscii( "DAV:creationdate" );
const ::rtl::OUString DAVProperties::DISPLAYNAME =
                ::rtl::OUString::createFromAscii( "DAV:displayname" );
const ::rtl::OUString DAVProperties::GETCONTENTLANGUAGE =
                ::rtl::OUString::createFromAscii( "DAV:getcontentlanguage" );
const ::rtl::OUString DAVProperties::GETCONTENTLENGTH =
                ::rtl::OUString::createFromAscii( "DAV:getcontentlength" );
const ::rtl::OUString DAVProperties::GETCONTENTTYPE =
                ::rtl::OUString::createFromAscii( "DAV:getcontenttype" );
const ::rtl::OUString DAVProperties::GETETAG =
                ::rtl::OUString::createFromAscii( "DAV:getetag" );
const ::rtl::OUString DAVProperties::GETLASTMODIFIED =
                ::rtl::OUString::createFromAscii( "DAV:getlastmodified" );
const ::rtl::OUString DAVProperties::LOCKDISCOVERY =
                ::rtl::OUString::createFromAscii( "DAV:lockdiscovery" );
const ::rtl::OUString DAVProperties::RESOURCETYPE =
                ::rtl::OUString::createFromAscii( "DAV:resourcetype" );
const ::rtl::OUString DAVProperties::SOURCE =
                ::rtl::OUString::createFromAscii( "DAV:source" );
const ::rtl::OUString DAVProperties::SUPPORTEDLOCK =
                ::rtl::OUString::createFromAscii( "DAV:supportedlock" );

const ::rtl::OUString DAVProperties::EXECUTABLE =
                ::rtl::OUString::createFromAscii(
                                "http://apache.org/dav/props/executable" );

// -------------------------------------------------------------------
// static
void DAVProperties::createNeonPropName( const rtl::OUString & rFullName,
                                        NeonPropName & rName )
{
    if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM( "DAV:" ) ) == 0 )
    {
        rName.nspace = "DAV:";
        rName.name
            = strdup( rtl::OUStringToOString(
                        rFullName.copy( RTL_CONSTASCII_LENGTH( "DAV:" ) ),
                                        RTL_TEXTENCODING_UTF8 ) );
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "http://apache.org/dav/props/" ) ) == 0 )
    {
        rName.nspace = "http://apache.org/dav/props/";
        rName.name
            = strdup( rtl::OUStringToOString(
                        rFullName.copy(
                            RTL_CONSTASCII_LENGTH(
                                "http://apache.org/dav/props/" ) ),
                            RTL_TEXTENCODING_UTF8 ) );
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "http://ucb.openoffice.org/dav/props/" ) ) == 0 )
    {
        rName.nspace = "http://ucb.openoffice.org/dav/props/";
        rName.name
            = strdup( rtl::OUStringToOString(
                        rFullName.copy(
                            RTL_CONSTASCII_LENGTH(
                                "http://ucb.openoffice.org/dav/props/" ) ),
                            RTL_TEXTENCODING_UTF8 ) );
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "<prop:" ) ) == 0 )
    {
        // Support for 3rd party namespaces/props

        rtl::OString aFullName
            = rtl::OUStringToOString( rFullName, RTL_TEXTENCODING_UTF8 );

        // Format: <prop:the_propname xmlns:prop="the_namespace">

        sal_Int32 nStart = RTL_CONSTASCII_LENGTH( "<prop:" );
        sal_Int32 nLen = aFullName.indexOf( ' ' ) - nStart;
        rName.name = strdup( aFullName.copy( nStart, nLen ) );

        nStart = aFullName.indexOf( '=', nStart + nLen ) + 2; // after ="
        nLen = aFullName.getLength() - RTL_CONSTASCII_LENGTH( "\">" ) - nStart;
        rName.nspace = strdup( aFullName.copy( nStart, nLen ) );
    }
    else
    {
        // Add our namespace to our own properties.
        rName.nspace = "http://ucb.openoffice.org/dav/props/";
        rName.name
            = strdup( rtl::OUStringToOString( rFullName,
                                              RTL_TEXTENCODING_UTF8 ) );
    }
}

// -------------------------------------------------------------------
// static
void DAVProperties::createUCBPropName( const char * nspace,
                                       const char * name,
                                       rtl::OUString & rFullName )
{
    rtl::OUString aNameSpace
        = rtl::OStringToOUString( nspace, RTL_TEXTENCODING_UTF8 );
    rtl::OUString aName
        = rtl::OStringToOUString( name,   RTL_TEXTENCODING_UTF8 );

    // Note: Concatenating strings BEFORE comparing against known namespaces
    //       is important. See RFC 2815 ( 23.4.2 Meaning of Qualified Names ).
    rFullName  = aNameSpace;
    rFullName += aName;

    if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "DAV:" ) ) == 0 )
    {
        // Okay, Just concat strings.
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "http://apache.org/dav/props/" ) ) == 0 )
    {
        // Okay, Just concat strings.
    }
    else if ( rFullName.compareToAscii( RTL_CONSTASCII_STRINGPARAM(
                "http://ucb.openoffice.org/dav/props/" ) ) == 0 )
    {
        // Remove namespace from our own properties.
        rFullName = rFullName.copy(
                        RTL_CONSTASCII_LENGTH(
                            "http://ucb.openoffice.org/dav/props/" ) );
    }
    else
    {
        // Create property name that encodes, namespace and name ( XML ).
        rFullName  = rtl::OUString::createFromAscii( "<prop:" );
        rFullName += aName;
        rFullName += rtl::OUString::createFromAscii( " xmlns:prop=\"" );
        rFullName += aNameSpace;
        rFullName += rtl::OUString::createFromAscii( "\">" );
    }
}

// -------------------------------------------------------------------
// static
bool DAVProperties::isUCBDeadProperty( const NeonPropName & rName )
{
    return ( rtl_str_compareIgnoreAsciiCase(
                rName.nspace, "http://ucb.openoffice.org/dav/props/" ) == 0 );
}
<|endoftext|>