<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This utility program exists to process the False Start blacklist file into
// a static hash table so that it can be efficiently queried by Chrome.

#include <stdio.h>
#include <stdlib.h>

#include <set>
#include <string>
#include <vector>

#include "base/basictypes.h"
#include "net/base/ssl_false_start_blacklist.h"

using net::SSLFalseStartBlacklist;

static const unsigned kBuckets = SSLFalseStartBlacklist::kBuckets;

static bool verbose = false;

static int
usage(const char* argv0) {
  fprintf(stderr, "Usage: %s <blacklist file> <output .c file>\n", argv0);
  return 1;
}

// StripWWWPrefix removes "www." from the beginning of any elements of the
// vector.
static void StripWWWPrefix(std::vector<std::string>* hosts) {
  static const char kPrefix[] = "www.";
  static const unsigned kPrefixLen = sizeof(kPrefix) - 1;

  for (size_t i = 0; i < hosts->size(); i++) {
    const std::string& h = (*hosts)[i];
    if (h.size() >= kPrefixLen &&
        memcmp(h.data(), kPrefix, kPrefixLen) == 0) {
      (*hosts)[i] = h.substr(kPrefixLen, h.size() - kPrefixLen);
    }
  }
}

// RemoveDuplicateEntries removes all duplicates from |hosts|.
static void RemoveDuplicateEntries(std::vector<std::string>* hosts) {
  std::set<std::string> hosts_set;
  std::vector<std::string> ret;

  for (std::vector<std::string>::const_iterator
       i = hosts->begin(); i != hosts->end(); i++) {
    if (hosts_set.count(*i)) {
      if (verbose)
        fprintf(stderr, "Removing duplicate entry for %s\n", i->c_str());
      continue;
    }
    hosts_set.insert(*i);
    ret.push_back(*i);
  }

  hosts->swap(ret);
}

// ParentDomain returns the parent domain for a given domain name or the empty
// string if the name is a top-level domain.
static std::string ParentDomain(const std::string& in) {
  for (size_t i = 0; i < in.size(); i++) {
    if (in[i] == '.') {
      return in.substr(i + 1, in.size() - i - 1);
    }
  }

  return std::string();
}

// RemoveRedundantEntries removes any entries which are subdomains of other
// entries. (i.e. foo.example.com would be removed if example.com were also
// included.)
static void RemoveRedundantEntries(std::vector<std::string>* hosts) {
  std::set<std::string> hosts_set;
  std::vector<std::string> ret;

  for (std::vector<std::string>::const_iterator
       i = hosts->begin(); i != hosts->end(); i++) {
    hosts_set.insert(*i);
  }

  for (std::vector<std::string>::const_iterator
       i = hosts->begin(); i != hosts->end(); i++) {
    std::string parent = ParentDomain(*i);
    while (!parent.empty()) {
      if (hosts_set.count(parent))
        break;
      parent = ParentDomain(parent);
    }
    if (parent.empty()) {
      ret.push_back(*i);
    } else {
      if (verbose)
        fprintf(stderr, "Removing %s as redundant\n", i->c_str());
    }
  }

  hosts->swap(ret);
}

// CheckLengths returns true iff every host is less than 256 bytes long (not
// including the terminating NUL) and contains two or more labels.
static bool CheckLengths(const std::vector<std::string>& hosts) {
  for (std::vector<std::string>::const_iterator
       i = hosts.begin(); i != hosts.end(); i++) {
     if (i->size() >= 256) {
       fprintf(stderr, "Entry %s is too large\n", i->c_str());
       return false;
     }
     if (SSLFalseStartBlacklist::LastTwoLabels(i->c_str()) == NULL) {
       fprintf(stderr, "Entry %s contains too few labels\n", i->c_str());
       return false;
     }
  }

  return true;
}

int main(int argc, char** argv) {
  if (argc != 3)
    return usage(argv[0]);

  const char* input_file = argv[1];
  const char* output_file = argv[2];
  FILE* input = fopen(input_file, "rb");
  if (!input) {
    perror("open");
    return usage(argv[0]);
  }

  if (fseek(input, 0, SEEK_END)) {
    perror("fseek");
    return 1;
  }

  const long input_size = ftell(input);

  if (fseek(input, 0, SEEK_SET)) {
    perror("fseek");
    return 1;
  }

  char* buffer = static_cast<char*>(malloc(input_size));
  long done = 0;
  while (done < input_size) {
    size_t n = fread(buffer + done, 1, input_size - done, input);
    if (n == 0) {
      perror("fread");
      free(buffer);
      fclose(input);
      return 1;
    }
    done += n;
  }
  fclose(input);

  std::vector<std::string> hosts;

  off_t line_start = 0;
  bool is_comment = false;
  bool non_whitespace_seen = false;
  for (long i = 0; i <= input_size; i++) {
    if (i == input_size || buffer[i] == '\n') {
      if (!is_comment && non_whitespace_seen) {
        long len = i - line_start;
        if (i > 0 && buffer[i-1] == '\r')
          len--;
        hosts.push_back(std::string(&buffer[line_start], len));
      }
      is_comment = false;
      non_whitespace_seen = false;
      line_start = i + 1;
      continue;
    }

    if (i == line_start && buffer[i] == '#')
      is_comment = true;
    if (buffer[i] != ' ' && buffer[i] != '\t' && buffer[i] != '\r')
      non_whitespace_seen = true;
  }
  free(buffer);

  fprintf(stderr, "Have %d hosts after parse\n", (int) hosts.size());
  StripWWWPrefix(&hosts);
  RemoveDuplicateEntries(&hosts);
  fprintf(stderr, "Have %d hosts after removing duplicates\n", (int) hosts.size());
  RemoveRedundantEntries(&hosts);
  fprintf(stderr, "Have %d hosts after removing redundants\n", (int) hosts.size());
  if (!CheckLengths(hosts)) {
    fprintf(stderr, "One or more entries is too large or too small\n");
    return 2;
  }

  fprintf(stderr, "Using %d entry hash table\n", kBuckets);
  uint32 table[kBuckets];
  std::vector<std::string> buckets[kBuckets];

  for (std::vector<std::string>::const_iterator
       i = hosts.begin(); i != hosts.end(); i++) {
    const char* last_two_labels =
        SSLFalseStartBlacklist::LastTwoLabels(i->c_str());
    const unsigned h = SSLFalseStartBlacklist::Hash(last_two_labels);
    buckets[h & (kBuckets - 1)].push_back(*i);
  }

  std::string table_data;
  unsigned max_bucket_size = 0;
  for (unsigned i = 0; i < kBuckets; i++) {
    if (buckets[i].size() > max_bucket_size)
      max_bucket_size = buckets[i].size();

    table[i] = table_data.size();
    for (std::vector<std::string>::const_iterator
         j = buckets[i].begin(); j != buckets[i].end(); j++) {
      table_data.push_back((char) j->size());
      table_data.append(*j);
    }
  }

  fprintf(stderr, "Largest bucket has %d entries\n", max_bucket_size);

  FILE* out = fopen(output_file, "w+");
  if (!out) {
    perror("opening output file");
    return 4;
  }

  fprintf(out, "// Copyright (c) 2010 The Chromium Authors. All rights "
          "reserved.\n// Use of this source code is governed by a BSD-style "
          "license that can be\n// found in the LICENSE file.\n\n");
  fprintf(out, "// WARNING: this code is generated by\n"
               "// ssl_false_start_blacklist_process.cc. Do not edit.\n\n");
  fprintf(out, "#include \"base/basictypes.h\"\n\n");
  fprintf(out, "#include \"net/base/ssl_false_start_blacklist.h\"\n\n");
  fprintf(out, "namespace net {\n\n");
  fprintf(out, "const uint32 SSLFalseStartBlacklist::kHashTable[%d + 1] = {\n",
          kBuckets);
  for (unsigned i = 0; i < kBuckets; i++) {
    fprintf(out, "  %u,\n", (unsigned) table[i]);
  }
  fprintf(out, "  %u,\n", (unsigned) table_data.size());
  fprintf(out, "};\n\n");

  fprintf(out, "const char SSLFalseStartBlacklist::kHashData[] = {\n");
  for (unsigned i = 0, line_length = 0; i < table_data.size(); i++) {
    if (line_length == 0)
      fprintf(out, "  ");
    uint8 c = static_cast<uint8>(table_data[i]);
    line_length += fprintf(out, "%d, ", c);
    if (i == table_data.size() - 1) {
      fprintf(out, "\n};\n");
    } else if (line_length >= 70) {
      fprintf(out, "\n");
      line_length = 0;
    }
  }
  fprintf(out, "\n}  // namespace net\n");
  fclose(out);

  return 0;
}
<commit_msg>Coverity bug fix (NEGATIVE_RETURNS) CID=12906<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This utility program exists to process the False Start blacklist file into
// a static hash table so that it can be efficiently queried by Chrome.

#include <stdio.h>
#include <stdlib.h>

#include <set>
#include <string>
#include <vector>

#include "base/basictypes.h"
#include "net/base/ssl_false_start_blacklist.h"

using net::SSLFalseStartBlacklist;

static const unsigned kBuckets = SSLFalseStartBlacklist::kBuckets;

static bool verbose = false;

static int
usage(const char* argv0) {
  fprintf(stderr, "Usage: %s <blacklist file> <output .c file>\n", argv0);
  return 1;
}

// StripWWWPrefix removes "www." from the beginning of any elements of the
// vector.
static void StripWWWPrefix(std::vector<std::string>* hosts) {
  static const char kPrefix[] = "www.";
  static const unsigned kPrefixLen = sizeof(kPrefix) - 1;

  for (size_t i = 0; i < hosts->size(); i++) {
    const std::string& h = (*hosts)[i];
    if (h.size() >= kPrefixLen &&
        memcmp(h.data(), kPrefix, kPrefixLen) == 0) {
      (*hosts)[i] = h.substr(kPrefixLen, h.size() - kPrefixLen);
    }
  }
}

// RemoveDuplicateEntries removes all duplicates from |hosts|.
static void RemoveDuplicateEntries(std::vector<std::string>* hosts) {
  std::set<std::string> hosts_set;
  std::vector<std::string> ret;

  for (std::vector<std::string>::const_iterator
       i = hosts->begin(); i != hosts->end(); i++) {
    if (hosts_set.count(*i)) {
      if (verbose)
        fprintf(stderr, "Removing duplicate entry for %s\n", i->c_str());
      continue;
    }
    hosts_set.insert(*i);
    ret.push_back(*i);
  }

  hosts->swap(ret);
}

// ParentDomain returns the parent domain for a given domain name or the empty
// string if the name is a top-level domain.
static std::string ParentDomain(const std::string& in) {
  for (size_t i = 0; i < in.size(); i++) {
    if (in[i] == '.') {
      return in.substr(i + 1, in.size() - i - 1);
    }
  }

  return std::string();
}

// RemoveRedundantEntries removes any entries which are subdomains of other
// entries. (i.e. foo.example.com would be removed if example.com were also
// included.)
static void RemoveRedundantEntries(std::vector<std::string>* hosts) {
  std::set<std::string> hosts_set;
  std::vector<std::string> ret;

  for (std::vector<std::string>::const_iterator
       i = hosts->begin(); i != hosts->end(); i++) {
    hosts_set.insert(*i);
  }

  for (std::vector<std::string>::const_iterator
       i = hosts->begin(); i != hosts->end(); i++) {
    std::string parent = ParentDomain(*i);
    while (!parent.empty()) {
      if (hosts_set.count(parent))
        break;
      parent = ParentDomain(parent);
    }
    if (parent.empty()) {
      ret.push_back(*i);
    } else {
      if (verbose)
        fprintf(stderr, "Removing %s as redundant\n", i->c_str());
    }
  }

  hosts->swap(ret);
}

// CheckLengths returns true iff every host is less than 256 bytes long (not
// including the terminating NUL) and contains two or more labels.
static bool CheckLengths(const std::vector<std::string>& hosts) {
  for (std::vector<std::string>::const_iterator
       i = hosts.begin(); i != hosts.end(); i++) {
     if (i->size() >= 256) {
       fprintf(stderr, "Entry %s is too large\n", i->c_str());
       return false;
     }
     if (SSLFalseStartBlacklist::LastTwoLabels(i->c_str()) == NULL) {
       fprintf(stderr, "Entry %s contains too few labels\n", i->c_str());
       return false;
     }
  }

  return true;
}

int main(int argc, char** argv) {
  if (argc != 3)
    return usage(argv[0]);

  const char* input_file = argv[1];
  const char* output_file = argv[2];
  FILE* input = fopen(input_file, "rb");
  if (!input) {
    perror("open");
    return usage(argv[0]);
  }

  if (fseek(input, 0, SEEK_END)) {
    perror("fseek");
    return 1;
  }

  const long input_size = ftell(input);
  if (input_size < 0) {
    perror("ftell");
    return 1;
  }

  if (fseek(input, 0, SEEK_SET)) {
    perror("fseek");
    return 1;
  }

  char* buffer = static_cast<char*>(malloc(input_size));
  long done = 0;
  while (done < input_size) {
    size_t n = fread(buffer + done, 1, input_size - done, input);
    if (n == 0) {
      perror("fread");
      free(buffer);
      fclose(input);
      return 1;
    }
    done += n;
  }
  fclose(input);

  std::vector<std::string> hosts;

  off_t line_start = 0;
  bool is_comment = false;
  bool non_whitespace_seen = false;
  for (long i = 0; i <= input_size; i++) {
    if (i == input_size || buffer[i] == '\n') {
      if (!is_comment && non_whitespace_seen) {
        long len = i - line_start;
        if (i > 0 && buffer[i-1] == '\r')
          len--;
        hosts.push_back(std::string(&buffer[line_start], len));
      }
      is_comment = false;
      non_whitespace_seen = false;
      line_start = i + 1;
      continue;
    }

    if (i == line_start && buffer[i] == '#')
      is_comment = true;
    if (buffer[i] != ' ' && buffer[i] != '\t' && buffer[i] != '\r')
      non_whitespace_seen = true;
  }
  free(buffer);

  fprintf(stderr, "Have %d hosts after parse\n", (int) hosts.size());
  StripWWWPrefix(&hosts);
  RemoveDuplicateEntries(&hosts);
  fprintf(stderr, "Have %d hosts after removing duplicates\n", (int) hosts.size());
  RemoveRedundantEntries(&hosts);
  fprintf(stderr, "Have %d hosts after removing redundants\n", (int) hosts.size());
  if (!CheckLengths(hosts)) {
    fprintf(stderr, "One or more entries is too large or too small\n");
    return 2;
  }

  fprintf(stderr, "Using %d entry hash table\n", kBuckets);
  uint32 table[kBuckets];
  std::vector<std::string> buckets[kBuckets];

  for (std::vector<std::string>::const_iterator
       i = hosts.begin(); i != hosts.end(); i++) {
    const char* last_two_labels =
        SSLFalseStartBlacklist::LastTwoLabels(i->c_str());
    const unsigned h = SSLFalseStartBlacklist::Hash(last_two_labels);
    buckets[h & (kBuckets - 1)].push_back(*i);
  }

  std::string table_data;
  unsigned max_bucket_size = 0;
  for (unsigned i = 0; i < kBuckets; i++) {
    if (buckets[i].size() > max_bucket_size)
      max_bucket_size = buckets[i].size();

    table[i] = table_data.size();
    for (std::vector<std::string>::const_iterator
         j = buckets[i].begin(); j != buckets[i].end(); j++) {
      table_data.push_back((char) j->size());
      table_data.append(*j);
    }
  }

  fprintf(stderr, "Largest bucket has %d entries\n", max_bucket_size);

  FILE* out = fopen(output_file, "w+");
  if (!out) {
    perror("opening output file");
    return 4;
  }

  fprintf(out, "// Copyright (c) 2010 The Chromium Authors. All rights "
          "reserved.\n// Use of this source code is governed by a BSD-style "
          "license that can be\n// found in the LICENSE file.\n\n");
  fprintf(out, "// WARNING: this code is generated by\n"
               "// ssl_false_start_blacklist_process.cc. Do not edit.\n\n");
  fprintf(out, "#include \"base/basictypes.h\"\n\n");
  fprintf(out, "#include \"net/base/ssl_false_start_blacklist.h\"\n\n");
  fprintf(out, "namespace net {\n\n");
  fprintf(out, "const uint32 SSLFalseStartBlacklist::kHashTable[%d + 1] = {\n",
          kBuckets);
  for (unsigned i = 0; i < kBuckets; i++) {
    fprintf(out, "  %u,\n", (unsigned) table[i]);
  }
  fprintf(out, "  %u,\n", (unsigned) table_data.size());
  fprintf(out, "};\n\n");

  fprintf(out, "const char SSLFalseStartBlacklist::kHashData[] = {\n");
  for (unsigned i = 0, line_length = 0; i < table_data.size(); i++) {
    if (line_length == 0)
      fprintf(out, "  ");
    uint8 c = static_cast<uint8>(table_data[i]);
    line_length += fprintf(out, "%d, ", c);
    if (i == table_data.size() - 1) {
      fprintf(out, "\n};\n");
    } else if (line_length >= 70) {
      fprintf(out, "\n");
      line_length = 0;
    }
  }
  fprintf(out, "\n}  // namespace net\n");
  fclose(out);

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>Correctly get ExtensionService out of EXTENSION_PROCESS_CRASHED notification.<commit_after><|endoftext|>


<commit_before>#include "vast/index.h"

#include <ze/type/regex.h>
#include "vast/logger.h"
#include "vast/fs/operations.h"
#include "vast/fs/fstream.h"
#include "vast/expression.h"

namespace vast {
namespace detail {

/// Picks the relevant subsets of the query expression and forwards them to
/// the index.
class picker : public expr::const_visitor
{
public:
  /// Constructs a picker with an index actor.
  picker(index::meta const& m, std::vector<ze::uuid>& ids)
    : meta_(m)
    , ids_(ids)
  {
  }

  virtual void visit(expr::node const&)
  {
    assert(! "should never happen");
  }

  virtual void visit(expr::extractor const&)
  {
    assert(! "should never happen");
  }

  virtual void visit(expr::timestamp_extractor const&)
  {
    assert(rhs_.which() == ze::timepoint_type);
    assert(op_ != nullptr);

    // If the time point is in the interval, we have to consider it.
    auto time = rhs_.get<ze::time_point>();
    for (auto& i : meta_.ranges)
      if (i.first.first >= time && i.first.second <= time)
        ids_.push_back(i.second);
  }

  virtual void visit(expr::name_extractor const& node)
  {
    assert(rhs_.which() == ze::string_type || rhs_.which() == ze::regex_type);
    assert(op_ != nullptr);

    for (auto& i : meta_.names)
    {
      if ((*op_)(i.first, rhs_))
        ids_.push_back(i.second);
    }
  }

  virtual void visit(expr::id_extractor const&)
  {
    /* Do exactly nothing. */
  }

  virtual void visit(expr::offset_extractor const&)
  {
    /* Do exactly nothing. */
  }

  virtual void visit(expr::exists const&)
  {
    /* Do exactly nothing. */
  }

  virtual void visit(expr::n_ary_operator const& n_ary)
  {
    assert(! "should never happen");
  }

  virtual void visit(expr::conjunction const& conj)
  {
    std::vector<ze::uuid> ids;

    // The first intersection operand has a free shot.
    auto i = conj.operands().begin();
    picker p(meta_, ids);
    (*i)->accept(p);
    std::sort(ids.begin(), ids.end());

    for (++i; i != conj.operands().end(); ++i)
    {
      std::vector<ze::uuid> result;
      picker p(meta_, result);
      (*i)->accept(p);

      std::sort(result.begin(), result.end());
      std::vector<ze::uuid> intersection;

      std::set_intersection(ids.begin(), ids.end(),
                     result.begin(), result.end(),
                     std::back_inserter(intersection));

      intersection.swap(ids);
    }

    ids_.swap(ids);
  }

  virtual void visit(expr::disjunction const& disj)
  {
    std::vector<ze::uuid> ids;
    for (auto& operand : disj.operands())
    {
      std::vector<ze::uuid> result;
      picker p(meta_, result);
      operand->accept(p);

      std::sort(result.begin(), result.end());
      std::vector<ze::uuid> unification;

      std::set_union(ids.begin(), ids.end(),
                     result.begin(), result.end(),
                     std::back_inserter(unification));

      unification.swap(ids);
    }

    ids_.swap(ids);
  }

  virtual void visit(expr::relational_operator const& op)
  {
    assert(op_ == nullptr);
    assert(rhs_ == ze::invalid);
    assert(op.operands().size() == 2);

    // We first save the RHS value,
    op.operands()[1]->accept(*this);

    // then save the predicate, ...
    op_ = &op.op();

    // ...and finally dispatch to the LHS extractor.
    op.operands()[0]->accept(*this);

    op_ = nullptr;
    rhs_ = ze::invalid;
  }

  virtual void visit(expr::constant const& c)
  {
    assert(c.ready());
    rhs_ = c.result();
  }

private:
  ze::value rhs_ = ze::invalid;
  expr::relational_operator::binary_predicate const* op_ = nullptr;
  index::meta const& meta_;
  std::vector<ze::uuid>& ids_;
};

} // namespace detail

index::index(cppa::actor_ptr archive, std::string directory)
  : dir_(std::move(directory))
  , archive_(archive)
{
  using namespace cppa;
  chaining(false);
  init_state = (
      on(atom("load")) >> [=]
      {
        LOG(verbose, index) << "spawning index @" << id();
        if (! fs::exists(dir_))
        {
          LOG(info, index)
            << "index @" << id() << " creates new directory " << dir_;
          fs::mkdir(dir_);
        }

        assert(fs::exists(dir_));
        fs::each_file_entry(
            dir_,
            [&](fs::path const& p)
            {
              fs::ifstream file(p, std::ios::binary | std::ios::in);
              ze::serialization::stream_iarchive ia(file);
              segment::header hdr;
              ia >> hdr;

              build(hdr);
            });
      },
      on(atom("hit"), atom("all")) >> [=]
      {
        if (ids_.empty())
        {
          reply(atom("miss"));
          return;
        }

        std::vector<ze::uuid> ids;
        std::copy(ids_.begin(), ids_.end(), std::back_inserter(ids));
        reply(atom("hit"), std::move(ids));
      },
      on(atom("hit"), arg_match) >> [=](expression const& expr)
      {
        if (ids_.empty())
        {
          reply(atom("miss"));
          return;
        }

        std::vector<ze::uuid> ids;
        detail::picker picker(meta_, ids);
        expr.accept(picker);

        if (ids.empty())
          reply(atom("miss"));
        else
          reply(atom("hit"), std::move(ids));

      },
      on(atom("build"), arg_match) >> [=](segment const& s)
      {
        process(s);
      },
      on(atom("shutdown")) >> [=]()
      {
        quit();
        LOG(verbose, index) << "index @" << id() << " terminated";
      });
}

void index::process(segment const& s)
{
  write(s);
  build(s.head());
}

void index::write(segment const& s)
{
  auto path = fs::path(dir_) / s.id().to_string();
  fs::ofstream file(path, std::ios::binary | std::ios::out);
  ze::serialization::stream_oarchive oa(file);
  oa << s.head();

  LOG(verbose, index)
    << "index @" << id() << " wrote segment header to " << path;
}

void index::build(segment::header const& hdr)
{
  LOG(verbose, index) << "index @" << id()
    << " builds in-memory indexes for segment " << hdr.id;

  assert(ids_.count(hdr.id) == 0);
  ids_.insert(hdr.id);

// TODO: Remove as soon as newer GCC versions have adopted r181022.
#ifdef __clang__
  for (auto& event : hdr.event_names)
    meta_.names.emplace(event, hdr.id);

#else
  for (auto& event : hdr.event_names)
    meta_.names.insert({event, hdr.id});
#endif

  meta_.ranges.insert({{hdr.start, hdr.end}, hdr.id});
}

} // namespace vast
<commit_msg>Better support time ranges.<commit_after>#include "vast/index.h"

#include <ze/type/regex.h>
#include "vast/logger.h"
#include "vast/fs/operations.h"
#include "vast/fs/fstream.h"
#include "vast/expression.h"

namespace vast {
namespace detail {

/// Picks the relevant subsets of the query expression and forwards them to
/// the index.
class picker : public expr::const_visitor
{
public:
  /// Constructs a picker with an index actor.
  picker(index::meta const& m, std::vector<ze::uuid>& ids)
    : meta_(m)
    , ids_(ids)
  {
  }

  virtual void visit(expr::node const&)
  {
    assert(! "should never happen");
  }

  virtual void visit(expr::extractor const&)
  {
    assert(! "should never happen");
  }

  virtual void visit(expr::timestamp_extractor const&)
  {
    assert(rhs_.which() == ze::timepoint_type);
    assert(op_ != nullptr);

    // If the time point is in the interval, we have to consider it.
    for (auto& i : meta_.ranges)
      if ((*op_)(i.first.first, rhs_) || (*op_)(i.first.first, rhs_))
        ids_.push_back(i.second);
  }

  virtual void visit(expr::name_extractor const& node)
  {
    assert(rhs_.which() == ze::string_type || rhs_.which() == ze::regex_type);
    assert(op_ != nullptr);

    for (auto& i : meta_.names)
    {
      if ((*op_)(i.first, rhs_))
        ids_.push_back(i.second);
    }
  }

  virtual void visit(expr::id_extractor const&)
  {
    /* Do exactly nothing. */
  }

  virtual void visit(expr::offset_extractor const&)
  {
    /* Do exactly nothing. */
  }

  virtual void visit(expr::exists const&)
  {
    /* Do exactly nothing. */
  }

  virtual void visit(expr::n_ary_operator const& n_ary)
  {
    assert(! "should never happen");
  }

  virtual void visit(expr::conjunction const& conj)
  {
    std::vector<ze::uuid> ids;

    // The first intersection operand has a free shot.
    auto i = conj.operands().begin();
    picker p(meta_, ids);
    (*i)->accept(p);
    std::sort(ids.begin(), ids.end());

    for (++i; i != conj.operands().end(); ++i)
    {
      std::vector<ze::uuid> result;
      picker p(meta_, result);
      (*i)->accept(p);

      std::sort(result.begin(), result.end());
      std::vector<ze::uuid> intersection;

      std::set_intersection(ids.begin(), ids.end(),
                     result.begin(), result.end(),
                     std::back_inserter(intersection));

      intersection.swap(ids);
    }

    ids_.swap(ids);
  }

  virtual void visit(expr::disjunction const& disj)
  {
    std::vector<ze::uuid> ids;
    for (auto& operand : disj.operands())
    {
      std::vector<ze::uuid> result;
      picker p(meta_, result);
      operand->accept(p);

      std::sort(result.begin(), result.end());
      std::vector<ze::uuid> unification;

      std::set_union(ids.begin(), ids.end(),
                     result.begin(), result.end(),
                     std::back_inserter(unification));

      unification.swap(ids);
    }

    ids_.swap(ids);
  }

  virtual void visit(expr::relational_operator const& op)
  {
    assert(op_ == nullptr);
    assert(rhs_ == ze::invalid);
    assert(op.operands().size() == 2);

    // We first save the RHS value,
    op.operands()[1]->accept(*this);

    // then save the predicate, ...
    op_ = &op.op();

    // ...and finally dispatch to the LHS extractor.
    op.operands()[0]->accept(*this);

    op_ = nullptr;
    rhs_ = ze::invalid;
  }

  virtual void visit(expr::constant const& c)
  {
    assert(c.ready());
    rhs_ = c.result();
  }

private:
  ze::value rhs_ = ze::invalid;
  expr::relational_operator::binary_predicate const* op_ = nullptr;
  index::meta const& meta_;
  std::vector<ze::uuid>& ids_;
};

} // namespace detail

index::index(cppa::actor_ptr archive, std::string directory)
  : dir_(std::move(directory))
  , archive_(archive)
{
  using namespace cppa;
  chaining(false);
  init_state = (
      on(atom("load")) >> [=]
      {
        LOG(verbose, index) << "spawning index @" << id();
        if (! fs::exists(dir_))
        {
          LOG(info, index)
            << "index @" << id() << " creates new directory " << dir_;
          fs::mkdir(dir_);
        }

        assert(fs::exists(dir_));
        fs::each_file_entry(
            dir_,
            [&](fs::path const& p)
            {
              fs::ifstream file(p, std::ios::binary | std::ios::in);
              ze::serialization::stream_iarchive ia(file);
              segment::header hdr;
              ia >> hdr;

              build(hdr);
            });
      },
      on(atom("hit"), atom("all")) >> [=]
      {
        if (ids_.empty())
        {
          reply(atom("miss"));
          return;
        }

        std::vector<ze::uuid> ids;
        std::copy(ids_.begin(), ids_.end(), std::back_inserter(ids));
        reply(atom("hit"), std::move(ids));
      },
      on(atom("hit"), arg_match) >> [=](expression const& expr)
      {
        if (ids_.empty())
        {
          reply(atom("miss"));
          return;
        }

        std::vector<ze::uuid> ids;
        detail::picker picker(meta_, ids);
        expr.accept(picker);

        if (ids.empty())
          reply(atom("miss"));
        else
          reply(atom("hit"), std::move(ids));

      },
      on(atom("build"), arg_match) >> [=](segment const& s)
      {
        process(s);
      },
      on(atom("shutdown")) >> [=]()
      {
        quit();
        LOG(verbose, index) << "index @" << id() << " terminated";
      });
}

void index::process(segment const& s)
{
  write(s);
  build(s.head());
}

void index::write(segment const& s)
{
  auto path = fs::path(dir_) / s.id().to_string();
  fs::ofstream file(path, std::ios::binary | std::ios::out);
  ze::serialization::stream_oarchive oa(file);
  oa << s.head();

  LOG(verbose, index)
    << "index @" << id() << " wrote segment header to " << path;
}

void index::build(segment::header const& hdr)
{
  LOG(verbose, index) << "index @" << id()
    << " builds in-memory indexes for segment " << hdr.id;

  assert(ids_.count(hdr.id) == 0);
  ids_.insert(hdr.id);

// TODO: Remove as soon as newer GCC versions have adopted r181022.
#ifdef __clang__
  for (auto& event : hdr.event_names)
    meta_.names.emplace(event, hdr.id);

#else
  for (auto& event : hdr.event_names)
    meta_.names.insert({event, hdr.id});
#endif

  meta_.ranges.insert({{hdr.start, hdr.end}, hdr.id});
}

} // namespace vast
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: randrwrapper.cxx,v $
 *
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifdef USE_RANDR

#include "prex.h"
#include <X11/extensions/Xrandr.h>
#include "postx.h"

#include "osl/module.h"
#include "rtl/ustring.hxx"

namespace
{
class RandRWrapper
{
    oslModule m_pRandRLib;

    // function pointers
    Bool(*m_pXRRQueryExtension)(Display*,int*,int*);
    Status(*m_pXRRQueryVersion)(Display*,int*,int*);
    XRRScreenConfiguration*(*m_pXRRGetScreenInfo)(Display*,Drawable);
    void(*m_pXRRFreeScreenConfigInfo)(XRRScreenConfiguration*);
    void(*m_pXRRSelectInput)(Display*,XLIB_Window,int);
    int(*m_pXRRUpdateConfiguration)(XEvent*);
    XRRScreenSize*(*m_pXRRSizes)(Display*,int,int*);
    XRRScreenSize*(*m_pXRRConfigSizes)(XRRScreenConfiguration*,int*);
    SizeID(*m_pXRRConfigCurrentConfiguration)(XRRScreenConfiguration*,Rotation*);

    bool m_bValid;

    void initFromModule();

    RandRWrapper(Display*);
    ~RandRWrapper();
public:
    static RandRWrapper& get(Display*);
    static void releaseWrapper();

    Bool XRRQueryExtension(Display* i_pDisp, int* o_event_base, int* o_error_base )
    {
        Bool bRet = False;
        if( m_bValid )
            bRet = m_pXRRQueryExtension( i_pDisp, o_event_base, o_error_base );
        return bRet;
    }
    Status XRRQueryVersion( Display* i_pDisp, int* o_major, int* o_minor )
    {
        return m_bValid ? m_pXRRQueryVersion( i_pDisp, o_major, o_minor ) : 0;
    }
    XRRScreenConfiguration* XRRGetScreenInfo( Display* i_pDisp, Drawable i_aDrawable )
    {
        return m_bValid ? m_pXRRGetScreenInfo( i_pDisp, i_aDrawable ) : NULL;
    }
    void XRRFreeScreenConfigInfo( XRRScreenConfiguration* i_pConfig )
    {
        if( m_bValid )
            m_pXRRFreeScreenConfigInfo( i_pConfig );
    }
    void XRRSelectInput( Display* i_pDisp, XLIB_Window i_window, int i_nMask )
    {
        if( m_bValid )
            m_pXRRSelectInput( i_pDisp, i_window, i_nMask );
    }
    int XRRUpdateConfiguration( XEvent* i_pEvent )
    {
        return m_bValid ? m_pXRRUpdateConfiguration( i_pEvent ) : 0;
    }
    XRRScreenSize* XRRSizes( Display* i_pDisp, int i_screen, int* o_nscreens )
    {
        return m_bValid ? m_pXRRSizes( i_pDisp, i_screen, o_nscreens ) : NULL;
    }
    XRRScreenSize* XRRConfigSizes( XRRScreenConfiguration* i_pConfig, int* o_nSizes )
    {
        return m_bValid ? m_pXRRConfigSizes( i_pConfig, o_nSizes ) : NULL;
    }
    SizeID XRRConfigCurrentConfiguration( XRRScreenConfiguration* i_pConfig, Rotation* o_pRot )
    {
        return m_bValid ? m_pXRRConfigCurrentConfiguration( i_pConfig, o_pRot ) : 0;
    }
};
}

void RandRWrapper::initFromModule()
{
    m_pXRRQueryExtension = (Bool(*)(Display*,int*,int*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRQueryExtension" );
    m_pXRRQueryVersion = (Status(*)(Display*,int*,int*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRQueryVersion" );
    m_pXRRGetScreenInfo = (XRRScreenConfiguration*(*)(Display*,Drawable))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRGetScreenInfo" );
    m_pXRRFreeScreenConfigInfo = (void(*)(XRRScreenConfiguration*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRFreeScreenConfigInfo" );
    m_pXRRSelectInput = (void(*)(Display*,XLIB_Window,int))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRSelectInput" );
    m_pXRRUpdateConfiguration = (int(*)(XEvent*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRUpdateConfiguration" );
    m_pXRRSizes = (XRRScreenSize*(*)(Display*,int,int*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRSizes" );
    m_pXRRConfigSizes = (XRRScreenSize*(*)(XRRScreenConfiguration*,int*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRConfigSizes" );
    m_pXRRConfigCurrentConfiguration = (SizeID(*)(XRRScreenConfiguration*,Rotation*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRConfigCurrentConfiguration" );

    m_bValid = m_pXRRQueryExtension             &&
               m_pXRRQueryVersion               &&
               m_pXRRGetScreenInfo              &&
               m_pXRRFreeScreenConfigInfo       &&
               m_pXRRSelectInput                &&
               m_pXRRUpdateConfiguration        &&
               m_pXRRSizes                      &&
               m_pXRRConfigSizes                &&
               m_pXRRConfigCurrentConfiguration
               ;
}

RandRWrapper::RandRWrapper( Display* pDisplay ) :
        m_pRandRLib( NULL ),
        m_pXRRQueryExtension( NULL ),
        m_pXRRQueryVersion( NULL ),
        m_pXRRGetScreenInfo( NULL ),
        m_pXRRFreeScreenConfigInfo( NULL ),
        m_pXRRSelectInput( NULL ),
        m_pXRRUpdateConfiguration( NULL ),
        m_pXRRSizes( NULL ),
        m_pXRRConfigSizes( NULL ),
        m_pXRRConfigCurrentConfiguration( NULL ),
        m_bValid( false )
{
    // first try in process space (e.g. gtk links that ?)
    initFromModule();
    if( ! m_bValid )
    {
        rtl::OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( "libXrandr.so.2" ) );
        m_pRandRLib = osl_loadModule( aLibName.pData, SAL_LOADMODULE_DEFAULT );
        initFromModule();
    }
    if( m_bValid )
    {
        int nEventBase = 0, nErrorBase = 0;
        if( ! m_pXRRQueryExtension( pDisplay, &nEventBase, &nErrorBase ) )
            m_bValid = false;
    }
}

RandRWrapper::~RandRWrapper()
{
    if( m_pRandRLib )
        osl_unloadModule( m_pRandRLib );
}

static RandRWrapper* pWrapper = NULL;

RandRWrapper& RandRWrapper::get( Display* i_pDisplay )
{
    if( ! pWrapper )
        pWrapper = new RandRWrapper( i_pDisplay );
    return *pWrapper;
}

void RandRWrapper::releaseWrapper()
{
    delete pWrapper;
    pWrapper = NULL;
}

#endif

#include "saldisp.hxx"

void SalDisplay::InitRandR( XLIB_Window aRoot ) const
{
    #ifdef USE_RANDR
    if( m_bUseRandRWrapper )
        RandRWrapper::get( GetDisplay() ).XRRSelectInput( GetDisplay(), aRoot, RRScreenChangeNotifyMask );
    #else
    (void)aRoot;
    #endif
}

void SalDisplay::DeInitRandR()
{
    #ifdef USE_RANDR
    if( m_bUseRandRWrapper )
        RandRWrapper::releaseWrapper();
    #endif
}

int SalDisplay::processRandREvent( XEvent* pEvent )
{
    int nRet = 0;
    #ifdef USE_RANDR
    if( m_bUseRandRWrapper && pWrapper )
    {
        nRet = pWrapper->XRRUpdateConfiguration( pEvent );
        if( nRet == 1 && pEvent->type != ConfigureNotify) // this should then be a XRRScreenChangeNotifyEvent
        {
            // update screens
            for( size_t i = 0; i < m_aScreens.size(); i++ )
            {
                if( m_aScreens[i].m_bInit )
                {
                    XRRScreenConfiguration *pConfig = NULL;
                    XRRScreenSize *pSizes = NULL;
                    int nSizes = 0;
                    Rotation nRot = 0;
                    SizeID nId = 0;

                    pConfig = pWrapper->XRRGetScreenInfo( GetDisplay(), m_aScreens[i].m_aRoot );
                    nId = pWrapper->XRRConfigCurrentConfiguration( pConfig, &nRot );
                    pSizes = pWrapper->XRRConfigSizes( pConfig, &nSizes );
                    XRRScreenSize *pTargetSize = pSizes + nId;

                    m_aScreens[i].m_aSize = Size( pTargetSize->width, pTargetSize->height );

                    pWrapper->XRRFreeScreenConfigInfo( pConfig );

                    #if OSL_DEBUG_LEVEL > 1
                    fprintf( stderr, "screen %d changed to size %dx%d\n", i, pTargetSize->width, pTargetSize->height );
                    #endif
                }
            }
        }
    }
    #else
    (void)pEvent;
    #endif
    return nRet;
}
<commit_msg>INTEGRATION: CWS vcl90 (1.3.58); FILE MERGED 2008/06/24 09:01:04 pl 1.3.58.2: #i90809# Xrandr link modifications (thanks thb) 2008/06/04 16:45:37 pl 1.3.58.1: remove warnings<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: randrwrapper.cxx,v $
 *
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifdef USE_RANDR

#include "prex.h"
#include <X11/extensions/Xrandr.h>
#include "postx.h"

#include "osl/module.h"
#include "rtl/ustring.hxx"

namespace
{

# ifdef XRANDR_DLOPEN

class RandRWrapper
{
    oslModule m_pRandRLib;

    // function pointers
    Bool(*m_pXRRQueryExtension)(Display*,int*,int*);
    Status(*m_pXRRQueryVersion)(Display*,int*,int*);
    XRRScreenConfiguration*(*m_pXRRGetScreenInfo)(Display*,Drawable);
    void(*m_pXRRFreeScreenConfigInfo)(XRRScreenConfiguration*);
    void(*m_pXRRSelectInput)(Display*,XLIB_Window,int);
    int(*m_pXRRUpdateConfiguration)(XEvent*);
    XRRScreenSize*(*m_pXRRSizes)(Display*,int,int*);
    XRRScreenSize*(*m_pXRRConfigSizes)(XRRScreenConfiguration*,int*);
    SizeID(*m_pXRRConfigCurrentConfiguration)(XRRScreenConfiguration*,Rotation*);
    int(*m_pXRRRootToScreen)(Display*, XLIB_Window);

    bool m_bValid;

    void initFromModule();

    RandRWrapper(Display*);
    ~RandRWrapper();
public:
    static RandRWrapper& get(Display*);
    static void releaseWrapper();

    Bool XRRQueryExtension(Display* i_pDisp, int* o_event_base, int* o_error_base )
    {
        Bool bRet = False;
        if( m_bValid )
            bRet = m_pXRRQueryExtension( i_pDisp, o_event_base, o_error_base );
        return bRet;
    }
    Status XRRQueryVersion( Display* i_pDisp, int* o_major, int* o_minor )
    {
        return m_bValid ? m_pXRRQueryVersion( i_pDisp, o_major, o_minor ) : 0;
    }
    XRRScreenConfiguration* XRRGetScreenInfo( Display* i_pDisp, Drawable i_aDrawable )
    {
        return m_bValid ? m_pXRRGetScreenInfo( i_pDisp, i_aDrawable ) : NULL;
    }
    void XRRFreeScreenConfigInfo( XRRScreenConfiguration* i_pConfig )
    {
        if( m_bValid )
            m_pXRRFreeScreenConfigInfo( i_pConfig );
    }
    void XRRSelectInput( Display* i_pDisp, XLIB_Window i_window, int i_nMask )
    {
        if( m_bValid )
            m_pXRRSelectInput( i_pDisp, i_window, i_nMask );
    }
    int XRRUpdateConfiguration( XEvent* i_pEvent )
    {
        return m_bValid ? m_pXRRUpdateConfiguration( i_pEvent ) : 0;
    }
    XRRScreenSize* XRRSizes( Display* i_pDisp, int i_screen, int* o_nscreens )
    {
        return m_bValid ? m_pXRRSizes( i_pDisp, i_screen, o_nscreens ) : NULL;
    }
    XRRScreenSize* XRRConfigSizes( XRRScreenConfiguration* i_pConfig, int* o_nSizes )
    {
        return m_bValid ? m_pXRRConfigSizes( i_pConfig, o_nSizes ) : NULL;
    }
    SizeID XRRConfigCurrentConfiguration( XRRScreenConfiguration* i_pConfig, Rotation* o_pRot )
    {
        return m_bValid ? m_pXRRConfigCurrentConfiguration( i_pConfig, o_pRot ) : 0;
    }
    int XRRRootToScreen( Display *dpy, XLIB_Window root )
    {
        return m_bValid ? m_pXRRRootToScreen( dpy, root ) : -1;
    }
};

void RandRWrapper::initFromModule()
{
    m_pXRRQueryExtension = (Bool(*)(Display*,int*,int*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRQueryExtension" );
    m_pXRRQueryVersion = (Status(*)(Display*,int*,int*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRQueryVersion" );
    m_pXRRGetScreenInfo = (XRRScreenConfiguration*(*)(Display*,Drawable))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRGetScreenInfo" );
    m_pXRRFreeScreenConfigInfo = (void(*)(XRRScreenConfiguration*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRFreeScreenConfigInfo" );
    m_pXRRSelectInput = (void(*)(Display*,XLIB_Window,int))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRSelectInput" );
    m_pXRRUpdateConfiguration = (int(*)(XEvent*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRUpdateConfiguration" );
    m_pXRRSizes = (XRRScreenSize*(*)(Display*,int,int*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRSizes" );
    m_pXRRConfigSizes = (XRRScreenSize*(*)(XRRScreenConfiguration*,int*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRConfigSizes" );
    m_pXRRConfigCurrentConfiguration = (SizeID(*)(XRRScreenConfiguration*,Rotation*))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRConfigCurrentConfiguration" );
    m_pXRRRootToScreen = (int(*)(Display*,XLIB_Window))osl_getAsciiFunctionSymbol( m_pRandRLib, "XRRRootToScreen" );

    m_bValid = m_pXRRQueryExtension             &&
               m_pXRRQueryVersion               &&
               m_pXRRGetScreenInfo              &&
               m_pXRRFreeScreenConfigInfo       &&
               m_pXRRSelectInput                &&
               m_pXRRUpdateConfiguration        &&
               m_pXRRSizes                      &&
               m_pXRRConfigSizes                &&
               m_pXRRConfigCurrentConfiguration &&
               m_pXRRRootToScreen
               ;
}

RandRWrapper::RandRWrapper( Display* pDisplay ) :
        m_pRandRLib( NULL ),
        m_pXRRQueryExtension( NULL ),
        m_pXRRQueryVersion( NULL ),
        m_pXRRGetScreenInfo( NULL ),
        m_pXRRFreeScreenConfigInfo( NULL ),
        m_pXRRSelectInput( NULL ),
        m_pXRRUpdateConfiguration( NULL ),
        m_pXRRSizes( NULL ),
        m_pXRRConfigSizes( NULL ),
        m_pXRRConfigCurrentConfiguration( NULL ),
        m_pXRRRootToScreen( NULL ),
        m_bValid( false )
{
    // first try in process space (e.g. gtk links that ?)
    initFromModule();
    if( ! m_bValid )
    {
        rtl::OUString aLibName( RTL_CONSTASCII_USTRINGPARAM( "libXrandr.so.2" ) );
        m_pRandRLib = osl_loadModule( aLibName.pData, SAL_LOADMODULE_DEFAULT );
        initFromModule();
    }
    if( m_bValid )
    {
        int nEventBase = 0, nErrorBase = 0;
        if( ! m_pXRRQueryExtension( pDisplay, &nEventBase, &nErrorBase ) )
            m_bValid = false;
    }
}

RandRWrapper::~RandRWrapper()
{
    if( m_pRandRLib )
        osl_unloadModule( m_pRandRLib );
}

static RandRWrapper* pWrapper = NULL;

RandRWrapper& RandRWrapper::get( Display* i_pDisplay )
{
    if( ! pWrapper )
        pWrapper = new RandRWrapper( i_pDisplay );
    return *pWrapper;
}

void RandRWrapper::releaseWrapper()
{
    delete pWrapper;
    pWrapper = NULL;
}

# else

class RandRWrapper
{
    bool m_bValid;

    RandRWrapper(Display*);
public:
    static RandRWrapper& get(Display*);
    static void releaseWrapper();

    Bool XRRQueryExtension(Display* i_pDisp, int* o_event_base, int* o_error_base )
    {
        Bool bRet = False;
        if( m_bValid )
            bRet = ::XRRQueryExtension( i_pDisp, o_event_base, o_error_base );
        return bRet;
    }
    Status XRRQueryVersion( Display* i_pDisp, int* o_major, int* o_minor )
    {
        return m_bValid ? ::XRRQueryVersion( i_pDisp, o_major, o_minor ) : 0;
    }
    XRRScreenConfiguration* XRRGetScreenInfo( Display* i_pDisp, Drawable i_aDrawable )
    {
        return m_bValid ? ::XRRGetScreenInfo( i_pDisp, i_aDrawable ) : NULL;
    }
    void XRRFreeScreenConfigInfo( XRRScreenConfiguration* i_pConfig )
    {
        if( m_bValid )
            ::XRRFreeScreenConfigInfo( i_pConfig );
    }
    void XRRSelectInput( Display* i_pDisp, XLIB_Window i_window, int i_nMask )
    {
        if( m_bValid )
            ::XRRSelectInput( i_pDisp, i_window, i_nMask );
    }
    int XRRUpdateConfiguration( XEvent* i_pEvent )
    {
        return m_bValid ? ::XRRUpdateConfiguration( i_pEvent ) : 0;
    }
    XRRScreenSize* XRRSizes( Display* i_pDisp, int i_screen, int* o_nscreens )
    {
        return m_bValid ? ::XRRSizes( i_pDisp, i_screen, o_nscreens ) : NULL;
    }
    XRRScreenSize* XRRConfigSizes( XRRScreenConfiguration* i_pConfig, int* o_nSizes )
    {
        return m_bValid ? ::XRRConfigSizes( i_pConfig, o_nSizes ) : NULL;
    }
    SizeID XRRConfigCurrentConfiguration( XRRScreenConfiguration* i_pConfig, Rotation* o_pRot )
    {
        return m_bValid ? ::XRRConfigCurrentConfiguration( i_pConfig, o_pRot ) : 0;
    }
    int XRRRootToScreen( Display *dpy, XLIB_Window root )
    {
        return m_bValid ? ::XRRRootToScreen( dpy, root ) : -1;
    }
};

RandRWrapper::RandRWrapper( Display* pDisplay ) :
    m_bValid( true )
{
    int nEventBase = 0, nErrorBase = 0;
    if( !XRRQueryExtension( pDisplay, &nEventBase, &nErrorBase ) )
        m_bValid = false;
}

static RandRWrapper* pWrapper = NULL;

RandRWrapper& RandRWrapper::get( Display* i_pDisplay )
{
    if( ! pWrapper )
        pWrapper = new RandRWrapper( i_pDisplay );
    return *pWrapper;
}

void RandRWrapper::releaseWrapper()
{
    delete pWrapper;
    pWrapper = NULL;
}

#endif

} // namespace

#endif

#include "saldisp.hxx"

void SalDisplay::InitRandR( XLIB_Window aRoot ) const
{
    #ifdef USE_RANDR
    if( m_bUseRandRWrapper )
        RandRWrapper::get( GetDisplay() ).XRRSelectInput( GetDisplay(), aRoot, RRScreenChangeNotifyMask );
    #else
    (void)aRoot;
    #endif
}

void SalDisplay::DeInitRandR()
{
    #ifdef USE_RANDR
    if( m_bUseRandRWrapper )
        RandRWrapper::releaseWrapper();
#if OSL_DEBUG_LEVEL > 1
    fprintf( stderr, "SalDisplay::DeInitRandR()\n" );
#endif
    #endif
}

int SalDisplay::processRandREvent( XEvent* pEvent )
{
    int nRet = 0;
    #ifdef USE_RANDR
    XConfigureEvent* pCnfEvent=(XConfigureEvent*)pEvent;
    if( m_bUseRandRWrapper && pWrapper && pWrapper->XRRRootToScreen(GetDisplay(),pCnfEvent->window) != -1 )
    {
        nRet = pWrapper->XRRUpdateConfiguration( pEvent );
        if( nRet == 1 && pEvent->type != ConfigureNotify) // this should then be a XRRScreenChangeNotifyEvent
        {
            // update screens
            for( size_t i = 0; i < m_aScreens.size(); i++ )
            {
                if( m_aScreens[i].m_bInit )
                {
                    XRRScreenConfiguration *pConfig = NULL;
                    XRRScreenSize *pSizes = NULL;
                    int nSizes = 0;
                    Rotation nRot = 0;
                    SizeID nId = 0;

                    pConfig = pWrapper->XRRGetScreenInfo( GetDisplay(), m_aScreens[i].m_aRoot );
                    nId = pWrapper->XRRConfigCurrentConfiguration( pConfig, &nRot );
                    pSizes = pWrapper->XRRConfigSizes( pConfig, &nSizes );
                    XRRScreenSize *pTargetSize = pSizes + nId;

                    m_aScreens[i].m_aSize = Size( pTargetSize->width, pTargetSize->height );

                    pWrapper->XRRFreeScreenConfigInfo( pConfig );

                    #if OSL_DEBUG_LEVEL > 1
                    fprintf( stderr, "screen %d changed to size %dx%d\n", (int)i, (int)pTargetSize->width, (int)pTargetSize->height );
                    #endif
                }
            }
        }
    }
    #else
    (void)pEvent;
    #endif
    return nRet;
}
<|endoftext|>


<commit_before>//
// Created by hacht on 4/25/17.
//

#include <cuda_runtime_api.h>
#include <iostream>
#include "../../simpleCNN/simpleCNN.h"

#include "cuda.h"

using namespace simpleCNN;

using dropout = Dropout_layer;
using conv    = Convolutional_layer;
using maxpool = Maxpooling_layer;
using fully   = Connected_layer;
using network = Network<Sequential>;
using adam    = Adam<float_t>;
using relu    = Activation_layer;
using softmax = loss::Softmax;

static bool train_mnist(const size_t batch_size, const size_t epoch, const std::string data, const std::string result) {
  /** Mnist specific parameters  */
  size_t mnist_image_row = 28;
  size_t mnist_image_col = 28;
  size_t mnist_image_num = 60000;
  size_t mnist_test_num  = 10000;
  size_t in_width        = 28;
  size_t in_height       = 28;
  size_t subset          = 1;

  /** Parse mnist */
  tensor_t labels({mnist_image_num / subset, 1, 1, 1});
  tensor_t images({mnist_image_num / subset, 1, in_height, in_width});
  tensor_t test_images({mnist_test_num / subset, 1, in_height, in_width});
  tensor_t test_labels({mnist_test_num, 1, 1, 1});

  float_t min = -1.0f;
  float_t max = 1.0f;
  images.fill(min);

  parse_mnist_images(data + "/train-images.idx3-ubyte", &images, min, max, 0, 0, subset);
  parse_mnist_labels(data + "/train-labels.idx1-ubyte", &labels, subset);
  parse_mnist_images(data + "/t10k-images.idx3-ubyte", &test_images, min, max, 0, 0, subset);
  parse_mnist_labels(data + "/t10k-labels.idx1-ubyte", &test_labels);

  /** Pre-processing */
  std::vector<float_t> mean_and_std = zero_mean_unit_variance(images);
  size_t minibatch_size             = batch_size;
  size_t epochs                     = epoch;
  mean_and_std.push_back(float_t(batch_size));
  mean_and_std.push_back(float_t(epoch));

  zero_mean_unit_variance(test_images, mean_and_std[0], mean_and_std[1]);

  /** Split data into a training and validation set */
  float_t training_validation_split_ratio = 0.75;
  size_t training_set_size                = (mnist_image_num / subset) * training_validation_split_ratio;
  size_t validation_set_size = std::floor((mnist_image_num / subset) * (1 - training_validation_split_ratio) + 0.5);

  tensor_t train_images({training_set_size, 1, in_height, in_width});
  tensor_t train_labels({training_set_size, 1, 1, 1});
  tensor_t validation_images({validation_set_size, 1, in_height, in_width});
  tensor_t validation_labels({validation_set_size, 1, 1, 1});

  split_training_validation(images, train_images, validation_images, training_validation_split_ratio);
  split_training_validation(labels, train_labels, validation_labels, training_validation_split_ratio);

  /*
  for (size_t sample = 0; sample < 100; sample++) {
    auto img = test_images.subView({sample}, {1, 1, in_height, in_width});
    auto lab = test_labels.subView({sample}, {1, 1, 1, 1});

    display_gray_image(img, *lab.host_begin(), mean_and_std.at(0), mean_and_std.at(1));
  } */

  /** Call-back for clocking */
  auto on_enumerate_minibatch = [&](time_t t) {
    std::cout << (float_t)(clock() - t) / CLOCKS_PER_SEC << "s elapsed." << std::endl;
  };

  auto on_enumerate_epoch = [&](size_t epoch) { std::cout << epoch + 1 << std::endl; };

  /** Define network architecture and optimizer */
  network net;
  float_t dropout_rate = 0.75;

  /* GPU - 21.56s 429MiB */
  net << conv(28, 28, 1, minibatch_size, 5, 32, 1, 2, true, core::backend_t::gpu, true)
      << relu(core::activation_t::relu, core::backend_t::gpu)
      << maxpool(28, 28, 32, minibatch_size, 2, 2, 2, 2, core::backend_t::gpu)
      << conv(14, 14, 32, minibatch_size, 5, 64, 1, 2, true, core::backend_t::gpu, true)
      << relu(core::activation_t::relu, core::backend_t::gpu)
      << maxpool(14, 14, 64, minibatch_size, 2, 2, 2, 2, core::backend_t::gpu)
      << fully(7 * 7 * 64, 1024, minibatch_size, true, core::backend_t::gpu, true)
      << relu(core::activation_t::relu, core::backend_t::gpu) << dropout(dropout_rate)
      << fully(1024, 10, minibatch_size, true, core::backend_t::gpu, true) << softmax();

  /* CPU - 902.74s
  net << conv(28, 28, 1, minibatch_size, 5, 32, 1, 2, true) << relu(core::activation_t::relu)
   << maxpool(28, 28, 32, minibatch_size)
   << conv(14, 14, 32, minibatch_size, 5, 64, 1, 2, true) << relu(core::activation_t::relu)
   << maxpool(14, 14, 64, minibatch_size)
   << fully(7 * 7 * 64, 1024, minibatch_size, true) << relu(core::activation_t::relu)
   << dropout(dropout_rate)
   << fully(1024, 10, minibatch_size, true) << softmax();
   */

  adam a;
  /** Train and save results */
  net.train<adam>(a, train_images, train_labels, validation_images, validation_labels, minibatch_size, epochs,
                  on_enumerate_minibatch, on_enumerate_epoch, true);
  net.save_results(mean_and_std, result);
  net.test_network(test_images, test_labels, minibatch_size, 10, result);

  return true;
}

int main(int argc, char* argv[]) {
  size_t expect = 5;
  if (argc < expect) {
    print("To few arguments, expted" + std::to_string(expect) + "\n");
    print("Usage: ./example_mnist batch_size epoch data_path store_results\n");
    print("Example usage: ./example_mnist 100 50 ~/data ~/results\n");
    return -1;
  }

  size_t batch_size  = atoi(argv[1]);  // use 50 or 100 etc
  size_t epoch       = atoi(argv[2]);
  std::string data   = argv[3];
  std::string result = argv[4];

  /** Let's go! */
  if (train_mnist(batch_size, epoch, data, result)) {
    return 0;
  }

  return -1;
}
<commit_msg>minor error fixed<commit_after>//
// Created by hacht on 4/25/17.
//

#include <iostream>
#include "../../simpleCNN/simpleCNN.h"

using namespace simpleCNN;

using dropout = Dropout_layer;
using conv    = Convolutional_layer;
using maxpool = Maxpooling_layer;
using fully   = Connected_layer;
using network = Network<Sequential>;
using adam    = Adam<float_t>;
using relu    = Activation_layer;
using softmax = loss::Softmax;

static bool train_mnist(const size_t batch_size, const size_t epoch, const std::string data, const std::string result) {
  /** Mnist specific parameters  */
  size_t mnist_image_row = 28;
  size_t mnist_image_col = 28;
  size_t mnist_image_num = 60000;
  size_t mnist_test_num  = 10000;
  size_t in_width        = 28;
  size_t in_height       = 28;
  size_t subset          = 1;

  /** Parse mnist */
  tensor_t labels({mnist_image_num / subset, 1, 1, 1});
  tensor_t images({mnist_image_num / subset, 1, in_height, in_width});
  tensor_t test_images({mnist_test_num / subset, 1, in_height, in_width});
  tensor_t test_labels({mnist_test_num, 1, 1, 1});

  float_t min = -1.0f;
  float_t max = 1.0f;
  images.fill(min);

  parse_mnist_images(data + "/train-images.idx3-ubyte", &images, min, max, 0, 0, subset);
  parse_mnist_labels(data + "/train-labels.idx1-ubyte", &labels, subset);
  parse_mnist_images(data + "/t10k-images.idx3-ubyte", &test_images, min, max, 0, 0, subset);
  parse_mnist_labels(data + "/t10k-labels.idx1-ubyte", &test_labels);

  /** Pre-processing */
  std::vector<float_t> mean_and_std = zero_mean_unit_variance(images);
  size_t minibatch_size             = batch_size;
  size_t epochs                     = epoch;
  mean_and_std.push_back(float_t(batch_size));
  mean_and_std.push_back(float_t(epoch));

  zero_mean_unit_variance(test_images, mean_and_std[0], mean_and_std[1]);

  /** Split data into a training and validation set */
  float_t training_validation_split_ratio = 0.75;
  size_t training_set_size                = (mnist_image_num / subset) * training_validation_split_ratio;
  size_t validation_set_size = std::floor((mnist_image_num / subset) * (1 - training_validation_split_ratio) + 0.5);

  tensor_t train_images({training_set_size, 1, in_height, in_width});
  tensor_t train_labels({training_set_size, 1, 1, 1});
  tensor_t validation_images({validation_set_size, 1, in_height, in_width});
  tensor_t validation_labels({validation_set_size, 1, 1, 1});

  split_training_validation(images, train_images, validation_images, training_validation_split_ratio);
  split_training_validation(labels, train_labels, validation_labels, training_validation_split_ratio);

  /*
  for (size_t sample = 0; sample < 100; sample++) {
    auto img = test_images.subView({sample}, {1, 1, in_height, in_width});
    auto lab = test_labels.subView({sample}, {1, 1, 1, 1});

    display_gray_image(img, *lab.host_begin(), mean_and_std.at(0), mean_and_std.at(1));
  } */

  /** Call-back for clocking */
  auto on_enumerate_minibatch = [&](time_t t) {
    std::cout << (float_t)(clock() - t) / CLOCKS_PER_SEC << "s elapsed." << std::endl;
  };

  auto on_enumerate_epoch = [&](size_t epoch) { std::cout << epoch + 1 << std::endl; };

  /** Define network architecture and optimizer */
  network net;
  float_t dropout_rate = 0.75;

  /* GPU - 21.56s 429MiB */
  net << conv(28, 28, 1, minibatch_size, 5, 32, 1, 2, true, core::backend_t::gpu, true)
      << relu(core::activation_t::relu, core::backend_t::gpu)
      << maxpool(28, 28, 32, minibatch_size, 2, 2, 2, 2, core::backend_t::gpu)
      << conv(14, 14, 32, minibatch_size, 5, 64, 1, 2, true, core::backend_t::gpu, true)
      << relu(core::activation_t::relu, core::backend_t::gpu)
      << maxpool(14, 14, 64, minibatch_size, 2, 2, 2, 2, core::backend_t::gpu)
      << fully(7 * 7 * 64, 1024, minibatch_size, true, core::backend_t::gpu, true)
      << relu(core::activation_t::relu, core::backend_t::gpu) << dropout(dropout_rate)
      << fully(1024, 10, minibatch_size, true, core::backend_t::gpu, true) << softmax();

  /* CPU - 902.74s
  net << conv(28, 28, 1, minibatch_size, 5, 32, 1, 2, true) << relu(core::activation_t::relu)
   << maxpool(28, 28, 32, minibatch_size)
   << conv(14, 14, 32, minibatch_size, 5, 64, 1, 2, true) << relu(core::activation_t::relu)
   << maxpool(14, 14, 64, minibatch_size)
   << fully(7 * 7 * 64, 1024, minibatch_size, true) << relu(core::activation_t::relu)
   << dropout(dropout_rate)
   << fully(1024, 10, minibatch_size, true) << softmax();
   */

  adam a;
  /** Train and save results */
  net.train<adam>(a, train_images, train_labels, validation_images, validation_labels, minibatch_size, epochs,
                  on_enumerate_minibatch, on_enumerate_epoch, true);
  net.save_results(mean_and_std, result);
  net.test_network(test_images, test_labels, minibatch_size, 10, result);

  return true;
}

int main(int argc, char* argv[]) {
  size_t expect = 5;
  if (argc < expect) {
    print("To few arguments, expted" + std::to_string(expect) + "\n");
    print("Usage: ./example_mnist batch_size epoch data_path store_results\n");
    print("Example usage: ./example_mnist 100 50 ~/data ~/results\n");
    return -1;
  }

  size_t batch_size  = atoi(argv[1]);  // use 50 or 100 etc
  size_t epoch       = atoi(argv[2]);
  std::string data   = argv[3];
  std::string result = argv[4];

  /** Let's go! */
  if (train_mnist(batch_size, epoch, data, result)) {
    return 0;
  }

  return -1;
}
<|endoftext|>


<commit_before><commit_msg>Fix regression (crash) in launching Apps (regular ones, not Extension Apps) caused by r50489.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove an include of a header that was removed in r10832.<commit_after><|endoftext|>


<commit_before><commit_msg>Use gdk_window_get_origin to determine the origin of the top-level window.  gtk_window_get_position returns different values (includes frame or not) depending on the window manager.<commit_after><|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <sys/time.h>
#include <assert.h>
using namespace std;

// Quicksort
void quickSort(int a[], int p, int r);
int partition(int a[], int p, int r);

// BubbleSort
void bubbleSort(int array[]);

// InsertionSort
void insertionSort(int arr[], int length);

// Get unsorted lists of integers
void getList(int array[], int sizeInt,  int listNum);

// Print array contents
void printList(int array[]);

// Check to see that array is sorted
bool isSorted(int a[], int size)

int main(int argc, char** argv)
{
    int sizes[11] = {10,50,100,500,1000,5000, 10000, 50000, 100000, 500000, 1000000}; // the sizes of lists
    int sizeInt = sizes[6];

    // THIS WON'T WORK:
    int array[sizeInt + 1]; // creates array to hold names

    int listNum = 1; // 1-1000
    ofstream outFile;
    outFile.open ("output.csv");
    outFile << "n, BubbleSort, QuickSort, InsertionSort, MergeSort\n";

    timeval t1;
    timeval t2;

    while (listNum <= 100)
    {
       getList(array, sizeInt, listNum);
       cout << "unsorted list:\n{";
       printList(array);
       cout << "}\n";

       // Bubble Sort
       gettimeofday(&t1, NULL);
       bubbleSort(array);
       gettimeofday(&t2, NULL);

       cout << "bubbleSorted list:\n{";
       printList(array);
       cout << "}\n";

        //cout << "t1: " << t1.tv_usec << ", t2: " << t2.tv_usec << endl;
//    cout << "bubbleSort execution time on n = "<< sizeInt << ": " << t2.tv_usec - t1.tv_usec << endl;
        outFile << sizeInt << "," << t2.tv_usec - t1.tv_usec << ",";
        getList(array, sizeInt, listNum);
    /*
     cout << "unsorted list:\n{";
    printList(array);
     cout << "}\n";
     */

    // Quick Sort
        gettimeofday(&t1, NULL);
        quickSort(array, 0, sizeInt);
        gettimeofday(&t2, NULL);

    /*
       cout << "quickSorted list:\n{";
       printList(array);
       cout << "}\n";

       cout << "t1: " << t1 << ", t2: " << t2 << endl;
     */
//    cout << "quickSort execution time on n = "<< sizeInt << ": " << t2.tv_usec - t1.tv_usec << endl;
        outFile << t2.tv_usec - t1.tv_usec << ",";

        getList(array, sizeInt, listNum);
    /*
    cout << "unSorted list:\n{";
        printList(array);
        cout << "}\n";
    */

        gettimeofday(&t1, NULL);
        insertionSort(array, sizeInt);
        gettimeofday(&t2, NULL);

    /*
    cout << "insertionSorted list:\n{";
    printList(array);
    cout << "}\n";
    */

//    cout << "insertionSort execution time on n = "<< sizeInt << ": " << t2.tv_usec - t1.tv_usec << endl;
        outFile << t2.tv_usec - t1.tv_usec << "\n";
        ++listNum;
    }
    outFile.close();
    return 0;
}

void bubbleSort(int array[])
{
    int swap;
    do{
        swap = 0;
        int n = 1;
        while (array[n] != '\0')
        {
            if (array[n-1] > array[n])
            {
                swap = 1;
                int temp = array[n-1];
                array[n-1] = array[n];
                array[n] = temp;
            }
            ++n;
        }
    }while(swap == 1);
}

int partition(int a[], int p, int r) {
    int x = a[r];
    int j = p - 1;
    for (int i = p; i < r; i++) {

        if (x <= a[i]) {
            j = j + 1;
            int temp = a[j];
            a[j] = a[i];
            a[i] = temp;
        }
    }
    a[r] = a[j + 1];
    a[j + 1] = x;

    return (j + 1);
}

void quickSort(int a[], int p, int r) {
    if (p < r) {
        int q = partition(a, p, r);
        quickSort(a, p, q - 1);
        quickSort(a, q + 1, r);
    }
}

void getList(int array[], int sizeInt, int listNum)
{
    int n = 0;
    char pathName[50];
    char listChar[50];
    char sizeChar[50];

    // "cast" int to chars
    sprintf (sizeChar, "%d", sizeInt);
    sprintf (listChar, "%d", listNum);

    // Create a pathname to the file where the unordered lists are stored.
    // sizeChar is how many ints are in the file, listChar is which file (1-100)
    strcpy(pathName, "../../lists/size");
    strcat(pathName, sizeChar);
    strcat(pathName, "/");
    strcat(pathName, "list");
    strcat(pathName, listChar);

    ifstream myfile (pathName); //opening the file.
    if(myfile.is_open()) //if the file is open
    {
        while (!myfile.eof()) //while the end of file is NOT reached
        {
            myfile >> array[n];
            n++;
        }
        array[n] = '\0';
        myfile.close(); //closing the file

    }
    else {
        cerr << "Unable to open file\n"; //if the file is not open output
        exit(0);
    }
}

void printList(int array[])
{
    int n = 0;
    while (array[n] != '\0')
    {
        cout << array[n] << ", ";
        ++n;
    }
}

void insertionSort(int arr[], int length)
{
    int i, j, tmp;
    for (i = 1; i < length; i++)
    {
        j = i;
        while (j > 0 && arr[j - 1] > arr[j])
        {
            tmp = arr[j];
            arr[j] = arr[j - 1];
            arr[j - 1] = tmp;
            j--;
        }
    }
}

bool isSorted(int a[], int size)
{
  int i;
  for(i = 0; i < (size-1); i++)
    if (a[i] > a[i+1])
      return false;
  return true;
}
<commit_msg>added assert stuff to allSort<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
#include <time.h>
#include <sys/time.h>
#include <assert.h>
using namespace std;

// Quicksort
void quickSort(int a[], int p, int r);
int partition(int a[], int p, int r);

// BubbleSort
void bubbleSort(int array[]);

// InsertionSort
void insertionSort(int arr[], int length);

// Get unsorted lists of integers
void getList(int array[], int listSize,  int listNum);

// Print array contents
void printList(int array[]);

// Check to see that array is sorted 0..n
bool isSorted(int a[], int size);

// Check to see that array is sorted n..0
bool isSortedR(int a[], int size);

int main(int argc, char** argv)
{
    int sizes[11] = {10,50,100,500,1000,5000, 10000, 50000, 100000, 500000, 1000000}; // the sizes of lists
    int listSize = sizes[4];

    // THIS WON'T WORK:
    int array[listSize + 1]; // creates array to hold names

    int listNum = 1; // 1-1000
    ofstream outFile;
    outFile.open ("output.csv");
    outFile << "n, BubbleSort, QuickSort, InsertionSort, MergeSort\n";

    timeval t1;
    timeval t2;

    while (listNum <= 100)
    {
        getList(array, listSize, listNum);
        cout << "unsorted list:\n{";
        printList(array);
        cout << "}\n";

        // Bubble Sort
        gettimeofday(&t1, NULL);
        bubbleSort(array);
        gettimeofday(&t2, NULL);

        // make sure list is sorted
        assert(isSorted(array, listSize));

        //cout << "bubbleSorted list:\n{";
        //printList(array);
        //cout << "}\n";

        //    cout << "t1: " << t1.tv_usec << ", t2: " << t2.tv_usec << endl;
        //    cout << "bubbleSort execution time on n = "<< listSize << ": " << t2.tv_usec - t1.tv_usec << endl;
        outFile << listSize << "," << t2.tv_usec - t1.tv_usec << ",";
        getList(array, listSize, listNum);
    /*
     cout << "unsorted list:\n{";
    printList(array);
     cout << "}\n";
     */

    // Quick Sort
        gettimeofday(&t1, NULL);
        quickSort(array, 0, listSize);
        gettimeofday(&t2, NULL);
        assert(isSortedR(array, listSize));

       cout << "quickSorted list:\n{";
       printList(array);
       cout << "}\n";

//    cout << "quickSort execution time on n = "<< listSize << ": " << t2.tv_usec - t1.tv_usec << endl;
        outFile << t2.tv_usec - t1.tv_usec << ",";

        getList(array, listSize, listNum);
    /*
    cout << "unSorted list:\n{";
        printList(array);
        cout << "}\n";
    */

        gettimeofday(&t1, NULL);
        insertionSort(array, listSize);
        gettimeofday(&t2, NULL);
        assert(isSorted(array, listSize));

    /*
    cout << "insertionSorted list:\n{";
    printList(array);
    cout << "}\n";
    */

//    cout << "insertionSort execution time on n = "<< listSize << ": " << t2.tv_usec - t1.tv_usec << endl;
        outFile << t2.tv_usec - t1.tv_usec << "\n";
        ++listNum;
    }
    outFile.close();
    return 0;
}

void bubbleSort(int array[])
{
    int swap;
    do{
        swap = 0;
        int n = 1;
        while (array[n] != '\0')
        {
            if (array[n-1] > array[n])
            {
                swap = 1;
                int temp = array[n-1];
                array[n-1] = array[n];
                array[n] = temp;
            }
            ++n;
        }
    }while(swap == 1);
}

int partition(int a[], int p, int r) {
    int x = a[r];
    int j = p - 1;
    for (int i = p; i < r; i++) {

        if (x <= a[i]) {
            j = j + 1;
            int temp = a[j];
            a[j] = a[i];
            a[i] = temp;
        }
    }
    a[r] = a[j + 1];
    a[j + 1] = x;

    return (j + 1);
}

void quickSort(int a[], int p, int r) {
    if (p < r) {
        int q = partition(a, p, r);
        quickSort(a, p, q - 1);
        quickSort(a, q + 1, r);
    }
}

void getList(int array[], int listSize, int listNum)
{
    int n = 0;
    char pathName[50];
    char listChar[50];
    char sizeChar[50];

    // "cast" int to chars
    sprintf (sizeChar, "%d", listSize);
    sprintf (listChar, "%d", listNum);

    // Create a pathname to the file where the unordered lists are stored.
    // sizeChar is how many ints are in the file, listChar is which file (1-100)
    strcpy(pathName, "../../lists/size");
    strcat(pathName, sizeChar);
    strcat(pathName, "/");
    strcat(pathName, "list");
    strcat(pathName, listChar);

    ifstream myfile (pathName); //opening the file.
    if(myfile.is_open()) //if the file is open
    {
        while (!myfile.eof()) //while the end of file is NOT reached
        {
            myfile >> array[n];
            n++;
        }
        array[n] = '\0';
        myfile.close(); //closing the file

    }
    else {
        cerr << "Unable to open file\n"; //if the file is not open output
        exit(0);
    }
}

void printList(int array[])
{
    int n = 0;
    while (array[n] != '\0')
    {
        cout << array[n] << ", ";
        ++n;
    }
}

void insertionSort(int arr[], int length)
{
    int i, j, tmp;
    for (i = 1; i < length; i++)
    {
        j = i;
        while (j > 0 && arr[j - 1] > arr[j])
        {
            tmp = arr[j];
            arr[j] = arr[j - 1];
            arr[j - 1] = tmp;
            j--;
        }
    }
}

bool isSorted(int a[], int size)
{
  int i;
  for(i = 0; i < (size-1); i++)
    if (a[i] > a[i+1])
      return false;
  return true;
}

bool isSortedR(int a[], int size)
{
  int i;
  for(i = 0; i < (size-1); i++)
    if (a[i] < a[i+1])
      return false;
  return true;
}
<|endoftext|>


<commit_before>
#ifndef LOAD_DATA_RESERVERS_H
#define LOAD_DATA_RESERVERS_H

#include <vector>
#include <fstream>
#include <string>
using namespace std;

#include <wiz/cpp_string.h>
#include <wiz/load_data_utility.h>
#include <wiz/queues.h>

namespace wiz {
	namespace load_data {
		class InFileReserver
		{
		private:
			ifstream* pInFile;
		public:
			int Num;
		public:
			explicit InFileReserver(ifstream& inFile)
			{
				pInFile = &inFile;
				Num = 1;
			}
			bool end()const { return pInFile->eof(); }
		public:
			bool operator() (ArrayQueue<string>& strVec)
			{
				return Utility::Reserve2(*pInFile, strVec, Num).second > 0;
			}
		};
		class NoneReserver
		{
		private:
			int count;
		public:
			explicit NoneReserver() : count(0) { }
			bool operator() (ArrayQueue<string>& strVec)
			{
				count = 1;
				return false;
			}
			bool end()const { return 1 == count; }
		};
	}
}

#endif<commit_msg>Delete LOAD_DATA_RESERVERS.H<commit_after><|endoftext|>


<commit_before>#include "TMC2130Stepper.h"

#define REG_COOLCONF 0X6D

///////////////////////////////////////////////////////////////////////////////////////
// REG_COOLCONF

void TMC2130Stepper::COOLCONF(uint32_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set COOLCONF: ");
	Serial.println(value);
#endif
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, value, 0xFFFFFFFF);
}

uint8_t TMC2130Stepper::sg_min() {return val_semin;}

void TMC2130Stepper::sg_min(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set semin: ");
	Serial.println(value);
#endif
	if (value > 15) value = 15;
	val_semin = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, value, 0xF);
}

uint8_t TMC2130Stepper::sg_step_width() {return val_seup;}

void TMC2130Stepper::sg_step_width(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set seup: ");
	Serial.println(value);
#endif
	uint8_t valid[] = {8, 4, 2, 1};

	if (value < valid[3]) value = valid[3]; // Make sure we find a match for low values
	for (int i = 0; i<4; i++) {
		if (value >= valid[i]) {
			value = valid[i];
			break;
		}
	}

	val_seup = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)value << 5, 0x60);
}

uint8_t TMC2130Stepper::sg_max() {return val_semax;}

void TMC2130Stepper::sg_max(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set semax: ");
	Serial.println(value);
#endif
	if (value > 15) value = 15;
	val_semin = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)value << 8, 0xF00);
}

uint8_t TMC2130Stepper::sg_current_decrease() {return val_sedn;}

void TMC2130Stepper::sg_current_decrease(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set sedn: ");
	Serial.println(value);
#endif
	uint8_t valid[] = {32, 8, 2, 1};

	if (value < valid[3]) value = valid[3]; // Make sure we find a match for low values
	for (int i = 0; i<4; i++) {
		if (value >= valid[i]) {
			value = valid[i];
			break;
		}
	}

	val_sedn = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)value << 13, 0x6000);
}

uint8_t TMC2130Stepper::smart_min_current() {return val_seimin;}

void TMC2130Stepper::smart_min_current(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set seimin: ");
	Serial.println(value);
#endif
	if (value > 1) value = 1;
	val_seimin = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)value << 15, 0x8000);
}

int8_t TMC2130Stepper::sg_stall_value() {return val_sgt;}

void TMC2130Stepper::sg_stall_value(int8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set sgt: ");
	Serial.println(value);
#endif
	if (value < -64) value = -64;
	else if (value > 63) value = 63;
	val_sgt = value;
	if (value < 0)
		send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)(value & 0x40) << 16, 0x7F0000UL);
	else
		send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)(value) << 16, 0x7F0000UL);
}

bool TMC2130Stepper::sg_filter() {return val_sfilt;}

void TMC2130Stepper::sg_filter(bool value) {
#ifdef TMC2130DEBUG
	Serial.print("Set sfilt: ");
	Serial.println(value);
#endif
	if (value > 1) value = 1;
	val_sfilt = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)value << 24, 0b1UL << 24);
}<commit_msg>Change to switch case structure. Default is no action.<commit_after>#include "TMC2130Stepper.h"

#define REG_COOLCONF 0X6D

///////////////////////////////////////////////////////////////////////////////////////
// REG_COOLCONF

void TMC2130Stepper::COOLCONF(uint32_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set COOLCONF: ");
	Serial.println(value);
#endif
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, value, 0xFFFFFFFF);
}

uint8_t TMC2130Stepper::sg_min() {return val_semin;}

void TMC2130Stepper::sg_min(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set semin: ");
	Serial.println(value);
#endif
	if (value > 15) value = 15;
	val_semin = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, value, 0xF);
}

uint8_t TMC2130Stepper::sg_step_width() {return val_seup;}

void TMC2130Stepper::sg_step_width(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set seup: ");
	Serial.println(value);
#endif
	uint32_t v;
	switch(value) {
		case 1: v = 0x0; break;
		case 2: v = 0x1; break;
		case 4: v = 0x2; break;
		case 8: v = 0x3; break;
		default: return;
	}
	val_seup = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, v << 5, 0x60);
}

uint8_t TMC2130Stepper::sg_max() {return val_semax;}

void TMC2130Stepper::sg_max(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set semax: ");
	Serial.println(value);
#endif
	if (value > 15) value = 15;
	val_semin = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)value << 8, 0xF00);
}

uint8_t TMC2130Stepper::sg_current_decrease() {return val_sedn;}

void TMC2130Stepper::sg_current_decrease(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set sedn: ");
	Serial.println(value);
#endif

	uint32_t v;
	switch(value) {
		case 32: v = 0b00; break;
		case  8: v = 0b01; break;
		case  2: v = 0b10; break;
		case  1: v = 0b11; break;
		default: return;
	}

	val_sedn = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, v << 13, 0x6000);
}

uint8_t TMC2130Stepper::smart_min_current() {return val_seimin;}

void TMC2130Stepper::smart_min_current(uint8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set seimin: ");
	Serial.println(value);
#endif
	if (value > 1) value = 1;
	val_seimin = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)value << 15, 0x8000);
}

int8_t TMC2130Stepper::sg_stall_value() {return val_sgt;}

void TMC2130Stepper::sg_stall_value(int8_t value) {
#ifdef TMC2130DEBUG
	Serial.print("Set sgt: ");
	Serial.println(value);
#endif
	if (value < -64) value = -64;
	else if (value > 63) value = 63;
	val_sgt = value;
	if (value < 0)
		send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)(value & 0x40) << 16, 0x7F0000UL);
	else
		send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)(value) << 16, 0x7F0000UL);
}

bool TMC2130Stepper::sg_filter() {return val_sfilt;}

void TMC2130Stepper::sg_filter(bool value) {
#ifdef TMC2130DEBUG
	Serial.print("Set sfilt: ");
	Serial.println(value);
#endif
	if (value > 1) value = 1;
	val_sfilt = value;
	send2130(WRITE|REG_COOLCONF, &cur_COOLCONF, (uint32_t)value << 24, 0b1UL << 24);
}<|endoftext|>


<commit_before><commit_msg>Adds switch to ui tests that enable dialogs in slave process. I'm adding this to make it easier to attach to a failing ui test.<commit_after><|endoftext|>


<commit_before>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 ( 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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIteratorWithIndex.h"

#include "itkTubeRidgeExtractor.h"

int itkTubeRidgeExtractorTest( int argc, char * argv[] )
  {
  if( argc != 3 )
    {
    std::cout
      << "itkTubeRidgeExtractorTest <inputImage> <outputImage>"
      << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::Image<float, 3>   ImageType;

  typedef itk::ImageFileReader< ImageType > ImageReaderType;
  ImageReaderType::Pointer imReader = ImageReaderType::New();
  imReader->SetFileName( argv[1] );
  imReader->Update();

  ImageType::Pointer im = imReader->GetOutput();

  ImageType::SizeType size = im->GetLargestPossibleRegion().GetSize();

  typedef itk::tube::RidgeExtractor<ImageType> RidgeOpType;
  RidgeOpType::Pointer ridgeOp = RidgeOpType::New();

  ridgeOp->SetInputImage( im );
  ridgeOp->SetStepX( 0.75 );

  double dataMin = ridgeOp->GetDataMin();
  std::cout << "Data min = " << dataMin << std::endl;
  double dataMax = ridgeOp->GetDataMax();
  std::cout << "Data max = " << dataMax << std::endl;
  double threshT = ridgeOp->GetThreshT();
  std::cout << "Theta threshold = " << threshT << std::endl;
  double threshX = ridgeOp->GetThreshX();
  std::cout << "X threshold = " << threshX << std::endl;
  double threshRidgeness = ridgeOp->GetThreshRidgeness();
  std::cout << "Ridgeness threshold = " << threshRidgeness << std::endl;
  double threshRidgenessStart = ridgeOp->GetThreshRidgenessStart();
  std::cout << "RidgenessStart threshold = " << threshRidgenessStart
    << std::endl;
  double threshCurvature = ridgeOp->GetThreshCurvature();
  std::cout << "Curvature threshold = " << threshCurvature << std::endl;
  double threshCurvatureStart = ridgeOp->GetThreshCurvatureStart();
  std::cout << "CurvatureStart threshold = " << threshCurvatureStart
    << std::endl;
  double threshRoundness = ridgeOp->GetThreshRoundness();
  std::cout << "Roundness threshold = " << threshRoundness << std::endl;
  double threshRoundnessStart = ridgeOp->GetThreshRoundnessStart();
  std::cout << "RoundnessStart threshold = " << threshRoundnessStart
    << std::endl;
  itk::Index<3> extractBoundMin = ridgeOp->GetExtractBoundMin();
  std::cout << "Extract bound min = " << extractBoundMin << std::endl;
  itk::Index<3> extractBoundMax = ridgeOp->GetExtractBoundMax();
  std::cout << "Extract bound max = " << extractBoundMax << std::endl;

  ridgeOp->SetScale( 1.0 );
  ridgeOp->SetExtent( 3.0 );
  ridgeOp->SetDynamicScale( true );

  double recoveryMax = ridgeOp->GetRecoveryMax();
  std::cout << "Recovery max = " << recoveryMax << std::endl;

  ImageType::Pointer imOut = ImageType::New();
  imOut->SetRegions( im->GetLargestPossibleRegion() );
  imOut->CopyInformation( im );
  imOut->Allocate();
  imOut->FillBuffer( 0 );

  double roundness;
  double curvature;
  unsigned int skip = 0;
  itk::ImageRegionIteratorWithIndex<ImageType> itOut( imOut,
    imOut->GetLargestPossibleRegion() );
  ImageType::IndexType indx;
  itk::ContinuousIndex<double, 3> contIndx;
  itOut.GoToBegin();
  ImageType::IndexType startIndx = itOut.GetIndex();
  std::cout << "Start..." << std::endl;
  bool firstSearch = false;
  while( !itOut.IsAtEnd() )
    {
    contIndx = itOut.GetIndex();
    switch( ( itOut.GetIndex()[2] - startIndx[2] ) % 5 )
      {
      default:
      case 0:
        std::cout << "Intensity: " << contIndx << std::endl;
        itOut.Set( ridgeOp->Intensity( itOut.GetIndex() ) );
        firstSearch = true;
        break;
      case 1:
        std::cout << "Ridgeness: " << contIndx << std::endl;
        itOut.Set( ridgeOp->Ridgeness( contIndx, roundness, curvature ) );
        firstSearch = true;
        break;
      case 2:
        std::cout << "Roundness: " << contIndx << std::endl;
        ridgeOp->Ridgeness( contIndx, roundness, curvature );
        itOut.Set( roundness );
        firstSearch = true;
        break;
      case 3:
        std::cout << "Curvature: " << contIndx << std::endl;
        ridgeOp->Ridgeness( contIndx, roundness, curvature );
        itOut.Set( curvature );
        firstSearch = true;
        break;
      case 4:
        if( firstSearch )
          {
          skip = (int)(contIndx[1]-startIndx[1])%4 * 3;
          firstSearch = false;
          }
        if( ++skip > 12 )
          {
          skip = 0;
          std::cout << "Local ridge: " << contIndx << std::endl;
          contIndx[1] = size[1]/2;
          if( ridgeOp->LocalRidge( contIndx ) )
            {
            std::cout << "   leads to: " << contIndx << std::endl;
            for( unsigned int i=0; i<3; i++ )
              {
              indx[i] = contIndx[i];
              }
            if( vnl_math_abs( indx[2] - itOut.GetIndex()[2] ) < 4 )
              {
              indx[2] = itOut.GetIndex()[2];
              int v = imOut->GetPixel( indx );
              imOut->SetPixel( indx, v+1 );
              }
            }
          }
        break;
      }
    ++itOut;
    }
  std::cout << "...end" << std::endl;

  typedef itk::ImageFileWriter<ImageType> ImageWriterType;
  ImageWriterType::Pointer imWriter = ImageWriterType::New();
  imWriter->SetFileName( argv[2] );
  imWriter->SetInput( imOut );
  imWriter->Update();

  return EXIT_SUCCESS;
  }
<commit_msg>COMP: Reduced verbosity of output<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 ( 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.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImageRegionIteratorWithIndex.h"

#include "itkTubeRidgeExtractor.h"

int itkTubeRidgeExtractorTest( int argc, char * argv[] )
  {
  if( argc != 3 )
    {
    std::cout
      << "itkTubeRidgeExtractorTest <inputImage> <outputImage>"
      << std::endl;
    return EXIT_FAILURE;
    }

  typedef itk::Image<float, 3>   ImageType;

  typedef itk::ImageFileReader< ImageType > ImageReaderType;
  ImageReaderType::Pointer imReader = ImageReaderType::New();
  imReader->SetFileName( argv[1] );
  imReader->Update();

  ImageType::Pointer im = imReader->GetOutput();

  ImageType::SizeType size = im->GetLargestPossibleRegion().GetSize();

  typedef itk::tube::RidgeExtractor<ImageType> RidgeOpType;
  RidgeOpType::Pointer ridgeOp = RidgeOpType::New();

  ridgeOp->SetInputImage( im );
  ridgeOp->SetStepX( 0.75 );

  double dataMin = ridgeOp->GetDataMin();
  std::cout << "Data min = " << dataMin << std::endl;
  double dataMax = ridgeOp->GetDataMax();
  std::cout << "Data max = " << dataMax << std::endl;
  double threshT = ridgeOp->GetThreshT();
  std::cout << "Theta threshold = " << threshT << std::endl;
  double threshX = ridgeOp->GetThreshX();
  std::cout << "X threshold = " << threshX << std::endl;
  double threshRidgeness = ridgeOp->GetThreshRidgeness();
  std::cout << "Ridgeness threshold = " << threshRidgeness << std::endl;
  double threshRidgenessStart = ridgeOp->GetThreshRidgenessStart();
  std::cout << "RidgenessStart threshold = " << threshRidgenessStart
    << std::endl;
  double threshCurvature = ridgeOp->GetThreshCurvature();
  std::cout << "Curvature threshold = " << threshCurvature << std::endl;
  double threshCurvatureStart = ridgeOp->GetThreshCurvatureStart();
  std::cout << "CurvatureStart threshold = " << threshCurvatureStart
    << std::endl;
  double threshRoundness = ridgeOp->GetThreshRoundness();
  std::cout << "Roundness threshold = " << threshRoundness << std::endl;
  double threshRoundnessStart = ridgeOp->GetThreshRoundnessStart();
  std::cout << "RoundnessStart threshold = " << threshRoundnessStart
    << std::endl;
  itk::Index<3> extractBoundMin = ridgeOp->GetExtractBoundMin();
  std::cout << "Extract bound min = " << extractBoundMin << std::endl;
  itk::Index<3> extractBoundMax = ridgeOp->GetExtractBoundMax();
  std::cout << "Extract bound max = " << extractBoundMax << std::endl;

  ridgeOp->SetScale( 1.0 );
  ridgeOp->SetExtent( 3.0 );
  ridgeOp->SetDynamicScale( true );

  double recoveryMax = ridgeOp->GetRecoveryMax();
  std::cout << "Recovery max = " << recoveryMax << std::endl;

  ImageType::Pointer imOut = ImageType::New();
  imOut->SetRegions( im->GetLargestPossibleRegion() );
  imOut->CopyInformation( im );
  imOut->Allocate();
  imOut->FillBuffer( 0 );

  double roundness;
  double curvature;
  unsigned int skip = 0;
  itk::ImageRegionIteratorWithIndex<ImageType> itOut( imOut,
    imOut->GetLargestPossibleRegion() );
  ImageType::IndexType indx;
  itk::ContinuousIndex<double, 3> contIndx;
  itOut.GoToBegin();
  ImageType::IndexType startIndx = itOut.GetIndex();
  std::cout << "Start..." << std::endl;
  bool firstSearch = false;
  int prev2 = -1;
  while( !itOut.IsAtEnd() )
    {
    contIndx = itOut.GetIndex();
    switch( ( itOut.GetIndex()[2] - startIndx[2] ) % 5 )
      {
      default:
      case 0:
        if( prev2 != itOut.GetIndex()[2] )
          {
          std::cout << "Intensity: " << contIndx << std::endl;
          prev2 = itOut.GetIndex()[2];
          }
        itOut.Set( ridgeOp->Intensity( itOut.GetIndex() ) );
        firstSearch = true;
        break;
      case 1:
        if( prev2 != itOut.GetIndex()[2] )
          {
          std::cout << "Ridgeness: " << contIndx << std::endl;
          prev2 = itOut.GetIndex()[2];
          }
        itOut.Set( ridgeOp->Ridgeness( contIndx, roundness, curvature ) );
        firstSearch = true;
        break;
      case 2:
        if( prev2 != itOut.GetIndex()[2] )
          {
          std::cout << "Roundness: " << contIndx << std::endl;
          prev2 = itOut.GetIndex()[2];
          }
        ridgeOp->Ridgeness( contIndx, roundness, curvature );
        itOut.Set( roundness );
        firstSearch = true;
        break;
      case 3:
        if( prev2 != itOut.GetIndex()[2] )
          {
          std::cout << "Curvature: " << contIndx << std::endl;
          prev2 = itOut.GetIndex()[2];
          }
        ridgeOp->Ridgeness( contIndx, roundness, curvature );
        itOut.Set( curvature );
        firstSearch = true;
        break;
      case 4:
        if( firstSearch )
          {
          skip = (int)(contIndx[1]-startIndx[1])%4 * 3;
          firstSearch = false;
          }
        if( ++skip > 12 )
          {
          skip = 0;
          std::cout << "Local ridge: " << contIndx << std::endl;
          contIndx[1] = size[1]/2;
          if( ridgeOp->LocalRidge( contIndx ) )
            {
            std::cout << "   leads to: " << contIndx << std::endl;
            for( unsigned int i=0; i<3; i++ )
              {
              indx[i] = contIndx[i];
              }
            if( vnl_math_abs( indx[2] - itOut.GetIndex()[2] ) < 4 )
              {
              indx[2] = itOut.GetIndex()[2];
              int v = imOut->GetPixel( indx );
              imOut->SetPixel( indx, v+1 );
              }
            }
          }
        break;
      }
    ++itOut;
    }
  std::cout << "...end" << std::endl;

  typedef itk::ImageFileWriter<ImageType> ImageWriterType;
  ImageWriterType::Pointer imWriter = ImageWriterType::New();
  imWriter->SetFileName( argv[2] );
  imWriter->SetInput( imOut );
  imWriter->Update();

  return EXIT_SUCCESS;
  }
<|endoftext|>