<commit_before>#include <gtest/gtest.h>

#include <redis_communicator.hpp>

static const std::string redis_server="192.168.10.11";
static const int redis_port=6379;
static const int num_test_msg=10;

void got_message(const std::string & t,const std::string & c)  {
  std::cout << "Using function callback > "<< t << "\t" << c << std::endl;
}
void got_error(const std::string & t,const int & v)  {
  std::cout << "Using function callback > "<< t << "\t->\t" << v << std::endl;
}
void unsubscribe(const std::string & t)  {
  std::cout << "Using function callback < "<< t << std::endl;
}

typedef configuration::communicator::RedisCommunicator CM;

using namespace configuration::communicator;

TEST (CommunicatorManager, CreateCommunicator) {
  CM cm(redis_server,redis_port);
}

TEST (CommunicatorManager, CommunicatorEmpty) {
  CM cm(redis_server,redis_port);
  EXPECT_EQ(cm.NumMessages(),0);
}

TEST (CommunicatorManager, AddMessage) {
  CM cm(redis_server,redis_port);
  EXPECT_EQ(cm.NumMessages(),0);
  EXPECT_TRUE( cm.Publish("key","a") );
  EXPECT_EQ(cm.NumMessages(),1);
}

TEST (CommunicatorManager, AddMessages) {
  CM cm(redis_server,redis_port);
  EXPECT_EQ(cm.NumMessages(),0);
  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i)
    EXPECT_TRUE( cm.Publish(std::to_string(i),status[i%3]) );
  EXPECT_EQ(cm.NumMessages(),num_test_msg);
}

TEST (CommunicatorManager, Notify) {
  CM cm(redis_server,redis_port);
  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    cm.Publish(std::string("message:")+std::to_string(i),status[i%3]);
  }
  EXPECT_TRUE( cm.Notify() );
  EXPECT_EQ(cm.NumMessages(),0);
}

TEST (CommunicatorManager, AutoNotify) {
  CM cm(redis_server,redis_port);
  EXPECT_EQ(cm.NumMessages(),0);
  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < 10*CM::MaxStoredMessages;++i) {
    EXPECT_TRUE( cm.Publish(std::string("message:")+std::to_string(i),status[i%3]) );
  }
  EXPECT_NE(cm.NumMessages(),10*CM::MaxStoredMessages);
}

TEST (CommunicatorManager, SubscribeSingleTopic) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);
  EXPECT_TRUE( listener.Subscribe("message:1") );
  // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  std::this_thread::sleep_for(std::chrono::seconds(1));
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  EXPECT_EQ(listener.NumRecvMessages(),num_test_msg);

}

TEST (CommunicatorManager, SubscribeMultipleTopics) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);
  EXPECT_TRUE( listener.Subscribe("message:*") );
  // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  EXPECT_EQ(listener.NumRecvMessages(),num_test_msg*3);

}

TEST (CommunicatorManager, SubscribeFunctionGotCallback) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  EXPECT_TRUE( listener.Subscribe("message:1",got_message) );

  // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  // EXPECT_EQ(listener.NumRecvMessages(),num_test_msg);

}

TEST (CommunicatorManager, SubscribeFunctionCallbacks) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  EXPECT_TRUE( listener.Subscribe("message:1",got_message,unsubscribe,got_error) );

  // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));

}

TEST (CommunicatorManager, SubscribeMemberGotCallback) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  configuration::communicator::ReceivedMessageCb got_cb;

  EXPECT_TRUE( listener.Subscribe("message:1",got_cb.f) );

  // // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  EXPECT_EQ(got_cb.num_msg,num_test_msg);

}

TEST (CommunicatorManager, SubscribeMembersCallback) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  configuration::communicator::ReceivedMessageCb got_cb;
  configuration::communicator::UnsubscribeCb uns_cb;
  configuration::communicator::SubscribeErrorCb err_cb;

  EXPECT_TRUE( listener.Subscribe("message:1",got_cb.f,uns_cb.f,err_cb.f) );

  // // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  EXPECT_EQ(got_cb.num_msg,num_test_msg);

}

TEST (CommunicatorManager, SubscribeMember) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  configuration::communicator::ReceivedMessageCb got_cb;

  listener.Subscribe("message:1",got_cb.f) ;

  // // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));

  EXPECT_TRUE( listener.Unsubscribe("message:1") );

}

TEST (CommunicatorManager, UnsubscribeMembers) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  configuration::communicator::ReceivedMessageCb got_cb;
  configuration::communicator::UnsubscribeCb uns_cb;
  configuration::communicator::SubscribeErrorCb err_cb;

  listener.Subscribe("message:1",got_cb.f,uns_cb.f,err_cb.f);

  // // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));

  EXPECT_TRUE( listener.Unsubscribe("message:*",err_cb.f) );

}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>fix merge issues<commit_after>#include <gtest/gtest.h>

#include <redis_communicator.hpp>

static const std::string redis_server="192.168.10.11";
static const int redis_port=6379;
static const int num_test_msg=10;

void got_message(const std::string & t,const std::string & c)  {
  std::cout << "Using function callback > "<< t << "\t" << c << std::endl;
}
void got_error(const std::string & t,const int & v)  {
  std::cout << "Using function callback > "<< t << "\t->\t" << v << std::endl;
}
void unsubscribe(const std::string & t)  {
  std::cout << "Using function callback < "<< t << std::endl;
}

typedef configuration::communicator::RedisCommunicator CM;

using namespace configuration::communicator;

TEST (CommunicatorManager, CreateCommunicator) {
  CM cm(redis_server,redis_port);
}

TEST (CommunicatorManager, CommunicatorEmpty) {
  CM cm(redis_server,redis_port);
  EXPECT_EQ(cm.NumMessages(),0);
}

TEST (CommunicatorManager, AddMessage) {
  CM cm(redis_server,redis_port);
  EXPECT_EQ(cm.NumMessages(),0);
  EXPECT_TRUE( cm.Publish("key","a") );
  EXPECT_EQ(cm.NumMessages(),1);
}

TEST (CommunicatorManager, AddMessages) {
  CM cm(redis_server,redis_port);
  EXPECT_EQ(cm.NumMessages(),0);
  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i)
    EXPECT_TRUE( cm.Publish(std::to_string(i),status[i%3]) );
  EXPECT_EQ(cm.NumMessages(),num_test_msg);
}

TEST (CommunicatorManager, Notify) {
  CM cm(redis_server,redis_port);
  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    cm.Publish(std::string("message:")+std::to_string(i),status[i%3]);
  }
  EXPECT_TRUE( cm.Notify() );
  EXPECT_EQ(cm.NumMessages(),0);
}

TEST (CommunicatorManager, AutoNotify) {
  CM cm(redis_server,redis_port);
  EXPECT_EQ(cm.NumMessages(),0);
  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < 10*CM::MaxStoredMessages;++i) {
    EXPECT_TRUE( cm.Publish(std::string("message:")+std::to_string(i),status[i%3]) );
  }
  EXPECT_NE(cm.NumMessages(),10*CM::MaxStoredMessages);
}

TEST (CommunicatorManager, SubscribeSingleTopic) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);
  EXPECT_TRUE( listener.Subscribe("message:1") );
  // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  std::this_thread::sleep_for(std::chrono::seconds(1));
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  EXPECT_EQ(listener.NumRecvMessages(),num_test_msg);

}

TEST (CommunicatorManager, SubscribeMultipleTopics) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);
  EXPECT_TRUE( listener.Subscribe("message:*") );
  // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  EXPECT_EQ(listener.NumRecvMessages(),num_test_msg*3);

}

TEST (CommunicatorManager, SubscribeFunctionGotCallback) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  EXPECT_TRUE( listener.Subscribe("message:1",got_message) );

  // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  // EXPECT_EQ(listener.NumRecvMessages(),num_test_msg);

}

TEST (CommunicatorManager, SubscribeFunctionCallbacks) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  EXPECT_TRUE( listener.Subscribe("message:1",got_message,unsubscribe,got_error) );

  // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));

}

TEST (CommunicatorManager, SubscribeMemberGotCallback) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  configuration::communicator::ReceivedMessageCb got_cb;

  EXPECT_TRUE( listener.Subscribe("message:1",got_cb.f) );

  // // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  EXPECT_EQ(got_cb.num_msg,num_test_msg);

}

TEST (CommunicatorManager, SubscribeMembersCallback) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  configuration::communicator::ReceivedMessageCb got_cb;
  configuration::communicator::UnsubscribeCb uns_cb;
  configuration::communicator::SubscribeErrorCb err_cb;

  EXPECT_TRUE( listener.Subscribe("message:1",got_cb.f,uns_cb.f,err_cb.f) );

  // // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  EXPECT_EQ(got_cb.num_msg,num_test_msg);

}

TEST (CommunicatorManager, SubscribeMember) {

  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  listener.Subscribe("message:1") ;

  // // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));
  EXPECT_TRUE( listener.Unsubscribe("message:1") );

}

TEST (CommunicatorManager, UnsubscribeMembers) {
  CM publisher(redis_server,redis_port);
  CM listener(redis_server,redis_port);

  configuration::communicator::ReceivedMessageCb got_cb;
  configuration::communicator::UnsubscribeCb uns_cb;
  configuration::communicator::SubscribeErrorCb err_cb;

  listener.Subscribe("message:1",got_cb.f,uns_cb.f,err_cb.f);

  // // just ensure enough time to connect
  std::this_thread::sleep_for(std::chrono::milliseconds(10));

  std::vector<std::string> status = {"a","u","d"};
  for(int i = 0; i < num_test_msg;++i) {
    publisher.Publish(std::string("message:1"),status[i%3]);
    publisher.Publish(std::string("message:2"),status[i%3]);
    publisher.Publish(std::string("message:3"),status[i%3]);
    publisher.Notify();
  }
  // after 1 sec you can be confident that all messages arrived
  std::this_thread::sleep_for(std::chrono::seconds(1));

  EXPECT_TRUE( listener.Unsubscribe("message:*",err_cb.f) );

}

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/**
 * @file mean_split_impl.hpp
 * @author Yash Vadalia
 * @author Ryan Curtin
 *
 * Implementation of class(MeanSplit) to split a binary space partition tree.
 */
#ifndef __MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_IMPL_HPP
#define __MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_IMPL_HPP

#include "mean_split.hpp"

namespace mlpack {
namespace tree {

template<typename BoundType, typename MatType>
bool MeanSplit<BoundType, MatType>::SplitNode(const BoundType& bound,
                                              MatType& data,
                                              const size_t begin,
                                              const size_t count,
                                              size_t& splitCol)
{
  size_t splitDimension = data.n_rows; // Indicate invalid.
  double maxWidth = -1;

  // Find the split dimension.
  size_t ties = 0;
  for (size_t d = 0; d < data.n_rows; d++)
  {
    double width = bound[d].Width();

    if (width > maxWidth)
    {
      maxWidth = width;
      splitDimension = d;
    }
    if (width == maxWidth)
    {
      // There's a tie.  Record that.
      ++ties;
    }
  }

  if (ties > 0)
  {
    // Look through a second time, and determine the correct dimension.
    size_t tieIndex = 0;
    for (size_t d = 0; d < data.n_rows; ++d)
    {
      const double width = bound[d].Width();

      if (width == maxWidth)
      {
        if (tieIndex == (nextDimension % ties))
        {
          splitDimension = d;
          break;
        }
        ++tieIndex;
      }
    }
  }

  if (maxWidth == 0) // All these points are the same.  We can't split.
    return false;

  // Split in the middle of that dimension.
  double splitVal = bound[splitDimension].Mid();

  // Perform the actual splitting.  This will order the dataset such that points
  // with value in dimension splitDimension less than or equal to splitVal are
  // on the left of splitCol, and points with value in dimension splitDimension
  // greater than splitVal are on the right side of splitCol.
  splitCol = PerformSplit(data, begin, count, splitDimension, splitVal);

  return true;
}

template<typename BoundType, typename MatType>
bool MeanSplit<BoundType, MatType>::SplitNode(const BoundType& bound,
                                              MatType& data,
                                              const size_t begin,
                                              const size_t count,
                                              size_t& splitCol,
                                              std::vector<size_t>& oldFromNew)
{
  size_t splitDimension = data.n_rows; // Indicate invalid.
  double maxWidth = -1;

  // Find the split dimension.
  for (size_t d = 0; d < data.n_rows; d++)
  {
    double width = bound[d].Width();

    if (width > maxWidth)
    {
      maxWidth = width;
      splitDimension = d;
    }
  }

  if (maxWidth == 0) // All these points are the same.  We can't split.
    return false;

  // Split in the middle of that dimension.
  double splitVal = bound[splitDimension].Mid();

  // Perform the actual splitting.  This will order the dataset such that points
  // with value in dimension splitDimension less than or equal to splitVal are
  // on the left of splitCol, and points with value in dimension splitDimension
  // greater than splitVal are on the right side of splitCol.
  splitCol = PerformSplit(data, begin, count, splitDimension, splitVal,
      oldFromNew);

  return true;
}

template<typename BoundType, typename MatType>
size_t MeanSplit<BoundType, MatType>::
    PerformSplit(MatType& data,
                 const size_t begin,
                 const size_t count,
                 const size_t splitDimension,
                 const double splitVal)
{
  // This method modifies the input dataset.  We loop both from the left and
  // right sides of the points contained in this node.  The points less than
  // splitVal should be on the left side of the matrix, and the points greater
  // than splitVal should be on the right side of the matrix.
  size_t left = begin;
  size_t right = begin + count - 1;

  // First half-iteration of the loop is out here because the termination
  // condition is in the middle.
  while ((data(splitDimension, left) < splitVal) && (left <= right))
    left++;
  while ((data(splitDimension, right) >= splitVal) && (left <= right))
    right--;

  while (left <= right)
  {
    // Swap columns.
    data.swap_cols(left, right);

    // See how many points on the left are correct.  When they are correct,
    // increase the left counter accordingly.  When we encounter one that isn't
    // correct, stop.  We will switch it later.
    while ((data(splitDimension, left) < splitVal) && (left <= right))
      left++;

    // Now see how many points on the right are correct.  When they are correct,
    // decrease the right counter accordingly.  When we encounter one that isn't
    // correct, stop.  We will switch it with the wrong point we found in the
    // previous loop.
    while ((data(splitDimension, right) >= splitVal) && (left <= right))
      right--;
  }

  Log::Assert(left == right + 1);

  if (left >= begin + count)
    Log::Fatal << "Left is count. Bad.\n";

  return left;
}

template<typename BoundType, typename MatType>
size_t MeanSplit<BoundType, MatType>::
    PerformSplit(MatType& data,
                 const size_t begin,
                 const size_t count,
                 const size_t splitDimension,
                 const double splitVal,
                 std::vector<size_t>& oldFromNew)
{
  // This method modifies the input dataset.  We loop both from the left and
  // right sides of the points contained in this node.  The points less than
  // splitVal should be on the left side of the matrix, and the points greater
  // than splitVal should be on the right side of the matrix.
  size_t left = begin;
  size_t right = begin + count - 1;

  // First half-iteration of the loop is out here because the termination
  // condition is in the middle.
  while ((data(splitDimension, left) < splitVal) && (left <= right))
    left++;
  while ((data(splitDimension, right) >= splitVal) && (left <= right))
    right--;

  while (left <= right)
  {
    // Swap columns.
    data.swap_cols(left, right);

    // Update the indices for what we changed.
    size_t t = oldFromNew[left];
    oldFromNew[left] = oldFromNew[right];
    oldFromNew[right] = t;

    // See how many points on the left are correct.  When they are correct,
    // increase the left counter accordingly.  When we encounter one that isn't
    // correct, stop.  We will switch it later.
    while ((data(splitDimension, left) < splitVal) && (left <= right))
      left++;

    // Now see how many points on the right are correct.  When they are correct,
    // decrease the right counter accordingly.  When we encounter one that isn't
    // correct, stop.  We will switch it with the wrong point we found in the
    // previous loop.
    while ((data(splitDimension, right) >= splitVal) && (left <= right))
      right--;
  }

  Log::Assert(left == right + 1);

  return left;
}

}; // namespace tree
}; // namespace mlpack

#endif
<commit_msg>This wasn't actually mean split before.  Now it is.<commit_after>/**
 * @file mean_split_impl.hpp
 * @author Yash Vadalia
 * @author Ryan Curtin
 *
 * Implementation of class(MeanSplit) to split a binary space partition tree.
 */
#ifndef __MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_IMPL_HPP
#define __MLPACK_CORE_TREE_BINARY_SPACE_TREE_MEAN_SPLIT_IMPL_HPP

#include "mean_split.hpp"

namespace mlpack {
namespace tree {

template<typename BoundType, typename MatType>
bool MeanSplit<BoundType, MatType>::SplitNode(const BoundType& bound,
                                              MatType& data,
                                              const size_t begin,
                                              const size_t count,
                                              size_t& splitCol)
{
  size_t splitDimension = data.n_rows; // Indicate invalid.
  double maxWidth = -1;

  // Find the split dimension.
  size_t ties = 0;
  for (size_t d = 0; d < data.n_rows; d++)
  {
    const double width = bound[d].Width();

    if (width > maxWidth)
    {
      maxWidth = width;
      splitDimension = d;
    }
    if (width == maxWidth)
    {
      // There's a tie.  Record that.
      ++ties;
    }
  }

  if (ties > 0)
  {
    // Look through a second time, and determine the correct dimension.
    size_t tieIndex = 0;
    for (size_t d = 0; d < data.n_rows; ++d)
    {
      const double width = bound[d].Width();

      if (width == maxWidth)
      {
        if (tieIndex == (nextDimension % ties))
        {
          splitDimension = d;
          break;
        }
        ++tieIndex;
      }
    }
  }

  if (maxWidth == 0) // All these points are the same.  We can't split.
    return false;

  // Split in the mean of that dimension.
  double splitVal = 0.0;
  for (size_t i = begin; i < begin + count; ++i)
    splitVal += data(splitDimension, i);
  splitVal /= count;

  // Perform the actual splitting.  This will order the dataset such that points
  // with value in dimension splitDimension less than or equal to splitVal are
  // on the left of splitCol, and points with value in dimension splitDimension
  // greater than splitVal are on the right side of splitCol.
  splitCol = PerformSplit(data, begin, count, splitDimension, splitVal);

  return true;
}

template<typename BoundType, typename MatType>
bool MeanSplit<BoundType, MatType>::SplitNode(const BoundType& bound,
                                              MatType& data,
                                              const size_t begin,
                                              const size_t count,
                                              size_t& splitCol,
                                              std::vector<size_t>& oldFromNew)
{
  size_t splitDimension = data.n_rows; // Indicate invalid.
  double maxWidth = -1;

  // Find the split dimension.
  for (size_t d = 0; d < data.n_rows; d++)
  {
    double width = bound[d].Width();

    if (width > maxWidth)
    {
      maxWidth = width;
      splitDimension = d;
    }
  }

  if (maxWidth == 0) // All these points are the same.  We can't split.
    return false;

  // Split in the middle of that dimension.
  double splitVal = bound[splitDimension].Mid();

  // Perform the actual splitting.  This will order the dataset such that points
  // with value in dimension splitDimension less than or equal to splitVal are
  // on the left of splitCol, and points with value in dimension splitDimension
  // greater than splitVal are on the right side of splitCol.
  splitCol = PerformSplit(data, begin, count, splitDimension, splitVal,
      oldFromNew);

  return true;
}

template<typename BoundType, typename MatType>
size_t MeanSplit<BoundType, MatType>::
    PerformSplit(MatType& data,
                 const size_t begin,
                 const size_t count,
                 const size_t splitDimension,
                 const double splitVal)
{
  // This method modifies the input dataset.  We loop both from the left and
  // right sides of the points contained in this node.  The points less than
  // splitVal should be on the left side of the matrix, and the points greater
  // than splitVal should be on the right side of the matrix.
  size_t left = begin;
  size_t right = begin + count - 1;

  // First half-iteration of the loop is out here because the termination
  // condition is in the middle.
  while ((data(splitDimension, left) < splitVal) && (left <= right))
    left++;
  while ((data(splitDimension, right) >= splitVal) && (left <= right))
    right--;

  while (left <= right)
  {
    // Swap columns.
    data.swap_cols(left, right);

    // See how many points on the left are correct.  When they are correct,
    // increase the left counter accordingly.  When we encounter one that isn't
    // correct, stop.  We will switch it later.
    while ((data(splitDimension, left) < splitVal) && (left <= right))
      left++;

    // Now see how many points on the right are correct.  When they are correct,
    // decrease the right counter accordingly.  When we encounter one that isn't
    // correct, stop.  We will switch it with the wrong point we found in the
    // previous loop.
    while ((data(splitDimension, right) >= splitVal) && (left <= right))
      right--;
  }

  Log::Assert(left == right + 1);

  if (left >= begin + count)
    Log::Fatal << "Left is count. Bad.\n";

  return left;
}

template<typename BoundType, typename MatType>
size_t MeanSplit<BoundType, MatType>::
    PerformSplit(MatType& data,
                 const size_t begin,
                 const size_t count,
                 const size_t splitDimension,
                 const double splitVal,
                 std::vector<size_t>& oldFromNew)
{
  // This method modifies the input dataset.  We loop both from the left and
  // right sides of the points contained in this node.  The points less than
  // splitVal should be on the left side of the matrix, and the points greater
  // than splitVal should be on the right side of the matrix.
  size_t left = begin;
  size_t right = begin + count - 1;

  // First half-iteration of the loop is out here because the termination
  // condition is in the middle.
  while ((data(splitDimension, left) < splitVal) && (left <= right))
    left++;
  while ((data(splitDimension, right) >= splitVal) && (left <= right))
    right--;

  while (left <= right)
  {
    // Swap columns.
    data.swap_cols(left, right);

    // Update the indices for what we changed.
    size_t t = oldFromNew[left];
    oldFromNew[left] = oldFromNew[right];
    oldFromNew[right] = t;

    // See how many points on the left are correct.  When they are correct,
    // increase the left counter accordingly.  When we encounter one that isn't
    // correct, stop.  We will switch it later.
    while ((data(splitDimension, left) < splitVal) && (left <= right))
      left++;

    // Now see how many points on the right are correct.  When they are correct,
    // decrease the right counter accordingly.  When we encounter one that isn't
    // correct, stop.  We will switch it with the wrong point we found in the
    // previous loop.
    while ((data(splitDimension, right) >= splitVal) && (left <= right))
      right--;
  }

  Log::Assert(left == right + 1);

  return left;
}

}; // namespace tree
}; // namespace mlpack

#endif
<|endoftext|>


<commit_before>/*
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
*/

//Copyright 2008 Henry de Valence <hdevalence@gmail.com>

#include "LatLonEditPlugin.h"

#include "../../lib/LatLonEdit.h"

#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtCore/QtPlugin>
#include <QtGui/QWidget>
#include <QtGui/QIcon>
#include <QtDesigner/QDesignerCustomWidgetInterface>

LatLonEditPlugin::LatLonEditPlugin(QObject *parent) : QObject(parent)
{
    m_initialized = false;
}
bool LatLonEditPlugin::isInitialized() const
{
    return m_initialized;
}
void LatLonEditPlugin::initialize(QDesignerFormEditorInterface *core)
{
    m_initialized = true;
}
bool LatLonEditPlugin::isContainer() const
{
    return false;
}
QIcon LatLonEditPlugin::icon() const
{
    return QIcon(":/icons/marble.png");
}
QString LatLonEditPlugin::domXml() const
{
    return "<widget class=\"Marble::LatLonEdit\" name=\"LatLonEdit\">\n"
           "</widget>\n";
}
QString LatLonEditPlugin::group() const
{
    return "Marble Desktop Globe";
}
QString LatLonEditPlugin::includeFile() const
{
    return QString( "LatLonEdit.h" );
}
QString LatLonEditPlugin::name() const
{
    return QString( "Marble::LatLonEdit" );
}
QString LatLonEditPlugin::toolTip() const
{
    return QString( "" );
}
QString LatLonEditPlugin::whatsThis() const
{
    return QString( "" );
}
QWidget *LatLonEditPlugin::createWidget(QWidget *parent)
{
    return new Marble::LatLonEdit(parent);
}

Q_EXPORT_PLUGIN2(LatLonEditPlugin, LatLonEditPlugin)

<commit_msg>fix undefined reference to vtable error<commit_after>/*
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
*/

//Copyright 2008 Henry de Valence <hdevalence@gmail.com>

#include "LatLonEditPlugin.h"

#include "../../lib/LatLonEdit.h"

#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtCore/QtPlugin>
#include <QtGui/QWidget>
#include <QtGui/QIcon>
#include <QtDesigner/QDesignerCustomWidgetInterface>

LatLonEditPlugin::LatLonEditPlugin(QObject *parent) : QObject(parent)
{
    m_initialized = false;
}
bool LatLonEditPlugin::isInitialized() const
{
    return m_initialized;
}
void LatLonEditPlugin::initialize(QDesignerFormEditorInterface *core)
{
    m_initialized = true;
}
bool LatLonEditPlugin::isContainer() const
{
    return false;
}
QIcon LatLonEditPlugin::icon() const
{
    return QIcon(":/icons/marble.png");
}
QString LatLonEditPlugin::domXml() const
{
    return "<widget class=\"Marble::LatLonEdit\" name=\"LatLonEdit\">\n"
           "</widget>\n";
}
QString LatLonEditPlugin::group() const
{
    return "Marble Desktop Globe";
}
QString LatLonEditPlugin::includeFile() const
{
    return QString( "LatLonEdit.h" );
}
QString LatLonEditPlugin::name() const
{
    return QString( "Marble::LatLonEdit" );
}
QString LatLonEditPlugin::toolTip() const
{
    return QString( "" );
}
QString LatLonEditPlugin::whatsThis() const
{
    return QString( "" );
}
QWidget *LatLonEditPlugin::createWidget(QWidget *parent)
{
    return new Marble::LatLonEdit(parent);
}

Q_EXPORT_PLUGIN2(LatLonEditPlugin, LatLonEditPlugin)

#include "LatLonEditPlugin.moc"
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "qmlitemnode.h"
#include <metainfo.h>
#include <QDeclarativeView>
#include "qmlchangeset.h"
#include "variantproperty.h"
#include "nodelistproperty.h"
#include "nodeinstance.h"
#include "qmlanchors.h"
#include "invalidmodelnodeexception.h"
#include "rewritertransaction.h"
#include "qmlmodelview.h"
#include "mathutils.h"

namespace QmlDesigner {

bool QmlItemNode::isValid() const
{
    return QmlModelNodeFacade::isValid() && modelNode().metaInfo().isValid() && modelNode().metaInfo().isSubclassOf("Qt/Item", 4, 7);
}

bool QmlItemNode::isRootNode() const
{
    return modelNode().isValid() && modelNode().isRootNode();
}

QStringList QmlModelStateGroup::names() const
{
    QStringList returnList;

    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (modelNode().property("states").isNodeListProperty()) {
        foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
            if (QmlModelState(node).isValid())
                returnList.append(QmlModelState(node).name());
        }
    }
    return returnList;
}

/**
  \brief Returns list of states (without 'base state').
  The list contains all states defined by this item.
  */
QmlModelStateGroup QmlItemNode::states() const
{
    if (isValid())
        return QmlModelStateGroup(modelNode());
    else
        return QmlModelStateGroup();
}

QList<QmlItemNode> QmlItemNode::children() const
{
    QList<QmlItemNode> returnList;

    if (isValid()) {

        QList<ModelNode> modelNodeList;

        if (modelNode().hasProperty("children")) {
            Q_ASSERT(modelNode().property("children").isNodeListProperty());
            modelNodeList.append(modelNode().nodeListProperty("children").toModelNodeList());
        }

        if (modelNode().hasProperty("data")) {
            Q_ASSERT(modelNode().property("data").isNodeListProperty());
            modelNodeList.append(modelNode().nodeListProperty("data").toModelNodeList());
        }

        foreach (const ModelNode &modelNode, modelNodeList) {
            if (QmlItemNode(modelNode).isValid())  //if ModelNode is FxItem
                returnList.append(modelNode);
        }
    }
    return returnList;
}

QList<QmlObjectNode> QmlItemNode::resources() const
{
    QList<QmlObjectNode> returnList;

    if (isValid()) {
        QList<ModelNode> modelNodeList;
        if (modelNode().hasProperty("resources")) {
            Q_ASSERT(modelNode().property("resources").isNodeListProperty());
            modelNodeList.append(modelNode().nodeListProperty("resources").toModelNodeList());
        }

        if (modelNode().hasProperty("data")) {
            Q_ASSERT(modelNode().property("data").isNodeListProperty());
            modelNodeList.append(modelNode().nodeListProperty("data").toModelNodeList());
        }

        foreach (const ModelNode &node, modelNodeList) {
            if (!QmlItemNode(node).isValid()) //if ModelNode is no FxItem
                returnList.append(node);
        }
    }
    return returnList;
}

QmlAnchors QmlItemNode::anchors() const
{
    return QmlAnchors(*this);
}

bool QmlItemNode::hasChildren() const
{
    return !children().isEmpty();
}

bool QmlItemNode::hasResources() const
{
    return !resources().isEmpty();
}

bool QmlItemNode::instanceHasAnchors() const
{
    return anchors().instanceHasAnchors();
}

bool QmlItemNode::hasShowContent() const
{
    return nodeInstance().hasContent();
}

bool QmlItemNode::canReparent() const
{
    return QmlObjectNode::canReparent() && !anchors().instanceHasAnchors() && !instanceIsAnchoredBy();
}

bool QmlItemNode::instanceIsAnchoredBy() const
{
    return nodeInstance().isAnchoredBy();
}

QRectF  QmlItemNode::instanceBoundingRect() const
{
    return nodeInstance().boundingRect();
}

QTransform  QmlItemNode::instanceTransform() const
{
    return nodeInstance().transform();
}

QTransform QmlItemNode::instanceSceneTransform() const
{
    return nodeInstance().sceneTransform();
}

QPointF QmlItemNode::instancePosition() const
{
    return nodeInstance().position();
}

QSizeF QmlItemNode::instanceSize() const
{
    return nodeInstance().size();
}

int QmlItemNode::instancePenWidth() const
{
    return nodeInstance().penWidth();
}

void QmlItemNode::paintInstance(QPainter *painter) const
{
    if (nodeInstance().isValid())
        nodeInstance().paint(painter);
}

void QmlItemNode::selectNode()
{
    modelNode().selectNode();
}

void QmlItemNode::deselectNode()
{
    modelNode().deselectNode();
}

bool QmlItemNode::isSelected() const
{
    return modelNode().isSelected();
}

QList<QmlModelState> QmlModelStateGroup::allStates() const
{
    QList<QmlModelState> returnList;

    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (modelNode().property("states").isNodeListProperty()) {
        foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
            if (QmlModelState(node).isValid())
                returnList.append(QmlModelState(node));
        }
    }
    return returnList;
}

QString QmlItemNode::simplifiedTypeName() const
{
    return modelNode().simplifiedTypeName();
}

uint qHash(const QmlItemNode &node)
{
    return qHash(node.modelNode());
}

QmlModelState QmlModelStateGroup::addState(const QString &name)
{
    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    PropertyListType propertyList;
    propertyList.append(qMakePair(QString("name"), QVariant(name)));

    ModelNode newState = modelNode().view()->createModelNode("Qt/State", 4, 7, propertyList);
    modelNode().nodeListProperty("states").reparentHere(newState);

    return newState;
}

void QmlModelStateGroup::removeState(const QString &name)
{
    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (state(name).isValid())
        state(name).modelNode().destroy();
}

QmlModelState QmlModelStateGroup::state(const QString &name) const
{
    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (modelNode().property("states").isNodeListProperty()) {
        foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
            if (QmlModelState(node).name() == name)
                return node;
        }
    }
    return QmlModelState();
}

QList<ModelNode> toModelNodeList(const QList<QmlItemNode> &qmlItemNodeList)
{
    QList<ModelNode> modelNodeList;

    foreach (const QmlItemNode &qmlItemNode, qmlItemNodeList)
        modelNodeList.append(qmlItemNode.modelNode());

    return modelNodeList;
}

QList<QmlItemNode> toQmlItemNodeList(const QList<ModelNode> &modelNodeList)
{
    QList<QmlItemNode> qmlItemNodeList;

    foreach (const ModelNode &modelNode, modelNodeList) {
        QmlItemNode itemNode(modelNode);
        if (itemNode.isValid())
            qmlItemNodeList.append(itemNode);
    }

    return qmlItemNodeList;
}

const QList<QmlItemNode> QmlItemNode::allDirectSubModelNodes() const
{
    return toQmlItemNodeList(modelNode().allDirectSubModelNodes());
}

const QList<QmlItemNode> QmlItemNode::allSubModelNodes() const
{
    return toQmlItemNodeList(modelNode().allSubModelNodes());
}

bool QmlItemNode::hasAnySubModelNodes() const
{
    return modelNode().hasAnySubModelNodes();
}

} //QmlDesigner
<commit_msg>QmlDesigner.core: changes QASSERT into condition<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "qmlitemnode.h"
#include <metainfo.h>
#include <QDeclarativeView>
#include "qmlchangeset.h"
#include "variantproperty.h"
#include "nodelistproperty.h"
#include "nodeinstance.h"
#include "qmlanchors.h"
#include "invalidmodelnodeexception.h"
#include "rewritertransaction.h"
#include "qmlmodelview.h"
#include "mathutils.h"

namespace QmlDesigner {

bool QmlItemNode::isValid() const
{
    return QmlModelNodeFacade::isValid() && modelNode().metaInfo().isValid() && modelNode().metaInfo().isSubclassOf("Qt/Item", 4, 7);
}

bool QmlItemNode::isRootNode() const
{
    return modelNode().isValid() && modelNode().isRootNode();
}

QStringList QmlModelStateGroup::names() const
{
    QStringList returnList;

    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (modelNode().property("states").isNodeListProperty()) {
        foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
            if (QmlModelState(node).isValid())
                returnList.append(QmlModelState(node).name());
        }
    }
    return returnList;
}

/**
  \brief Returns list of states (without 'base state').
  The list contains all states defined by this item.
  */
QmlModelStateGroup QmlItemNode::states() const
{
    if (isValid())
        return QmlModelStateGroup(modelNode());
    else
        return QmlModelStateGroup();
}

QList<QmlItemNode> QmlItemNode::children() const
{
    QList<QmlItemNode> returnList;

    if (isValid()) {

        QList<ModelNode> modelNodeList;

        if (modelNode().hasProperty("children")) {
            if (modelNode().property("children").isNodeListProperty())
                modelNodeList.append(modelNode().nodeListProperty("children").toModelNodeList());
        }

        if (modelNode().hasProperty("data")) {
            if (modelNode().property("data").isNodeListProperty())
                modelNodeList.append(modelNode().nodeListProperty("data").toModelNodeList());
        }

        foreach (const ModelNode &modelNode, modelNodeList) {
            if (QmlItemNode(modelNode).isValid())  //if ModelNode is FxItem
                returnList.append(modelNode);
        }
    }
    return returnList;
}

QList<QmlObjectNode> QmlItemNode::resources() const
{
    QList<QmlObjectNode> returnList;

    if (isValid()) {
        QList<ModelNode> modelNodeList;
        if (modelNode().hasProperty("resources")) {
            if (modelNode().property("resources").isNodeListProperty())
                modelNodeList.append(modelNode().nodeListProperty("resources").toModelNodeList());
        }

        if (modelNode().hasProperty("data")) {
            if (modelNode().property("data").isNodeListProperty())
                modelNodeList.append(modelNode().nodeListProperty("data").toModelNodeList());
        }

        foreach (const ModelNode &node, modelNodeList) {
            if (!QmlItemNode(node).isValid()) //if ModelNode is no FxItem
                returnList.append(node);
        }
    }
    return returnList;
}

QmlAnchors QmlItemNode::anchors() const
{
    return QmlAnchors(*this);
}

bool QmlItemNode::hasChildren() const
{
    return !children().isEmpty();
}

bool QmlItemNode::hasResources() const
{
    return !resources().isEmpty();
}

bool QmlItemNode::instanceHasAnchors() const
{
    return anchors().instanceHasAnchors();
}

bool QmlItemNode::hasShowContent() const
{
    return nodeInstance().hasContent();
}

bool QmlItemNode::canReparent() const
{
    return QmlObjectNode::canReparent() && !anchors().instanceHasAnchors() && !instanceIsAnchoredBy();
}

bool QmlItemNode::instanceIsAnchoredBy() const
{
    return nodeInstance().isAnchoredBy();
}

QRectF  QmlItemNode::instanceBoundingRect() const
{
    return nodeInstance().boundingRect();
}

QTransform  QmlItemNode::instanceTransform() const
{
    return nodeInstance().transform();
}

QTransform QmlItemNode::instanceSceneTransform() const
{
    return nodeInstance().sceneTransform();
}

QPointF QmlItemNode::instancePosition() const
{
    return nodeInstance().position();
}

QSizeF QmlItemNode::instanceSize() const
{
    return nodeInstance().size();
}

int QmlItemNode::instancePenWidth() const
{
    return nodeInstance().penWidth();
}

void QmlItemNode::paintInstance(QPainter *painter) const
{
    if (nodeInstance().isValid())
        nodeInstance().paint(painter);
}

void QmlItemNode::selectNode()
{
    modelNode().selectNode();
}

void QmlItemNode::deselectNode()
{
    modelNode().deselectNode();
}

bool QmlItemNode::isSelected() const
{
    return modelNode().isSelected();
}

QList<QmlModelState> QmlModelStateGroup::allStates() const
{
    QList<QmlModelState> returnList;

    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (modelNode().property("states").isNodeListProperty()) {
        foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
            if (QmlModelState(node).isValid())
                returnList.append(QmlModelState(node));
        }
    }
    return returnList;
}

QString QmlItemNode::simplifiedTypeName() const
{
    return modelNode().simplifiedTypeName();
}

uint qHash(const QmlItemNode &node)
{
    return qHash(node.modelNode());
}

QmlModelState QmlModelStateGroup::addState(const QString &name)
{
    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    PropertyListType propertyList;
    propertyList.append(qMakePair(QString("name"), QVariant(name)));

    ModelNode newState = modelNode().view()->createModelNode("Qt/State", 4, 7, propertyList);
    modelNode().nodeListProperty("states").reparentHere(newState);

    return newState;
}

void QmlModelStateGroup::removeState(const QString &name)
{
    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (state(name).isValid())
        state(name).modelNode().destroy();
}

QmlModelState QmlModelStateGroup::state(const QString &name) const
{
    if (!modelNode().isValid())
        throw new InvalidModelNodeException(__LINE__, __FUNCTION__, __FILE__);

    if (modelNode().property("states").isNodeListProperty()) {
        foreach (const ModelNode &node, modelNode().nodeListProperty("states").toModelNodeList()) {
            if (QmlModelState(node).name() == name)
                return node;
        }
    }
    return QmlModelState();
}

QList<ModelNode> toModelNodeList(const QList<QmlItemNode> &qmlItemNodeList)
{
    QList<ModelNode> modelNodeList;

    foreach (const QmlItemNode &qmlItemNode, qmlItemNodeList)
        modelNodeList.append(qmlItemNode.modelNode());

    return modelNodeList;
}

QList<QmlItemNode> toQmlItemNodeList(const QList<ModelNode> &modelNodeList)
{
    QList<QmlItemNode> qmlItemNodeList;

    foreach (const ModelNode &modelNode, modelNodeList) {
        QmlItemNode itemNode(modelNode);
        if (itemNode.isValid())
            qmlItemNodeList.append(itemNode);
    }

    return qmlItemNodeList;
}

const QList<QmlItemNode> QmlItemNode::allDirectSubModelNodes() const
{
    return toQmlItemNodeList(modelNode().allDirectSubModelNodes());
}

const QList<QmlItemNode> QmlItemNode::allSubModelNodes() const
{
    return toQmlItemNodeList(modelNode().allSubModelNodes());
}

bool QmlItemNode::hasAnySubModelNodes() const
{
    return modelNode().hasAnySubModelNodes();
}

} //QmlDesigner
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * X testing environment - Google Test environment feat. dummy x server
 *
 * Copyright (C) 2011, 2012 Canonical Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 ******************************************************************************/

#include "xorg/gtest/xorg-gtest-process.h"

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <algorithm>
#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <vector>

struct xorg::testing::Process::Private {
  pid_t pid;
};

xorg::testing::Process::Process() : d_(new Private) {
  d_->pid = -1;
}

void xorg::testing::Process::Start(const std::string &program, const std::vector<std::string> &argv) {
  if (d_->pid != -1)
    throw std::runtime_error("Attempting to start an already started process");

  d_->pid = vfork();

  if (d_->pid == -1) {
    throw std::runtime_error("Failed to fork child process");
  } else if (d_->pid == 0) { /* Child */
    close(0);
    close(1);
    close(2);

    std::vector<char*> args;
    std::vector<std::string>::const_iterator it;

    args.push_back(strdup(program.c_str()));

    for (it = argv.begin(); it != argv.end(); it++)
      if (!it->empty())
        args.push_back(strdup(it->c_str()));
    args.push_back(NULL);

    execvp(program.c_str(), &args[0]);

    throw std::runtime_error("Failed to start process");
  }
}

void xorg::testing::Process::Start(const std::string& program, va_list args) {
  std::vector<std::string> argv;

  do {
    std::string arg(va_arg(args, char*));
    argv.push_back(arg);
  } while (!argv.back().empty());

  Start(program, argv);
}

void xorg::testing::Process::Start(const std::string& program, ...) {
  va_list list;
  va_start(list, program);
  Start(program, list);
  va_end(list); /* Shouldn't get here */
}

bool xorg::testing::Process::WaitForExit(unsigned int timeout) {
  for (int i = 0; i < 10; i++) {
    int status;
    int pid = waitpid(Pid(), &status, WNOHANG);

    if (pid == Pid())
      return true;

      usleep(timeout * 100);
  }

  return false;
}

bool xorg::testing::Process::KillSelf(int signal, unsigned int timeout) {
  bool wait_success = true;

  if (d_->pid == -1) {
    return false;
  } else if (d_->pid == 0) {
    /* Child */
    throw std::runtime_error("Child process tried to kill itself");
  } else { /* Parent */
    if (kill(d_->pid, signal) < 0) {
      d_->pid = -1;
      return false;
    }
    if (timeout > 0)
      wait_success = WaitForExit(timeout);
    d_->pid = -1;
  }
  return wait_success;
}

bool xorg::testing::Process::Terminate(unsigned int timeout) {
  return KillSelf(SIGTERM, timeout);
}

bool xorg::testing::Process::Kill(unsigned int timeout) {
  return KillSelf(SIGKILL, timeout);
}

void xorg::testing::Process::SetEnv(const std::string& name,
                                    const std::string& value, bool overwrite) {
  if (setenv(name.c_str(), value.c_str(), overwrite) != 0)
    throw std::runtime_error("Failed to set environment variable in process");

  return;
}

std::string xorg::testing::Process::GetEnv(const std::string& name,
                                           bool* exists) {
  const char* var = getenv(name.c_str());
  if (exists != NULL)
    *exists = (var != NULL);

  return std::string(var);
}

pid_t xorg::testing::Process::Pid() const {
  return d_->pid;
}
<commit_msg>process: use fork(), not vfork()<commit_after>/*******************************************************************************
 *
 * X testing environment - Google Test environment feat. dummy x server
 *
 * Copyright (C) 2011, 2012 Canonical Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 ******************************************************************************/

#include "xorg/gtest/xorg-gtest-process.h"

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include <algorithm>
#include <cerrno>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdexcept>
#include <vector>

struct xorg::testing::Process::Private {
  pid_t pid;
};

xorg::testing::Process::Process() : d_(new Private) {
  d_->pid = -1;
}

void xorg::testing::Process::Start(const std::string &program, const std::vector<std::string> &argv) {
  if (d_->pid != -1)
    throw std::runtime_error("Attempting to start an already started process");

  d_->pid = fork();

  if (d_->pid == -1) {
    throw std::runtime_error("Failed to fork child process");
  } else if (d_->pid == 0) { /* Child */
    close(0);
    close(1);
    close(2);

    std::vector<char*> args;
    std::vector<std::string>::const_iterator it;

    args.push_back(strdup(program.c_str()));

    for (it = argv.begin(); it != argv.end(); it++)
      if (!it->empty())
        args.push_back(strdup(it->c_str()));
    args.push_back(NULL);

    execvp(program.c_str(), &args[0]);

    throw std::runtime_error("Failed to start process");
  }
}

void xorg::testing::Process::Start(const std::string& program, va_list args) {
  std::vector<std::string> argv;

  do {
    std::string arg(va_arg(args, char*));
    argv.push_back(arg);
  } while (!argv.back().empty());

  Start(program, argv);
}

void xorg::testing::Process::Start(const std::string& program, ...) {
  va_list list;
  va_start(list, program);
  Start(program, list);
  va_end(list); /* Shouldn't get here */
}

bool xorg::testing::Process::WaitForExit(unsigned int timeout) {
  for (int i = 0; i < 10; i++) {
    int status;
    int pid = waitpid(Pid(), &status, WNOHANG);

    if (pid == Pid())
      return true;

      usleep(timeout * 100);
  }

  return false;
}

bool xorg::testing::Process::KillSelf(int signal, unsigned int timeout) {
  bool wait_success = true;

  if (d_->pid == -1) {
    return false;
  } else if (d_->pid == 0) {
    /* Child */
    throw std::runtime_error("Child process tried to kill itself");
  } else { /* Parent */
    if (kill(d_->pid, signal) < 0) {
      d_->pid = -1;
      return false;
    }
    if (timeout > 0)
      wait_success = WaitForExit(timeout);
    d_->pid = -1;
  }
  return wait_success;
}

bool xorg::testing::Process::Terminate(unsigned int timeout) {
  return KillSelf(SIGTERM, timeout);
}

bool xorg::testing::Process::Kill(unsigned int timeout) {
  return KillSelf(SIGKILL, timeout);
}

void xorg::testing::Process::SetEnv(const std::string& name,
                                    const std::string& value, bool overwrite) {
  if (setenv(name.c_str(), value.c_str(), overwrite) != 0)
    throw std::runtime_error("Failed to set environment variable in process");

  return;
}

std::string xorg::testing::Process::GetEnv(const std::string& name,
                                           bool* exists) {
  const char* var = getenv(name.c_str());
  if (exists != NULL)
    *exists = (var != NULL);

  return std::string(var);
}

pid_t xorg::testing::Process::Pid() const {
  return d_->pid;
}
<|endoftext|>


<commit_before>#include "process.hpp"

//////////////
// Includes //
#include "image.hpp"

//////////
// Code //

// Processing a set of images.
Image* processImages(int count, Image** imgs) {
    // TODO: Implement
    return nullptr;
}
<commit_msg>Everything but consensus!<commit_after>#include "process.hpp"

//////////////
// Includes //
#include "image.hpp"

//////////
// Code //

// Verifying the validity of a set of images.
bool validateImages(int count, Image** imgs) {
    for (int i = 1; i < count; i++) {
        if (imgs[i - 1]->width    != imgs[i]->width  ||
            imgs[i - 1]->height   != imgs[i]->height ||
            imgs[i - 1]->maxValue != imgs[i]->maxValue)
            return false;
    }
    return true;
}

// Getting a single pixel at a given index of every image.
Pixel* getPixelsAt(int count, Image** imgs, int index) {
    Pixel* pixels = new Pixel[count];
    for (int i = 0; i < count; i++)
        pixels[i] = imgs[i]->pixels[i];
    return pixels;
}

Pixel choosePixel(int count, Pixel* pixels) {
    // TODO: Develop a consensus.
    Pixel p;
    return p;
}

// Processing a set of images.
Image* processImages(int count, Image** imgs) {
    if (!validateImages(count, imgs))
        return nullptr;

    int length = imgs[0]->width * imgs[0]->height;
    Pixel* finalPixels = new Pixel[length];
    Pixel* pixels;

    for (int i = 0; i < length; i++) {
        pixels = getPixelsAt(count, imgs, i);
        finalPixels[i] = choosePixel(count, pixels);
        delete[] pixels;
    }

    return new Image(finalPixels,
                     imgs[0]->width,
                     imgs[0]->height,
                     imgs[0]->maxValue);
}
<|endoftext|>


<commit_before>#include "packet/framing.h"
#include "osal.h"

/*
 * Packet framing uses the Consistent Overhead Byte Stuffing algorithm for
 * encoding data bytes. The maximum length for each packet is limited to 254 bytes.
 * Refer to: https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing
 */

namespace packet {
namespace framing {

uint8_t stuff(const void* source, void* dest, uint8_t source_byte_size) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);
    osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET,
            "source data exceeds allowed frame algorithm size");

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    const char* end = source_ + source_byte_size;
    char* code_p = dest_++; /* pointer to write code */
    uint8_t code = 0x01;

    auto write_code = [&]() {
        *code_p = code;
        code_p = dest_++;
        code = 0x01;
    };

    while (source_ < end) {
        if (*source_ == 0) { /* handle zero byte in data */
            write_code();
        } else { /* handle non-zero byte */
            *dest_++ = *source_;
            if (++code == 0xff) { /* reached max COBS data size */
                write_code();
            }
        }
        ++source_;
    }
    write_code();
    *dest_ = COBS_PACKET_DELIMITER;
    return source_byte_size + PACKET_OVERHEAD;
}

uint8_t unstuff(const void* source, void* dest, uint8_t source_byte_size) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);
    // osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET + 1,
    // "invalid data size"); always true due to data type

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    const char* end = source_ + source_byte_size;
    while (source_ < end) {
        uint8_t code = *source_++;

        if (code == 0) {
            osalDbgAssert(dest_ != static_cast<char*>(dest), "zero byte input");
            break;
        }
        osalDbgAssert((code - 1) <= (end - source_), "input code too small or source buffer too small");
        for (uint8_t i = 1; i < code; ++i) {
            *dest_++ = *source_++;
        }
        if (code < 0xff) { /* don't write the end-of-packet zero if data length = 0xff */
            *dest_++ = 0;
        }
    }
    return source_byte_size - PACKET_OVERHEAD;
}

uint8_t unstuff(const void* source, void* dest) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    const char* start = dest_;
    while (true) {
        uint8_t code = *source_++;

        if (code == 0) {
            osalDbgAssert(start != dest_, "zero byte input");
            break;
        }
        osalDbgAssert((code - 1) <= (COBS_MAX_SIZE_DATA_SET - (dest_ - start)),
                "input code too small or source buffer too small");
        for (uint8_t i = 1; i < code; ++i) {
            *dest_++ = *source_++;
        }
        if (code < 0xff) { /* don't write the end-of-packet zero if data length = 0xff */
            *dest_++ = 0;
        }
    }
    return dest_ - start;
}

} // namespace framing
} // namespace packet
<commit_msg>Fix bytes written calculation in unstuff<commit_after>#include "packet/framing.h"
#include "osal.h"

/*
 * Packet framing uses the Consistent Overhead Byte Stuffing algorithm for
 * encoding data bytes. The maximum length for each packet is limited to 254 bytes.
 * Refer to: https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing
 */

namespace packet {
namespace framing {

uint8_t stuff(const void* source, void* dest, uint8_t source_byte_size) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);
    osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET,
            "source data exceeds allowed frame algorithm size");

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    const char* end = source_ + source_byte_size;
    char* code_p = dest_++; /* pointer to write code */
    uint8_t code = 0x01;

    auto write_code = [&]() {
        *code_p = code;
        code_p = dest_++;
        code = 0x01;
    };

    while (source_ < end) {
        if (*source_ == 0) { /* handle zero byte in data */
            write_code();
        } else { /* handle non-zero byte */
            *dest_++ = *source_;
            if (++code == 0xff) { /* reached max COBS data size */
                write_code();
            }
        }
        ++source_;
    }
    write_code();
    *dest_ = COBS_PACKET_DELIMITER;
    return source_byte_size + PACKET_OVERHEAD;
}

uint8_t unstuff(const void* source, void* dest, uint8_t source_byte_size) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);
    // osalDbgAssert(source_byte_size <= COBS_MAX_SIZE_DATA_SET + 1,
    // "invalid data size"); always true due to data type

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    const char* end = source_ + source_byte_size;
    while (source_ < end) {
        uint8_t code = *source_++;

        if (code == 0) {
            osalDbgAssert(dest_ != static_cast<char*>(dest), "zero byte input");
            break;
        }
        osalDbgAssert((code - 1) <= (end - source_), "input code too small or source buffer too small");
        for (uint8_t i = 1; i < code; ++i) {
            *dest_++ = *source_++;
        }
        if (code < 0xff) { /* don't write the end-of-packet zero if data length = 0xff */
            *dest_++ = 0;
        }
    }
    return source_byte_size - PACKET_OVERHEAD;
}

uint8_t unstuff(const void* source, void* dest) {
    osalDbgCheck(source != nullptr);
    osalDbgCheck(dest != nullptr);

    const char* source_ = static_cast<const char*>(source);
    char* dest_ = static_cast<char*>(dest);

    while (true) {
        uint8_t code = *source_++;

        if (code == 0) {
            osalDbgAssert(dest_ != static_cast<char*>(dest), "zero byte input");
            break;
        }
        osalDbgAssert((code - 1) <=
                (COBS_MAX_SIZE_DATA_SET - (dest_ - static_cast<char*>(dest) - 1)),
                "input code too small or source buffer too small");
        for (uint8_t i = 1; i < code; ++i) {
            *dest_++ = *source_++;
        }
        if (code < 0xff) { /* don't write the end-of-packet zero if data length = 0xff */
            *dest_++ = 0;
        }
    }
    return dest_ - static_cast<char*>(dest) - 1;
}

} // namespace framing
} // namespace packet
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "init.h"

// #ifndef WIN32
// #include <signal.h>
// #endif

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern void noui_connect();

int GetDigitValue (char digit)
{
     int asciiOffset, digitValue;
     if (digit >= 48 && digit <= 57)
     {
        // code for '0' through '9'
        asciiOffset = 48;
        digitValue = digit - asciiOffset;
        return digitValue;
     }
     else if (digit >= 65 && digit <= 70)
     {
        // digit is 'A' through 'F'
        asciiOffset = 55;
        digitValue = digit - asciiOffset;
        return digitValue;
     }
     else if (digit >= 97 && digit <= 102)
     {
        // code for 'a' through 'f'
        asciiOffset = 87;
        digitValue = digit - asciiOffset;
        return digitValue;
     }
     else
     {
           // illegal digit
        return -1;
     }
}
std::vector<unsigned char> Convert (SecureString hexNumber)
// assumes 2 character string with legal hex digits
{
     std::vector<unsigned char> chars;
     int size = hexNumber.length();
     for (int i = 0; i < size; i+=2)
     {
         char highOrderDig = hexNumber[i];
         char lowOrderDig  = hexNumber[i+1];
         int lowOrderValue = GetDigitValue(lowOrderDig);//;  convert lowOrderDig to number from 0 to 15
         int highOrderValue = GetDigitValue(highOrderDig);//; convert highOrderDig to number from 0 to 15
         chars.push_back(lowOrderValue + 16 * highOrderValue);
    }
     return chars;
}
inline double Factorial(int x) {
  return (x == 1 ? x : x * Factorial(x - 1));
}
int main(int argc, char* argv[])
{
    CCrypter crypter;
    CKeyingMaterial vMasterKey;

    // Use the crypto from the locked wallet
    const unsigned int nDeriveIterations = 90367;
    const std::vector<unsigned char> chSalt = Convert("693f87a08e771ef0");
    const std::vector<unsigned char> vchCryptedKey = Convert("153eabea2afe4fa960c4d0cc05eb8b233f7f00bc4dc55bebf129f40cdcc3bec3451d572c0851fa5327d08d532f48bbd5");
    const std::vector<unsigned char> vchPubKey = Convert("04ffa71a0b3024136808c2e131a640e30b9c78812699e4cfa3b38a846207dcded9eade2549378c861e38343873ef9a94c6b54660c8aa0bd20146add7a0df7b4543");
    const std::vector<unsigned char> vchCryptedSecret = Convert("6c88d9b67f5b3b0cb7390da96b1eeb04e520e3add8c8370959d045f5bb185a39fbea6fddd4f67a665c599e7620d4b9ce");

    // Try any password as input
    SecureString attempt;
    std::getline(std::cin, attempt);

    do{
        const SecureString strWalletPassphrase = attempt;
        std::cout << strWalletPassphrase <<"\n";
        if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, chSalt, nDeriveIterations, 0))
        {
            // cout << i << " " << strWalletPassphrase <<"\n";
            continue;
        }
        if (!crypter.Decrypt(vchCryptedKey, vMasterKey))
        {
            // cout << i << " " << strWalletPassphrase <<"\n";
            continue;
        }

        CSecret vchSecret;
        if(!DecryptSecret(vMasterKey, vchCryptedSecret, Hash(vchPubKey.begin(), vchPubKey.end()), vchSecret))
        {
            // cout << "** didn't decrypt **" <<"\n";
            continue;
        }
        if (vchSecret.size() != 32)
        {
            // cout << "** wrong size secret **" <<"\n";
            continue;
        }
        CKey key;
        key.SetPubKey(vchPubKey);
        key.SetSecret(vchSecret);
        if (key.GetPubKey() == vchPubKey)
        {
            std::cout<<"Found it: "<<strWalletPassphrase<<"\n";
            return 0;
        }

    }while(std::getline(std::cin, attempt));

    return 0;
}
<commit_msg>added comment about wallet values<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "init.h"

// #ifndef WIN32
// #include <signal.h>
// #endif

CWallet* pwalletMain;
CClientUIInterface uiInterface;

extern void noui_connect();

int GetDigitValue (char digit)
{
     int asciiOffset, digitValue;
     if (digit >= 48 && digit <= 57)
     {
        // code for '0' through '9'
        asciiOffset = 48;
        digitValue = digit - asciiOffset;
        return digitValue;
     }
     else if (digit >= 65 && digit <= 70)
     {
        // digit is 'A' through 'F'
        asciiOffset = 55;
        digitValue = digit - asciiOffset;
        return digitValue;
     }
     else if (digit >= 97 && digit <= 102)
     {
        // code for 'a' through 'f'
        asciiOffset = 87;
        digitValue = digit - asciiOffset;
        return digitValue;
     }
     else
     {
           // illegal digit
        return -1;
     }
}
std::vector<unsigned char> Convert (SecureString hexNumber)
// assumes 2 character string with legal hex digits
{
     std::vector<unsigned char> chars;
     int size = hexNumber.length();
     for (int i = 0; i < size; i+=2)
     {
         char highOrderDig = hexNumber[i];
         char lowOrderDig  = hexNumber[i+1];
         int lowOrderValue = GetDigitValue(lowOrderDig);//;  convert lowOrderDig to number from 0 to 15
         int highOrderValue = GetDigitValue(highOrderDig);//; convert highOrderDig to number from 0 to 15
         chars.push_back(lowOrderValue + 16 * highOrderValue);
    }
     return chars;
}
inline double Factorial(int x) {
  return (x == 1 ? x : x * Factorial(x - 1));
}
int main(int argc, char* argv[])
{
    CCrypter crypter;
    CKeyingMaterial vMasterKey;

    // Use the crypto from the locked wallet
    // Replace these values with your own
    // Note: so far I have had no luck cracking these values
    //       they are from my locked wallet. If anyone has success,
    //       I will reward them with 5 bitcoin. email me at jakeva (at) gmail (dot) com
    const unsigned int nDeriveIterations = 90367;
    const std::vector<unsigned char> chSalt = Convert("693f87a08e771ef0");
    const std::vector<unsigned char> vchCryptedKey = Convert("153eabea2afe4fa960c4d0cc05eb8b233f7f00bc4dc55bebf129f40cdcc3bec3451d572c0851fa5327d08d532f48bbd5");
    const std::vector<unsigned char> vchPubKey = Convert("04ffa71a0b3024136808c2e131a640e30b9c78812699e4cfa3b38a846207dcded9eade2549378c861e38343873ef9a94c6b54660c8aa0bd20146add7a0df7b4543");
    const std::vector<unsigned char> vchCryptedSecret = Convert("6c88d9b67f5b3b0cb7390da96b1eeb04e520e3add8c8370959d045f5bb185a39fbea6fddd4f67a665c599e7620d4b9ce");

    // Try any password as input
    SecureString attempt;
    std::getline(std::cin, attempt);

    do{
        const SecureString strWalletPassphrase = attempt;
        std::cout << strWalletPassphrase <<"\n";
        if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, chSalt, nDeriveIterations, 0))
        {
            // cout << i << " " << strWalletPassphrase <<"\n";
            continue;
        }
        if (!crypter.Decrypt(vchCryptedKey, vMasterKey))
        {
            // cout << i << " " << strWalletPassphrase <<"\n";
            continue;
        }

        CSecret vchSecret;
        if(!DecryptSecret(vMasterKey, vchCryptedSecret, Hash(vchPubKey.begin(), vchPubKey.end()), vchSecret))
        {
            // cout << "** didn't decrypt **" <<"\n";
            continue;
        }
        if (vchSecret.size() != 32)
        {
            // cout << "** wrong size secret **" <<"\n";
            continue;
        }
        CKey key;
        key.SetPubKey(vchPubKey);
        key.SetSecret(vchSecret);
        if (key.GetPubKey() == vchPubKey)
        {
            std::cout<<"Found it: "<<strWalletPassphrase<<"\n";
            return 0;
        }

    }while(std::getline(std::cin, attempt));

    return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtGui/qgraphicssceneindex.h>
#include <private/qgraphicsscene_bsp_p.h>

//TESTED_CLASS=
//TESTED_FILES=

class tst_QGraphicsSceneIndex : public QObject
{
    Q_OBJECT
public slots:
    void initTestCase();

private slots:
    void sceneRect_data();
    void sceneRect();

private:
    void common_data();
    QGraphicsSceneIndex *createIndex(const QString &name);
};

void tst_QGraphicsSceneIndex::initTestCase()
{
}

void tst_QGraphicsSceneIndex::common_data()
{
    QTest::addColumn<QString>("indexMethod");

    QTest::newRow("BSP") << QString("bsp");
}

QGraphicsSceneIndex *tst_QGraphicsSceneIndex::createIndex(const QString &indexMethod)
{
    QGraphicsSceneIndex *index = 0;

    if (indexMethod == "bsp")
        index = new QGraphicsSceneBspTree;

    return index;
}

void tst_QGraphicsSceneIndex::sceneRect_data()
{
    common_data();
}

void tst_QGraphicsSceneIndex::sceneRect()
{
    QGraphicsSceneIndex *index = new QGraphicsSceneBspTree;
    index->setRect(QRectF(0, 0, 2000, 2000));
    QCOMPARE(index->rect(), QRectF(0, 0, 2000, 2000));
}

QTEST_MAIN(tst_QGraphicsSceneIndex)
#include "tst_qgraphicssceneindex.moc"
<commit_msg>Fixes:    Autotest for changing the index method of a scene.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtGui/qgraphicsscene.h>
#include <QtGui/qgraphicssceneindex.h>
#include <private/qgraphicsscene_bsp_p.h>

//TESTED_CLASS=
//TESTED_FILES=

class tst_QGraphicsSceneIndex : public QObject
{
    Q_OBJECT
public slots:
    void initTestCase();

private slots:
    void sceneRect_data();
    void sceneRect();
    void customIndex_data();
    void customIndex();

private:
    void common_data();
    QGraphicsSceneIndex *createIndex(const QString &name);
};

void tst_QGraphicsSceneIndex::initTestCase()
{
}

void tst_QGraphicsSceneIndex::common_data()
{
    QTest::addColumn<QString>("indexMethod");

    QTest::newRow("BSP") << QString("bsp");
}

QGraphicsSceneIndex *tst_QGraphicsSceneIndex::createIndex(const QString &indexMethod)
{
    QGraphicsSceneIndex *index = 0;

    if (indexMethod == "bsp")
        index = new QGraphicsSceneBspTree;

    return index;
}

void tst_QGraphicsSceneIndex::sceneRect_data()
{
    common_data();
}

void tst_QGraphicsSceneIndex::sceneRect()
{
    QGraphicsSceneIndex *index = new QGraphicsSceneBspTree;
    index->setRect(QRectF(0, 0, 2000, 2000));
    QCOMPARE(index->rect(), QRectF(0, 0, 2000, 2000));
}

void tst_QGraphicsSceneIndex::customIndex_data()
{
    common_data();
}

void tst_QGraphicsSceneIndex::customIndex()
{
    QFETCH(QString, indexMethod);
    QGraphicsSceneIndex *index = createIndex(indexMethod);

    QGraphicsScene scene;
    scene.setSceneIndex(index);

    scene.addRect(0, 0, 30, 40);
    QCOMPARE(scene.items(QRectF(0, 0, 10, 10)).count(), 1);
}

QTEST_MAIN(tst_QGraphicsSceneIndex)
#include "tst_qgraphicssceneindex.moc"
<|endoftext|>


<commit_before>///
/// @file  pi_lmo_simple.cpp
/// @brief Simple demonstration implementation of the
///        Lagarias-Miller-Odlyzko prime counting algorithm.
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include "imath.h"
#include "Pk.h"
#include "phi.h"

#include <primesieve/soe/PrimeSieve.h>
#include <primecount.h>
#include <stdint.h>
#include <vector>
#include <limits>

namespace primecount {

/// Initialize a vector with Möbius function values.
/// This implementation is based on code by Rick Sladkey
/// posted here: http://mathoverflow.net/a/99545
///
void init_moebius(std::vector<int32_t>& mu, int64_t max)
{
  mu.resize(max + 1, 1);

  for (int32_t i = 2; i * i <= max; i++)
  {
    if (mu[i] == 1)
    {
      for (int32_t j = i; j <= max; j += i)
        mu[j] *= -i;
      for (int32_t j = i * i; j <= max; j += i * i)
        mu[j] = 0;
    }
  }
  for (int32_t i = 2; i <= max; i++)
  {
    if (mu[i] == i)
      mu[i] = 1;
    else if (mu[i] == -i)
      mu[i] = -1;
    else if (mu[i] < 0)
      mu[i] = 1;
    else if (mu[i] > 0)
      mu[i] = -1;
  }
}

/// Initialize a vector with the least prime
/// factors of the integers <= max.
///
void init_least_factor(std::vector<int32_t>& lpf, int64_t max)
{
  lpf.resize(max + 1, 1);

  // phi(x / 1, c) contributes to the sum,
  // lpf[1] = MAX in order to pass
  // if (least_factor[1] > primes[c])
  if (lpf.size() > 1)
    lpf[1] = std::numeric_limits<int32_t>::max();

  for (int32_t i = 2; i * i <= max; i++)
    if (lpf[i] == 1)
      for (int32_t j = i * 2; j <= max; j += i)
        if (lpf[j] == 1)
          lpf[j] = i;

  for (int32_t i = 2; i <= max; i++)
    if (lpf[i] == 1)
      lpf[i] = i;
}

/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3)) operations, O(x^(1/3)) space.
///
int64_t pi_lmo_simple(int64_t x, int threads)
{
  int64_t x13 = iroot<3>(x);
  int64_t a = pi_meissel(x13);
  int64_t c = 7;

  // generate the primes <= x^(1/3)
  std::vector<int32_t> primes;
  primes.push_back(0);
  PrimeSieve ps;
  ps.generate_N_Primes(a, &primes);

  if (a < c || isqrt(x) < primes[c + 1])
    return pi_meissel(x);

  std::vector<int32_t> moebius;
  std::vector<int32_t> least_factor;
  init_moebius(moebius, x13);
  init_least_factor(least_factor, x13);

  int64_t S1 = 0;
  int64_t S2 = 0;

  for (int64_t n = 1; n <= x13; n++)
    if (least_factor[n] > primes[c])
      S1 += moebius[n] * phi(x / n, c);

  for (int64_t b = c; b + 1 < a; b++)
    for (int64_t m = (x13 / primes[b + 1]) + 1; m <= x13; m++)
      if (least_factor[m] > primes[b + 1])
        S2 -= moebius[m] * phi(x / (m * primes[b + 1]), b);

  int64_t phi = S1 + S2;
  int64_t sum = phi + a - 1 - P2(x, a);

  return sum;
}

} // namespace primecount
<commit_msg>Fixed array bound checking<commit_after>///
/// @file  pi_lmo_simple.cpp
/// @brief Simple demonstration implementation of the
///        Lagarias-Miller-Odlyzko prime counting algorithm.
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include "imath.h"
#include "Pk.h"
#include "phi.h"

#include <primesieve/soe/PrimeSieve.h>
#include <primecount.h>
#include <stdint.h>
#include <vector>
#include <limits>

namespace primecount {

/// Initialize a vector with Möbius function values.
/// This implementation is based on code by Rick Sladkey
/// posted here: http://mathoverflow.net/a/99545
///
void init_moebius(std::vector<int32_t>& mu, int64_t max)
{
  mu.resize(max + 1, 1);

  for (int32_t i = 2; i * i <= max; i++)
  {
    if (mu[i] == 1)
    {
      for (int32_t j = i; j <= max; j += i)
        mu[j] *= -i;
      for (int32_t j = i * i; j <= max; j += i * i)
        mu[j] = 0;
    }
  }
  for (int32_t i = 2; i <= max; i++)
  {
    if (mu[i] == i)
      mu[i] = 1;
    else if (mu[i] == -i)
      mu[i] = -1;
    else if (mu[i] < 0)
      mu[i] = 1;
    else if (mu[i] > 0)
      mu[i] = -1;
  }
}

/// Initialize a vector with the least prime
/// factors of the integers <= max.
///
void init_least_factor(std::vector<int32_t>& lpf, int64_t max)
{
  lpf.resize(max + 1, 1);

  // phi(x / 1, c) contributes to the sum,
  // lpf[1] = MAX in order to pass
  // if (least_factor[1] > primes[c])
  if (lpf.size() > 1)
    lpf[1] = std::numeric_limits<int32_t>::max();

  for (int32_t i = 2; i * i <= max; i++)
    if (lpf[i] == 1)
      for (int32_t j = i * 2; j <= max; j += i)
        if (lpf[j] == 1)
          lpf[j] = i;

  for (int32_t i = 2; i <= max; i++)
    if (lpf[i] == 1)
      lpf[i] = i;
}

/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3)) operations, O(x^(1/3)) space.
///
int64_t pi_lmo_simple(int64_t x, int threads)
{
  int64_t x13 = iroot<3>(x);
  int64_t a = pi_meissel(x13);
  int64_t c = 7;

  // generate the primes <= x^(1/3)
  std::vector<int32_t> primes;
  primes.push_back(0);
  PrimeSieve ps;
  ps.generate_N_Primes(a, &primes);

  if (a < c + 1 || isqrt(x) < primes[c + 1])
    return pi_meissel(x);

  std::vector<int32_t> moebius;
  std::vector<int32_t> least_factor;
  init_moebius(moebius, x13);
  init_least_factor(least_factor, x13);

  int64_t S1 = 0;
  int64_t S2 = 0;

  for (int64_t n = 1; n <= x13; n++)
    if (least_factor[n] > primes[c])
      S1 += moebius[n] * phi(x / n, c);

  for (int64_t b = c; b + 1 < a; b++)
    for (int64_t m = (x13 / primes[b + 1]) + 1; m <= x13; m++)
      if (least_factor[m] > primes[b + 1])
        S2 -= moebius[m] * phi(x / (m * primes[b + 1]), b);

  int64_t phi = S1 + S2;
  int64_t sum = phi + a - 1 - P2(x, a);

  return sum;
}

} // namespace primecount
<|endoftext|>


<commit_before>#include "usbutil.h"
#include "buffers.h"
#include "log.h"

#define USB_PACKET_SIZE 64

extern "C" {
extern bool handleControlRequest(uint8_t);
}

// This is a reference to the last packet read
extern volatile CTRL_TRF_SETUP SetupPkt;
extern UsbDevice USB_DEVICE;

boolean usbCallback(USB_EVENT event, void *pdata, word size) {
    // initial connection up to configure will be handled by the default
    // callback routine.
    USB_DEVICE.device.DefaultCBEventHandler(event, pdata, size);

    switch(event) {
    case EVENT_CONFIGURED:
        debug("USB Configured\r\n");
        USB_DEVICE.configured = true;
        USB_DEVICE.device.EnableEndpoint(USB_DEVICE.inEndpoint,
                USB_IN_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
        USB_DEVICE.device.EnableEndpoint(USB_DEVICE.outEndpoint,
                USB_OUT_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
        break;

    case EVENT_EP0_REQUEST:
        handleControlRequest(SetupPkt.bRequest);
        break;

    default:
        break;
    }
}

void sendControlMessage(uint8_t* data, uint8_t length) {
    USB_DEVICE.device.EP0SendRAMPtr(data, length, USB_EP0_INCLUDE_ZERO);
}

bool waitForHandle(UsbDevice* usbDevice) {
    int i = 0;
    while(usbDevice->device.HandleBusy(usbDevice->deviceToHostHandle)) {
        ++i;
        if(i > 400) {
            debug("USB most likely not connected or at least not requesting "
                    "IN transfers - bailing out of handle waiting\r\n");
            return false;
        }
    }
    return true;
}

void processUsbSendQueue(UsbDevice* usbDevice) {
    if(!usbDevice->configured) {
        return;
    }

    while(!QUEUE_EMPTY(uint8_t, &usbDevice->sendQueue)) {
        // Make sure the USB write is 100% complete before messing with this buffer
        // after we copy the message into it - the Microchip library doesn't copy
        // the data to its own internal buffer. See #171 for background on this
        // issue.
        if(!waitForHandle(usbDevice)) {
            return;
        }

        int byteCount = 0;
        while(!QUEUE_EMPTY(uint8_t, &usbDevice->sendQueue) && byteCount < 64) {
            usbDevice->sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &usbDevice->sendQueue);
        }

        int nextByteIndex = 0;
        while(nextByteIndex < byteCount) {
            if(!waitForHandle(usbDevice)) {
                return;
            }
            int bytesToTransfer = min(USB_PACKET_SIZE, byteCount - nextByteIndex);
            usbDevice->deviceToHostHandle = usbDevice->device.GenWrite(
                    usbDevice->inEndpoint, &usbDevice->sendBuffer[nextByteIndex], bytesToTransfer);
            nextByteIndex += bytesToTransfer;
        }
    }
}

void initializeUsb(UsbDevice* usbDevice) {
    debug("Initializing USB.....");
	usbDevice->device = USBDevice(usbCallback);
    usbDevice->device.InitializeSystem(false);
    QUEUE_INIT(uint8_t, &usbDevice->sendQueue);
    QUEUE_INIT(uint8_t, &usbDevice->receiveQueue);
    debug("Done.\r\n");
}

void armForRead(UsbDevice* usbDevice, char* buffer) {
    buffer[0] = 0;
    usbDevice->hostToDeviceHandle = usbDevice->device.GenRead(
            usbDevice->outEndpoint, (uint8_t*)buffer, usbDevice->outEndpointSize);
}

void readFromHost(UsbDevice* usbDevice, bool (*callback)(uint8_t*)) {
    if(!usbDevice->device.HandleBusy(usbDevice->hostToDeviceHandle)) {
        if(usbDevice->receiveBuffer[0] != NULL) {
            for(int i = 0; i < usbDevice->outEndpointSize; i++) {
                if(!QUEUE_PUSH(uint8_t, &usbDevice->receiveQueue,
                            usbDevice->receiveBuffer[i])) {
                    debug("Dropped write from host -- queue is full\r\n");
                }
            }
            processQueue(&usbDevice->receiveQueue, callback);
        }
        armForRead(usbDevice, usbDevice->receiveBuffer);
    }
}
<commit_msg>Increase USB send timeout in order to pass bench test at 100%.<commit_after>#include "usbutil.h"
#include "buffers.h"
#include "log.h"

#define USB_PACKET_SIZE 64

extern "C" {
extern bool handleControlRequest(uint8_t);
}

// This is a reference to the last packet read
extern volatile CTRL_TRF_SETUP SetupPkt;
extern UsbDevice USB_DEVICE;

boolean usbCallback(USB_EVENT event, void *pdata, word size) {
    // initial connection up to configure will be handled by the default
    // callback routine.
    USB_DEVICE.device.DefaultCBEventHandler(event, pdata, size);

    switch(event) {
    case EVENT_CONFIGURED:
        debug("USB Configured\r\n");
        USB_DEVICE.configured = true;
        USB_DEVICE.device.EnableEndpoint(USB_DEVICE.inEndpoint,
                USB_IN_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
        USB_DEVICE.device.EnableEndpoint(USB_DEVICE.outEndpoint,
                USB_OUT_ENABLED|USB_HANDSHAKE_ENABLED|USB_DISALLOW_SETUP);
        break;

    case EVENT_EP0_REQUEST:
        handleControlRequest(SetupPkt.bRequest);
        break;

    default:
        break;
    }
}

void sendControlMessage(uint8_t* data, uint8_t length) {
    USB_DEVICE.device.EP0SendRAMPtr(data, length, USB_EP0_INCLUDE_ZERO);
}

bool waitForHandle(UsbDevice* usbDevice) {
    int i = 0;
    while(usbDevice->device.HandleBusy(usbDevice->deviceToHostHandle)) {
        ++i;
        if(i > 800) {
            debug("USB most likely not connected or at least not requesting "
                    "IN transfers - bailing out of handle waiting\r\n");
            return false;
        }
    }
    return true;
}

void processUsbSendQueue(UsbDevice* usbDevice) {
    if(!usbDevice->configured) {
        return;
    }

    while(!QUEUE_EMPTY(uint8_t, &usbDevice->sendQueue)) {
        // Make sure the USB write is 100% complete before messing with this buffer
        // after we copy the message into it - the Microchip library doesn't copy
        // the data to its own internal buffer. See #171 for background on this
        // issue.
        if(!waitForHandle(usbDevice)) {
            return;
        }

        int byteCount = 0;
        while(!QUEUE_EMPTY(uint8_t, &usbDevice->sendQueue) && byteCount < 64) {
            usbDevice->sendBuffer[byteCount++] = QUEUE_POP(uint8_t, &usbDevice->sendQueue);
        }

        int nextByteIndex = 0;
        while(nextByteIndex < byteCount) {
            if(!waitForHandle(usbDevice)) {
                return;
            }
            int bytesToTransfer = min(USB_PACKET_SIZE, byteCount - nextByteIndex);
            usbDevice->deviceToHostHandle = usbDevice->device.GenWrite(
                    usbDevice->inEndpoint, &usbDevice->sendBuffer[nextByteIndex], bytesToTransfer);
            nextByteIndex += bytesToTransfer;
        }
    }
}

void initializeUsb(UsbDevice* usbDevice) {
    debug("Initializing USB.....");
	usbDevice->device = USBDevice(usbCallback);
    usbDevice->device.InitializeSystem(false);
    QUEUE_INIT(uint8_t, &usbDevice->sendQueue);
    QUEUE_INIT(uint8_t, &usbDevice->receiveQueue);
    debug("Done.\r\n");
}

void armForRead(UsbDevice* usbDevice, char* buffer) {
    buffer[0] = 0;
    usbDevice->hostToDeviceHandle = usbDevice->device.GenRead(
            usbDevice->outEndpoint, (uint8_t*)buffer, usbDevice->outEndpointSize);
}

void readFromHost(UsbDevice* usbDevice, bool (*callback)(uint8_t*)) {
    if(!usbDevice->device.HandleBusy(usbDevice->hostToDeviceHandle)) {
        if(usbDevice->receiveBuffer[0] != NULL) {
            for(int i = 0; i < usbDevice->outEndpointSize; i++) {
                if(!QUEUE_PUSH(uint8_t, &usbDevice->receiveQueue,
                            usbDevice->receiveBuffer[i])) {
                    debug("Dropped write from host -- queue is full\r\n");
                }
            }
            processQueue(&usbDevice->receiveQueue, callback);
        }
        armForRead(usbDevice, usbDevice->receiveBuffer);
    }
}
<|endoftext|>