<commit_before>/**
 * Non-metric Space Library
 *
 * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info).
 * With contributions from Lawrence Cayton (http://lcayton.com/) and others.
 *
 * For the complete list of contributors and further details see:
 * https://github.com/searchivarius/NonMetricSpaceLib
 *
 * Copyright (c) 2014
 *
 * This code is released under the
 * Apache License Version 2.0 http://www.apache.org/licenses/.
 *
 */

#include <unordered_map>
#include <queue>

#include "space.h"
#include "knnquery.h"
#include "method/simple_inverted_index.h"
#include "falconn_heap_mod.h"
#include "ported_boost_progress.h"

#define SANITY_CHECKS

namespace similarity {

using namespace std;

template <typename dist_t>
void SimplInvIndex<dist_t>::Search(KNNQuery<dist_t>* query, IdType) const {
  // the query vector, its size is the number of query terms (non-zero dimensions of the query vector)
  vector<SparseVectElem<dist_t>>    query_vect;
  const Object* o = query->QueryObject();
  UnpackSparseElements(o->data(), o->datalength(), query_vect);

  size_t K = query->GetK();

  // sorted list (priority queue) of pairs (doc_id, its_position_in_the_posting_list)
  //   the doc_ids are negative to keep the queue ordered the way we need
  FalconnHeapMod1<IdType, int32_t>            postListQueue;
  // state information for each query-term posting list
  vector<unique_ptr<PostListQueryState>>      queryStates(query_vect.size());

  // number of valid query terms (that are in the dictionary)
  size_t wordQty = 0;
  // query term index
  unsigned qsi = 0;
  // initialize queryStates and postListQueue variables
  for (auto eQuery : query_vect) {
    auto it = index_.find(eQuery.id_);
    if (it != index_.end()) { // There may be out-of-vocabulary words
#ifdef SANITY_CHECKS
      CHECK(it->second.get() != nullptr);
#endif
      const PostList& pl = *it->second;
      CHECK(pl.qty_ > 0);
      ++wordQty;
      // initialize the queryStates[query_term_index]  to the first position in the posting list
      queryStates[qsi].reset(new PostListQueryState(pl, eQuery.val_, eQuery.val_ * pl.entries_[0].val_));
      // initialize the postListQueue to the first position - insert pair (-doc_id, query_term_index)
      postListQueue.push(-pl.entries_[0].doc_id_, qsi);
    }
    ++qsi;
  }

  // While some people expect the result set to always contain at least k entries,
  // it's not clear what we return here
  if (0 == wordQty) return;

  // temporary queue with the top-K results  (ordered by the accumulated values so that top value is the smallest=worst document)
  FalconnHeapMod1<dist_t, IdType>             tmpResQueue;
  // accumulation of PostListQueryState.qval_x_docval_ for each document (DAAT)
  dist_t   accum = 0;

  while (!postListQueue.empty()) {
    // index of the posting list with the current SMALLEST doc_id
    IdType minDocIdNeg = postListQueue.top_key();

    // this while accumulates values for one document (DAAT), specifically for the one with   doc_id = -minDocIdNeg
    while (!postListQueue.empty() && postListQueue.top_key() == minDocIdNeg) {
      unsigned qsi = postListQueue.top_data();
      PostListQueryState& queryState = *queryStates[qsi];
      const PostList& pl = *queryState.post_;
      accum += queryState.qval_x_docval_;
      //accum += queryState.qval_ * pl.entries_[queryState.post_pos_].val_;

      // move to next position in the posting list
      queryState.post_pos_++;
      /*
       * If we didn't reach the end of the posting list, we retrieve the next document id.
       * Then, we push this update element down the priority queue.
       *
       * On reaching the end of the posting list, we evict the entry from the priority queue.
       */
      if (queryState.post_pos_ < pl.qty_) {
        // the next entry in the posting list
        const PostEntry& eDoc = pl.entries_[queryState.post_pos_];
        /*
         * Leo thinks it may be beneficial to access the posting list entry only once.
         * This access is used for two things
         * 1) obtain the next doc id
         * 2) compute the contribution of the current document to the overall dot product (val_ * qval_)
         */
        postListQueue.replace_top_key(-eDoc.doc_id_);
        queryState.qval_x_docval_ = eDoc.val_ * queryState.qval_;
      } else postListQueue.pop();
    }

    // tmpResQueue is a MAX-QUEUE (which is what we need, b/c we maximize the dot product
    dist_t negAccum = -accum;
#if 1
    // This one seems to be a bit faster
    // DAVID: THIS CONSTRUCTION IS WRONG. DUE TO THE FIRST CONDITION, THERE MIGHT BE MORE THAN K DOCUMENTS IN THE
    // RESULT, RIGHT? BUT THE SECOND FORK ONLY REPLACES ONE OF THE "WORST" DOCUMENTS
    if (tmpResQueue.size() < K || tmpResQueue.top_key() == negAccum)
      tmpResQueue.push(negAccum, -minDocIdNeg);
    else if (tmpResQueue.top_key() > negAccum)
      tmpResQueue.replace_top(negAccum, -minDocIdNeg);
#else
    query->CheckAndAddToResult(negAccum, data_[-minDocIdNeg]);
#endif

    accum = 0;
  }

  while (!tmpResQueue.empty()) {
#ifdef SANITY_CHECKS
    CHECK(tmpResQueue.top_data() >= 0);
#endif

#if 0
    query->CheckAndAddToResult(-tmpResQueue.top_key(), data_[tmpResQueue.top_data()]);
#else
    // This branch recomputes the distance, but it normally has a negligibly small effect on the run-time
    query->CheckAndAddToResult(data_[tmpResQueue.top_data()]);
#endif
    tmpResQueue.pop();
  }
}

template <typename dist_t>
void SimplInvIndex<dist_t>::CreateIndex(const AnyParams& IndexParams) {
  AnyParamManager pmgr(IndexParams);
  CreateIndex(pmgr);
}

template <typename dist_t>
void SimplInvIndex<dist_t>::CreateIndex(AnyParamManager& ParamManager) {
  ParamManager.CheckUnused();
  // Always call ResetQueryTimeParams() to set query-time parameters to their default values
  this->ResetQueryTimeParams();

  // Let's first calculate memory requirements
  unordered_map<unsigned, size_t>   dict_qty;
  vector<SparseVectElem<dist_t>>    tmp_vect;
  LOG(LIB_INFO) << "Collecting dictionary stat";

  ProgressDisplay  pbar(data_.size(), cerr);

  for (const Object* o : data_) {
    tmp_vect.clear();
    UnpackSparseElements(o->data(), o->datalength(), tmp_vect);
    for (const auto& e : tmp_vect) dict_qty[e.id_] ++;
    ++pbar;
  }

  LOG(LIB_INFO) << "Actually creating the index";
  // post_pos is a map of positions in the postings lists? (initialized as zeros)
  unordered_map<unsigned, size_t> post_pos;
  // Create posting-list place holders
  for (const auto dictEntry : dict_qty) {
    unsigned wordId = dictEntry.first;
    size_t   qty = dictEntry.second;
    post_pos.insert(make_pair(wordId, 0));
    // insert into index_ PostLists with pre-allocated number of PostEntries
    index_.insert(make_pair(wordId, unique_ptr<PostList>(new PostList(qty))));
  }

  // Fill posting lists
  for (size_t did = 0; did < data_.size(); ++did) {
    tmp_vect.clear();
    UnpackSparseElements(data_[did]->data(), data_[did]->datalength(), tmp_vect);
    // iterate over all terms in the document (non-zero values in the sparse vector)
    for (const auto& e : tmp_vect) {
      const auto wordId = e.id_;
      // posting list for given term (the value is probably a pair [position/key, value] ?)
      auto itPost     = index_.find(wordId);
      // actual position in the posting list
      auto itPostPos  = post_pos.find(wordId);
#ifdef SANITY_CHECKS
      CHECK(itPost != index_.end());
      CHECK(itPostPos != post_pos.end());
      CHECK(itPost->second.get() != nullptr);
#endif
      // the actual posting list
      PostList& pl = *itPost->second;
      // get actual position in the list (and shift it by +1)
      size_t curr_pos = itPostPos->second++;;
      CHECK(curr_pos < pl.qty_);
      pl.entries_[curr_pos] = PostEntry(did, e.val_);
    }
  }
#ifdef SANITY_CHECKS
  // Sanity check
  LOG(LIB_INFO) << "Sanity check";
  for (const auto dictEntry : dict_qty) {
    unsigned wordId = dictEntry.first;
    size_t qty = dictEntry.second;
    CHECK(qty == post_pos[wordId]);
  }
#endif
}

template <typename dist_t>
SimplInvIndex<dist_t>::~SimplInvIndex() {
// nothing here yet
}

template <typename dist_t>
void
SimplInvIndex<dist_t>::SetQueryTimeParams(const AnyParams& QueryTimeParams) {
  // Check if a user specified extra parameters, which can be also misspelled variants of existing ones
  AnyParamManager pmgr(QueryTimeParams);
  int dummy;
  // Note that GetParamOptional() should always have a default value
  pmgr.GetParamOptional("dummyParam", dummy, -1);
  LOG(LIB_INFO) << "Set dummy = " << dummy;
  pmgr.CheckUnused();
}

template class SimplInvIndex<float>;

}
<commit_msg>fixing the progress bar<commit_after>/**
 * Non-metric Space Library
 *
 * Authors: Bilegsaikhan Naidan (https://github.com/bileg), Leonid Boytsov (http://boytsov.info).
 * With contributions from Lawrence Cayton (http://lcayton.com/) and others.
 *
 * For the complete list of contributors and further details see:
 * https://github.com/searchivarius/NonMetricSpaceLib
 *
 * Copyright (c) 2014
 *
 * This code is released under the
 * Apache License Version 2.0 http://www.apache.org/licenses/.
 *
 */

#include <unordered_map>
#include <queue>

#include "space.h"
#include "knnquery.h"
#include "method/simple_inverted_index.h"
#include "falconn_heap_mod.h"
#include "ported_boost_progress.h"

#define SANITY_CHECKS

namespace similarity {

using namespace std;

template <typename dist_t>
void SimplInvIndex<dist_t>::Search(KNNQuery<dist_t>* query, IdType) const {
  // the query vector, its size is the number of query terms (non-zero dimensions of the query vector)
  vector<SparseVectElem<dist_t>>    query_vect;
  const Object* o = query->QueryObject();
  UnpackSparseElements(o->data(), o->datalength(), query_vect);

  size_t K = query->GetK();

  // sorted list (priority queue) of pairs (doc_id, its_position_in_the_posting_list)
  //   the doc_ids are negative to keep the queue ordered the way we need
  FalconnHeapMod1<IdType, int32_t>            postListQueue;
  // state information for each query-term posting list
  vector<unique_ptr<PostListQueryState>>      queryStates(query_vect.size());

  // number of valid query terms (that are in the dictionary)
  size_t wordQty = 0;
  // query term index
  unsigned qsi = 0;
  // initialize queryStates and postListQueue variables
  for (auto eQuery : query_vect) {
    auto it = index_.find(eQuery.id_);
    if (it != index_.end()) { // There may be out-of-vocabulary words
#ifdef SANITY_CHECKS
      CHECK(it->second.get() != nullptr);
#endif
      const PostList& pl = *it->second;
      CHECK(pl.qty_ > 0);
      ++wordQty;
      // initialize the queryStates[query_term_index]  to the first position in the posting list
      queryStates[qsi].reset(new PostListQueryState(pl, eQuery.val_, eQuery.val_ * pl.entries_[0].val_));
      // initialize the postListQueue to the first position - insert pair (-doc_id, query_term_index)
      postListQueue.push(-pl.entries_[0].doc_id_, qsi);
    }
    ++qsi;
  }

  // While some people expect the result set to always contain at least k entries,
  // it's not clear what we return here
  if (0 == wordQty) return;

  // temporary queue with the top-K results  (ordered by the accumulated values so that top value is the smallest=worst document)
  FalconnHeapMod1<dist_t, IdType>             tmpResQueue;
  // accumulation of PostListQueryState.qval_x_docval_ for each document (DAAT)
  dist_t   accum = 0;

  while (!postListQueue.empty()) {
    // index of the posting list with the current SMALLEST doc_id
    IdType minDocIdNeg = postListQueue.top_key();

    // this while accumulates values for one document (DAAT), specifically for the one with   doc_id = -minDocIdNeg
    while (!postListQueue.empty() && postListQueue.top_key() == minDocIdNeg) {
      unsigned qsi = postListQueue.top_data();
      PostListQueryState& queryState = *queryStates[qsi];
      const PostList& pl = *queryState.post_;
      accum += queryState.qval_x_docval_;
      //accum += queryState.qval_ * pl.entries_[queryState.post_pos_].val_;

      // move to next position in the posting list
      queryState.post_pos_++;
      /*
       * If we didn't reach the end of the posting list, we retrieve the next document id.
       * Then, we push this update element down the priority queue.
       *
       * On reaching the end of the posting list, we evict the entry from the priority queue.
       */
      if (queryState.post_pos_ < pl.qty_) {
        // the next entry in the posting list
        const PostEntry& eDoc = pl.entries_[queryState.post_pos_];
        /*
         * Leo thinks it may be beneficial to access the posting list entry only once.
         * This access is used for two things
         * 1) obtain the next doc id
         * 2) compute the contribution of the current document to the overall dot product (val_ * qval_)
         */
        postListQueue.replace_top_key(-eDoc.doc_id_);
        queryState.qval_x_docval_ = eDoc.val_ * queryState.qval_;
      } else postListQueue.pop();
    }

    // tmpResQueue is a MAX-QUEUE (which is what we need, b/c we maximize the dot product
    dist_t negAccum = -accum;
#if 1
    // This one seems to be a bit faster
    // DAVID: THIS CONSTRUCTION IS WRONG. DUE TO THE FIRST CONDITION, THERE MIGHT BE MORE THAN K DOCUMENTS IN THE
    // RESULT, RIGHT? BUT THE SECOND FORK ONLY REPLACES ONE OF THE "WORST" DOCUMENTS
    if (tmpResQueue.size() < K || tmpResQueue.top_key() == negAccum)
      tmpResQueue.push(negAccum, -minDocIdNeg);
    else if (tmpResQueue.top_key() > negAccum)
      tmpResQueue.replace_top(negAccum, -minDocIdNeg);
#else
    query->CheckAndAddToResult(negAccum, data_[-minDocIdNeg]);
#endif

    accum = 0;
  }

  while (!tmpResQueue.empty()) {
#ifdef SANITY_CHECKS
    CHECK(tmpResQueue.top_data() >= 0);
#endif

#if 0
    query->CheckAndAddToResult(-tmpResQueue.top_key(), data_[tmpResQueue.top_data()]);
#else
    // This branch recomputes the distance, but it normally has a negligibly small effect on the run-time
    query->CheckAndAddToResult(data_[tmpResQueue.top_data()]);
#endif
    tmpResQueue.pop();
  }
}

template <typename dist_t>
void SimplInvIndex<dist_t>::CreateIndex(const AnyParams& IndexParams) {
  AnyParamManager pmgr(IndexParams);
  CreateIndex(pmgr);
}

template <typename dist_t>
void SimplInvIndex<dist_t>::CreateIndex(AnyParamManager& ParamManager) {
  ParamManager.CheckUnused();
  // Always call ResetQueryTimeParams() to set query-time parameters to their default values
  this->ResetQueryTimeParams();

  // Let's first calculate memory requirements
  unordered_map<unsigned, size_t>   dict_qty;
  vector<SparseVectElem<dist_t>>    tmp_vect;
  LOG(LIB_INFO) << "Collecting dictionary stat";

  {
    ProgressDisplay  pbar(data_.size(), cerr);

    for (const Object* o : data_) {
      tmp_vect.clear();
      UnpackSparseElements(o->data(), o->datalength(), tmp_vect);
      for (const auto& e : tmp_vect) dict_qty[e.id_] ++;
      ++pbar;
    }
  }

  LOG(LIB_INFO) << "Actually creating the index";
  // post_pos is a map of positions in the postings lists? (initialized as zeros)
  unordered_map<unsigned, size_t> post_pos;
  // Create posting-list place holders
  for (const auto dictEntry : dict_qty) {
    unsigned wordId = dictEntry.first;
    size_t   qty = dictEntry.second;
    post_pos.insert(make_pair(wordId, 0));
    // insert into index_ PostLists with pre-allocated number of PostEntries
    index_.insert(make_pair(wordId, unique_ptr<PostList>(new PostList(qty))));
  }

  {
    ProgressDisplay  pbar(data_.size(), cerr);

    // Fill posting lists
    for (size_t did = 0; did < data_.size(); ++did) {
      tmp_vect.clear();
      UnpackSparseElements(data_[did]->data(), data_[did]->datalength(), tmp_vect);
      // iterate over all terms in the document (non-zero values in the sparse vector)
      for (const auto& e : tmp_vect) {
        const auto wordId = e.id_;
        // posting list for given term (the value is probably a pair [position/key, value] ?)
        auto itPost     = index_.find(wordId);
        // actual position in the posting list
        auto itPostPos  = post_pos.find(wordId);
  #ifdef SANITY_CHECKS
        CHECK(itPost != index_.end());
        CHECK(itPostPos != post_pos.end());
        CHECK(itPost->second.get() != nullptr);
  #endif
        // the actual posting list
        PostList& pl = *itPost->second;
        // get actual position in the list (and shift it by +1)
        size_t curr_pos = itPostPos->second++;;
        CHECK(curr_pos < pl.qty_);
        pl.entries_[curr_pos] = PostEntry(did, e.val_);
      }
      ++pbar;
    }
  }
#ifdef SANITY_CHECKS
  // Sanity check
  LOG(LIB_INFO) << "Sanity check";
  for (const auto dictEntry : dict_qty) {
    unsigned wordId = dictEntry.first;
    size_t qty = dictEntry.second;
    CHECK(qty == post_pos[wordId]);
  }
#endif
}

template <typename dist_t>
SimplInvIndex<dist_t>::~SimplInvIndex() {
// nothing here yet
}

template <typename dist_t>
void
SimplInvIndex<dist_t>::SetQueryTimeParams(const AnyParams& QueryTimeParams) {
  // Check if a user specified extra parameters, which can be also misspelled variants of existing ones
  AnyParamManager pmgr(QueryTimeParams);
  int dummy;
  // Note that GetParamOptional() should always have a default value
  pmgr.GetParamOptional("dummyParam", dummy, -1);
  LOG(LIB_INFO) << "Set dummy = " << dummy;
  pmgr.CheckUnused();
}

template class SimplInvIndex<float>;

}
<|endoftext|>


<commit_before>class Solution {
public:
    /**
     * @param A: A list of lists of integers
     * @return: An integer
     */
    int jump(vector<int> A) {
        // wirte your code here
        int n=A.size(),f[n+10],j,i,k;
        for (i=0;i<n+1;i++) f[i]=0;
        f[0]=1;
    	for (i=0;i<n;i++){

    	}
    }
};<commit_msg>Solve No.117<commit_after>class Solution {
public:
    /**
     * @param A: A list of lists of integers
     * @return: An integer
     */
    int jump(vector<int> A) {
        // wirte your code here
        int n=A.size(),f[n+10],j,i,k;
        for (i=0;i<n+1;i++) f[i]=INT_MAX/2;
        f[0]=0;
    	for (i=0;i<n;i++){
    		for (j=A[i];j>=1;j--){
    			if (i+j>=n) continue;
    			f[i+j]=min(f[i]+1,f[i+j]);
    		}
    	}

    	return f[n-1];
    }
};<|endoftext|>


<commit_before>#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/alert.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/error_code.hpp"

#include <fstream>

using namespace libtorrent;

int test_main()
{
	int http_port = start_web_server();
	int udp_port = start_tracker();

	int prev_udp_announces = g_udp_tracker_requests;
	int prev_http_announces = g_http_tracker_requests;

	int const alert_mask = alert::all_categories
		& ~alert::progress_notification
		& ~alert::stats_notification;

	session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask);

	session_settings sett;
	sett.half_open_limit = 1;
	sett.announce_to_all_trackers = true;
	sett.announce_to_all_tiers = true;
	s->set_settings(sett);

	error_code ec;
	create_directory("./tmp1_tracker", ec);
	std::ofstream file("./tmp1_tracker/temporary");
	boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	char tracker_url[200];
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url);

	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url);

	add_torrent_params addp;
	addp.paused = false;
	addp.auto_managed = false;
	addp.ti = t;
	addp.save_path = "./tmp1_tracker";
	torrent_handle h = s->add_torrent(addp);

	test_sleep(2000);

	// we should have announced to the tracker by now
	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 1);

	delete s;

	// we should have announced the stopped event now
	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 2);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 2);

	// ========================================
	// test that we move on to try the next tier if the first one fails
	// ========================================

	s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask);

	sett.half_open_limit = 1;
	sett.announce_to_all_trackers = true;
	sett.announce_to_all_tiers = false;
	sett.tracker_completion_timeout = 4;
	sett.tracker_receive_timeout = 2;
	s->set_settings(sett);

	create_directory("./tmp2_tracker", ec);
	file.open("./tmp2_tracker/temporary");
	t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	// this should fail
	snprintf(tracker_url, sizeof(tracker_url), "udp://www.google.com:80/announce");
	t->add_tracker(tracker_url, 0);

	// and this should fail
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce");
	t->add_tracker(tracker_url, 1);

	// this should be announced to
	// udp trackers are prioritized if they're on the same host as an http one
	// so this must be before the http one on 127.0.0.1
	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 2);

	// and this should not be announced to (since the one before it succeeded)
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 3);

	prev_udp_announces = g_udp_tracker_requests;
	prev_http_announces = g_http_tracker_requests;

	addp.paused = false;
	addp.auto_managed = false;
	addp.ti = t;
	addp.save_path = "./tmp2_tracker";
	h = s->add_torrent(addp);

	for (int i = 0; i < 10; ++i)
	{
		test_sleep(1000);
		print_alerts(*s, "s");
		if (g_udp_tracker_requests == prev_udp_announces + 1) break;
	}

	test_sleep(1000);

	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces);

	delete s;

	stop_tracker();
	stop_web_server();

	return 0;
}

<commit_msg>fix unit test<commit_after>#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/alert.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/error_code.hpp"

#include <fstream>

using namespace libtorrent;

int test_main()
{
	int http_port = start_web_server();
	int udp_port = start_tracker();

	int prev_udp_announces = g_udp_tracker_requests;
	int prev_http_announces = g_http_tracker_requests;

	int const alert_mask = alert::all_categories
		& ~alert::progress_notification
		& ~alert::stats_notification;

	session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask);

	session_settings sett;
	sett.half_open_limit = 1;
	sett.announce_to_all_trackers = true;
	sett.announce_to_all_tiers = true;
	s->set_settings(sett);

	error_code ec;
	create_directory("./tmp1_tracker", ec);
	std::ofstream file("./tmp1_tracker/temporary");
	boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	char tracker_url[200];
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url);

	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url);

	add_torrent_params addp;
	addp.paused = false;
	addp.auto_managed = false;
	addp.ti = t;
	addp.save_path = "./tmp1_tracker";
	torrent_handle h = s->add_torrent(addp);

	test_sleep(2000);

	// we should have announced to the tracker by now
	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 1);

	delete s;

	// we should have announced the stopped event now
	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 2);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces + 2);

	// ========================================
	// test that we move on to try the next tier if the first one fails
	// ========================================

	s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask);

	sett.half_open_limit = 1;
	sett.announce_to_all_trackers = true;
	sett.announce_to_all_tiers = false;
	sett.tracker_completion_timeout = 2;
	sett.tracker_receive_timeout = 1;
	s->set_settings(sett);

	create_directory("./tmp2_tracker", ec);
	file.open("./tmp2_tracker/temporary");
	t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	// this should fail
	snprintf(tracker_url, sizeof(tracker_url), "udp://www.google.com:80/announce");
	t->add_tracker(tracker_url, 0);

	// and this should fail
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce");
	t->add_tracker(tracker_url, 1);

	// this should be announced to
	// udp trackers are prioritized if they're on the same host as an http one
	// so this must be before the http one on 127.0.0.1
	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 2);

	// and this should not be announced to (since the one before it succeeded)
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 3);

	prev_udp_announces = g_udp_tracker_requests;
	prev_http_announces = g_http_tracker_requests;

	addp.paused = false;
	addp.auto_managed = false;
	addp.ti = t;
	addp.save_path = "./tmp2_tracker";
	h = s->add_torrent(addp);

	for (int i = 0; i < 10; ++i)
	{
		print_alerts(*s, "s");
		test_sleep(1000);
		if (g_udp_tracker_requests == prev_udp_announces + 1) break;
	}

	test_sleep(1000);

	TEST_EQUAL(g_udp_tracker_requests, prev_udp_announces + 1);
	TEST_EQUAL(g_http_tracker_requests, prev_http_announces);

	delete s;

	stop_tracker();
	stop_web_server();

	return 0;
}

<|endoftext|>


<commit_before>// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: keir@google.com (Keir Mierle)
//         sameeragarwal@google.com (Sameer Agarwal)

#include "ceres/solver.h"

#include <vector>
#include "ceres/levenberg_marquardt.h"
#include "ceres/program.h"
#include "ceres/solver_impl.h"
#include "ceres/stringprintf.h"
#include "ceres/problem.h"

namespace ceres {

Solver::~Solver() {}

// TODO(sameeragarwal): The timing code here should use a sub-second
// timer.
void Solver::Solve(const Solver::Options& options,
                   Problem* problem,
                   Solver::Summary* summary) {
  time_t start_time_seconds = time(NULL);
  internal::SolverImpl::Solve(options, problem, summary);
  summary->total_time_in_seconds =  time(NULL) - start_time_seconds;
  summary->preprocessor_time_in_seconds =
      summary->total_time_in_seconds - summary->minimizer_time_in_seconds;
}

void Solve(const Solver::Options& options,
           Problem* problem,
           Solver::Summary* summary) {
  time_t start_time_seconds = time(NULL);
  internal::SolverImpl::Solve(options, problem, summary);
  summary->total_time_in_seconds =  time(NULL) - start_time_seconds;
  summary->preprocessor_time_in_seconds =
      summary->total_time_in_seconds - summary->minimizer_time_in_seconds;
}

Solver::Summary::Summary()
    // Invalid values for most fields, to ensure that we are not
    // accidentally reporting default values.
    : termination_type(DID_NOT_RUN),
      initial_cost(-1.0),
      final_cost(-1.0),
      fixed_cost(-1.0),
      num_successful_steps(-1),
      num_unsuccessful_steps(-1),
      preprocessor_time_in_seconds(-1.0),
      minimizer_time_in_seconds(-1.0),
      total_time_in_seconds(-1.0),
      num_parameter_blocks(-1),
      num_parameters(-1),
      num_residual_blocks(-1),
      num_residuals(-1),
      num_parameter_blocks_reduced(-1),
      num_parameters_reduced(-1),
      num_residual_blocks_reduced(-1),
      num_residuals_reduced(-1),
      num_eliminate_blocks_given(-1),
      num_eliminate_blocks_used(-1),
      num_threads_given(-1),
      num_threads_used(-1),
      num_linear_solver_threads_given(-1),
      num_linear_solver_threads_used(-1),
      linear_solver_type_given(SPARSE_NORMAL_CHOLESKY),
      linear_solver_type_used(SPARSE_NORMAL_CHOLESKY),
      preconditioner_type(IDENTITY),
      ordering_type(NATURAL) {
}

string Solver::Summary::BriefReport() const {
  string report = "Ceres Solver Report: ";
  if (termination_type == DID_NOT_RUN) {
    CHECK(!error.empty())
          << "Solver terminated with DID_NOT_RUN but the solver did not "
          << "return a reason. This is a Ceres error. Please report this "
          << "to the Ceres team";
    return report + "Termination: DID_NOT_RUN, because " + error;
  }

  internal::StringAppendF(&report, "Iterations: %d",
                          num_successful_steps + num_unsuccessful_steps);
  internal::StringAppendF(&report, ", Initial cost: %e", initial_cost);

  // If the solver failed or was aborted, then the final_cost has no
  // meaning.
  if (termination_type != NUMERICAL_FAILURE &&
      termination_type != USER_ABORT) {
    internal::StringAppendF(&report, ", Final cost: %e", final_cost);
  }

  internal::StringAppendF(&report, ", Termination: %s.",
                          SolverTerminationTypeToString(termination_type));
  return report;
};

string Solver::Summary::FullReport() const {
  string report =
      "\n"
      "Ceres Solver Report\n"
      "-------------------\n";

  if (termination_type == DID_NOT_RUN) {
    internal::StringAppendF(&report, "                      Original\n");
    internal::StringAppendF(&report, "Parameter blocks    % 10d\n",
                            num_parameter_blocks);
    internal::StringAppendF(&report, "Parameters          % 10d\n",
                            num_parameters);
    internal::StringAppendF(&report, "Residual blocks     % 10d\n",
                            num_residual_blocks);
    internal::StringAppendF(&report, "Residual            % 10d\n\n",
                            num_residuals);
  } else {
    internal::StringAppendF(&report, "%45s    %21s\n", "Original", "Reduced");
    internal::StringAppendF(&report, "Parameter blocks    % 25d% 25d\n",
                            num_parameter_blocks, num_parameter_blocks_reduced);
    internal::StringAppendF(&report, "Parameters          % 25d% 25d\n",
                            num_parameters, num_parameters_reduced);
    internal::StringAppendF(&report, "Residual blocks     % 25d% 25d\n",
                            num_residual_blocks, num_residual_blocks_reduced);
    internal::StringAppendF(&report, "Residual            % 25d% 25d\n\n",
                          num_residuals, num_residuals_reduced);
  }

  internal::StringAppendF(&report,   "%45s    %21s\n", "Given",  "Used");
  internal::StringAppendF(&report, "Linear solver       %25s%25s\n",
                          LinearSolverTypeToString(linear_solver_type_given),
                          LinearSolverTypeToString(linear_solver_type_used));

  if (linear_solver_type_given == CGNR ||
      linear_solver_type_given == ITERATIVE_SCHUR) {
    internal::StringAppendF(&report, "Preconditioner      %25s%25s\n",
                            PreconditionerTypeToString(preconditioner_type),
                            PreconditionerTypeToString(preconditioner_type));
  } else {
    internal::StringAppendF(&report, "Preconditioner      %25s%25s\n",
                            "N/A", "N/A");
  }

  internal::StringAppendF(&report, "Ordering            %25s%25s\n",
                          OrderingTypeToString(ordering_type),
                          OrderingTypeToString(ordering_type));

  if (IsSchurType(linear_solver_type_given)) {
    if (ordering_type == SCHUR) {
      internal::StringAppendF(&report, "num_eliminate_blocks%25s% 25d\n",
                              "N/A",
                              num_eliminate_blocks_used);
    } else {
      internal::StringAppendF(&report, "num_eliminate_blocks% 25d% 25d\n",
                              num_eliminate_blocks_given,
                              num_eliminate_blocks_used);
    }
  }

  internal::StringAppendF(&report, "Threads:            % 25d% 25d\n",
                          num_threads_given, num_threads_used);
  internal::StringAppendF(&report, "Linear Solver Threads:% 23d% 25d\n",
                          num_linear_solver_threads_given,
                          num_linear_solver_threads_used);

  if (termination_type == DID_NOT_RUN) {
    CHECK(!error.empty())
        << "Solver terminated with DID_NOT_RUN but the solver did not "
        << "return a reason. This is a Ceres error. Please report this "
        << "to the Ceres team";
    internal::StringAppendF(&report, "Termination:           %20s\n",
                            "DID_NOT_RUN");
    internal::StringAppendF(&report, "Reason: %s\n", error.c_str());
    return report;
  }

  internal::StringAppendF(&report, "\nCost:\n");
  internal::StringAppendF(&report, "Initial        % 30e\n", initial_cost);
  if (termination_type != NUMERICAL_FAILURE && termination_type != USER_ABORT) {
    internal::StringAppendF(&report, "Final          % 30e\n", final_cost);
    internal::StringAppendF(&report, "Change         % 30e\n",
                            initial_cost - final_cost);
  }

  internal::StringAppendF(&report, "\nNumber of iterations:\n");
  internal::StringAppendF(&report, "Successful               % 20d\n",
                          num_successful_steps);
  internal::StringAppendF(&report, "Unsuccessful             % 20d\n",
                          num_unsuccessful_steps);
  internal::StringAppendF(&report, "Total                    % 20d\n",
                          num_successful_steps + num_unsuccessful_steps);
  internal::StringAppendF(&report, "\nTime (in seconds):\n");
  internal::StringAppendF(&report, "Preprocessor        % 25e\n",
                          preprocessor_time_in_seconds);
  internal::StringAppendF(&report, "Minimizer           % 25e\n",
                          minimizer_time_in_seconds);
  internal::StringAppendF(&report, "Total               % 25e\n",
                          total_time_in_seconds);

  internal::StringAppendF(&report, "Termination:        %25s\n",
                SolverTerminationTypeToString(termination_type));
  return report;
};

}  // namespace ceres
<commit_msg>Residuals instead of Residual in FullReport<commit_after>// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2010, 2011, 2012 Google Inc. All rights reserved.
// http://code.google.com/p/ceres-solver/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
//   used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: keir@google.com (Keir Mierle)
//         sameeragarwal@google.com (Sameer Agarwal)

#include "ceres/solver.h"

#include <vector>
#include "ceres/levenberg_marquardt.h"
#include "ceres/program.h"
#include "ceres/solver_impl.h"
#include "ceres/stringprintf.h"
#include "ceres/problem.h"

namespace ceres {

Solver::~Solver() {}

// TODO(sameeragarwal): The timing code here should use a sub-second
// timer.
void Solver::Solve(const Solver::Options& options,
                   Problem* problem,
                   Solver::Summary* summary) {
  time_t start_time_seconds = time(NULL);
  internal::SolverImpl::Solve(options, problem, summary);
  summary->total_time_in_seconds =  time(NULL) - start_time_seconds;
  summary->preprocessor_time_in_seconds =
      summary->total_time_in_seconds - summary->minimizer_time_in_seconds;
}

void Solve(const Solver::Options& options,
           Problem* problem,
           Solver::Summary* summary) {
  time_t start_time_seconds = time(NULL);
  internal::SolverImpl::Solve(options, problem, summary);
  summary->total_time_in_seconds =  time(NULL) - start_time_seconds;
  summary->preprocessor_time_in_seconds =
      summary->total_time_in_seconds - summary->minimizer_time_in_seconds;
}

Solver::Summary::Summary()
    // Invalid values for most fields, to ensure that we are not
    // accidentally reporting default values.
    : termination_type(DID_NOT_RUN),
      initial_cost(-1.0),
      final_cost(-1.0),
      fixed_cost(-1.0),
      num_successful_steps(-1),
      num_unsuccessful_steps(-1),
      preprocessor_time_in_seconds(-1.0),
      minimizer_time_in_seconds(-1.0),
      total_time_in_seconds(-1.0),
      num_parameter_blocks(-1),
      num_parameters(-1),
      num_residual_blocks(-1),
      num_residuals(-1),
      num_parameter_blocks_reduced(-1),
      num_parameters_reduced(-1),
      num_residual_blocks_reduced(-1),
      num_residuals_reduced(-1),
      num_eliminate_blocks_given(-1),
      num_eliminate_blocks_used(-1),
      num_threads_given(-1),
      num_threads_used(-1),
      num_linear_solver_threads_given(-1),
      num_linear_solver_threads_used(-1),
      linear_solver_type_given(SPARSE_NORMAL_CHOLESKY),
      linear_solver_type_used(SPARSE_NORMAL_CHOLESKY),
      preconditioner_type(IDENTITY),
      ordering_type(NATURAL) {
}

string Solver::Summary::BriefReport() const {
  string report = "Ceres Solver Report: ";
  if (termination_type == DID_NOT_RUN) {
    CHECK(!error.empty())
          << "Solver terminated with DID_NOT_RUN but the solver did not "
          << "return a reason. This is a Ceres error. Please report this "
          << "to the Ceres team";
    return report + "Termination: DID_NOT_RUN, because " + error;
  }

  internal::StringAppendF(&report, "Iterations: %d",
                          num_successful_steps + num_unsuccessful_steps);
  internal::StringAppendF(&report, ", Initial cost: %e", initial_cost);

  // If the solver failed or was aborted, then the final_cost has no
  // meaning.
  if (termination_type != NUMERICAL_FAILURE &&
      termination_type != USER_ABORT) {
    internal::StringAppendF(&report, ", Final cost: %e", final_cost);
  }

  internal::StringAppendF(&report, ", Termination: %s.",
                          SolverTerminationTypeToString(termination_type));
  return report;
};

string Solver::Summary::FullReport() const {
  string report =
      "\n"
      "Ceres Solver Report\n"
      "-------------------\n";

  if (termination_type == DID_NOT_RUN) {
    internal::StringAppendF(&report, "                      Original\n");
    internal::StringAppendF(&report, "Parameter blocks    % 10d\n",
                            num_parameter_blocks);
    internal::StringAppendF(&report, "Parameters          % 10d\n",
                            num_parameters);
    internal::StringAppendF(&report, "Residual blocks     % 10d\n",
                            num_residual_blocks);
    internal::StringAppendF(&report, "Residuals           % 10d\n\n",
                            num_residuals);
  } else {
    internal::StringAppendF(&report, "%45s    %21s\n", "Original", "Reduced");
    internal::StringAppendF(&report, "Parameter blocks    % 25d% 25d\n",
                            num_parameter_blocks, num_parameter_blocks_reduced);
    internal::StringAppendF(&report, "Parameters          % 25d% 25d\n",
                            num_parameters, num_parameters_reduced);
    internal::StringAppendF(&report, "Residual blocks     % 25d% 25d\n",
                            num_residual_blocks, num_residual_blocks_reduced);
    internal::StringAppendF(&report, "Residual            % 25d% 25d\n\n",
                          num_residuals, num_residuals_reduced);
  }

  internal::StringAppendF(&report,   "%45s    %21s\n", "Given",  "Used");
  internal::StringAppendF(&report, "Linear solver       %25s%25s\n",
                          LinearSolverTypeToString(linear_solver_type_given),
                          LinearSolverTypeToString(linear_solver_type_used));

  if (linear_solver_type_given == CGNR ||
      linear_solver_type_given == ITERATIVE_SCHUR) {
    internal::StringAppendF(&report, "Preconditioner      %25s%25s\n",
                            PreconditionerTypeToString(preconditioner_type),
                            PreconditionerTypeToString(preconditioner_type));
  } else {
    internal::StringAppendF(&report, "Preconditioner      %25s%25s\n",
                            "N/A", "N/A");
  }

  internal::StringAppendF(&report, "Ordering            %25s%25s\n",
                          OrderingTypeToString(ordering_type),
                          OrderingTypeToString(ordering_type));

  if (IsSchurType(linear_solver_type_given)) {
    if (ordering_type == SCHUR) {
      internal::StringAppendF(&report, "num_eliminate_blocks%25s% 25d\n",
                              "N/A",
                              num_eliminate_blocks_used);
    } else {
      internal::StringAppendF(&report, "num_eliminate_blocks% 25d% 25d\n",
                              num_eliminate_blocks_given,
                              num_eliminate_blocks_used);
    }
  }

  internal::StringAppendF(&report, "Threads:            % 25d% 25d\n",
                          num_threads_given, num_threads_used);
  internal::StringAppendF(&report, "Linear Solver Threads:% 23d% 25d\n",
                          num_linear_solver_threads_given,
                          num_linear_solver_threads_used);

  if (termination_type == DID_NOT_RUN) {
    CHECK(!error.empty())
        << "Solver terminated with DID_NOT_RUN but the solver did not "
        << "return a reason. This is a Ceres error. Please report this "
        << "to the Ceres team";
    internal::StringAppendF(&report, "Termination:           %20s\n",
                            "DID_NOT_RUN");
    internal::StringAppendF(&report, "Reason: %s\n", error.c_str());
    return report;
  }

  internal::StringAppendF(&report, "\nCost:\n");
  internal::StringAppendF(&report, "Initial        % 30e\n", initial_cost);
  if (termination_type != NUMERICAL_FAILURE && termination_type != USER_ABORT) {
    internal::StringAppendF(&report, "Final          % 30e\n", final_cost);
    internal::StringAppendF(&report, "Change         % 30e\n",
                            initial_cost - final_cost);
  }

  internal::StringAppendF(&report, "\nNumber of iterations:\n");
  internal::StringAppendF(&report, "Successful               % 20d\n",
                          num_successful_steps);
  internal::StringAppendF(&report, "Unsuccessful             % 20d\n",
                          num_unsuccessful_steps);
  internal::StringAppendF(&report, "Total                    % 20d\n",
                          num_successful_steps + num_unsuccessful_steps);
  internal::StringAppendF(&report, "\nTime (in seconds):\n");
  internal::StringAppendF(&report, "Preprocessor        % 25e\n",
                          preprocessor_time_in_seconds);
  internal::StringAppendF(&report, "Minimizer           % 25e\n",
                          minimizer_time_in_seconds);
  internal::StringAppendF(&report, "Total               % 25e\n",
                          total_time_in_seconds);

  internal::StringAppendF(&report, "Termination:        %25s\n",
                SolverTerminationTypeToString(termination_type));
  return report;
};

}  // namespace ceres
<|endoftext|>


<commit_before><commit_msg>Updated decodehdr.cpp<commit_after><|endoftext|>


<commit_before>#include "openlr/score_candidate_points_getter.hpp"

#include "openlr/helpers.hpp"

#include "routing/road_graph.hpp"
#include "routing/routing_helpers.hpp"

#include "storage/country_info_getter.hpp"

#include "indexer/feature.hpp"
#include "indexer/scales.hpp"

#include "geometry/mercator.hpp"
#include "geometry/point_with_altitude.hpp"

#include "base/assert.hpp"
#include "base/stl_helpers.hpp"

#include <algorithm>
#include <set>
#include <utility>

using namespace routing;

namespace
{
// Ends of segments and intermediate points of segments are considered only within this radius.
double const kRadius = 30.0;
} //  namespace

namespace openlr
{
void ScoreCandidatePointsGetter::GetJunctionPointCandidates(m2::PointD const & p, bool isLastPoint,
                                                            ScoreEdgeVec & edgeCandidates)
{
  ScorePointVec pointCandidates;
  auto const selectCandidates = [&p, &pointCandidates, this](FeatureType & ft) {
    ft.ParseGeometry(FeatureType::BEST_GEOMETRY);
    ft.ForEachPoint(
        [&p, &pointCandidates, this](m2::PointD const & candidate) {
          if (mercator::DistanceOnEarth(p, candidate) < kRadius)
            pointCandidates.emplace_back(GetScoreByDistance(p, candidate), candidate);
        },
        scales::GetUpperScale());
  };

  m_dataSource.ForEachInRect(selectCandidates, mercator::RectByCenterXYAndSizeInMeters(p, kRadius),
                             scales::GetUpperScale());

  base::SortUnique(pointCandidates);
  std::reverse(pointCandidates.begin(), pointCandidates.end());

  pointCandidates.resize(std::min(m_maxJunctionCandidates, pointCandidates.size()));

  for (auto const & pc : pointCandidates)
  {
    Graph::EdgeVector edges;
    if (!isLastPoint)
      m_graph.GetOutgoingEdges(geometry::PointWithAltitude(pc.m_point, 0 /* altitude */), edges);
    else
      m_graph.GetIngoingEdges(geometry::PointWithAltitude(pc.m_point, 0 /* altitude */), edges);

    for (auto const & e : edges)
      edgeCandidates.emplace_back(pc.m_score, e);
  }
}

void ScoreCandidatePointsGetter::EnrichWithProjectionPoints(m2::PointD const & p,
                                                            ScoreEdgeVec & edgeCandidates)
{
  m_graph.ResetFakes();

  std::vector<std::pair<Graph::Edge, geometry::PointWithAltitude>> vicinities;
  m_graph.FindClosestEdges(p, static_cast<uint32_t>(m_maxProjectionCandidates), vicinities);
  for (auto const & v : vicinities)
  {
    auto const & edge = v.first;
    auto const & proj = v.second;

    CHECK(edge.HasRealPart(), ());
    CHECK(!edge.IsFake(), ());

    if (mercator::DistanceOnEarth(p, proj.GetPoint()) >= kRadius)
      continue;

    edgeCandidates.emplace_back(GetScoreByDistance(p, proj.GetPoint()), edge);
  }
}

bool ScoreCandidatePointsGetter::IsJunction(m2::PointD const & p)
{
  Graph::EdgeVector outgoing;
  m_graph.GetRegularOutgoingEdges(geometry::PointWithAltitude(p, 0 /* altitude */), outgoing);

  Graph::EdgeVector ingoing;
  m_graph.GetRegularIngoingEdges(geometry::PointWithAltitude(p, 0 /* altitude */), ingoing);

  // Note. At mwm borders the size of |ids| may be bigger than two in case of straight
  // road because of road feature duplication at borders.
  std::set<std::pair<uint32_t, uint32_t>> ids;
  for (auto const & e : outgoing)
    ids.insert(std::make_pair(e.GetFeatureId().m_index, e.GetSegId()));

  for (auto const & e : ingoing)
    ids.insert(std::make_pair(e.GetFeatureId().m_index, e.GetSegId()));

  // Size of |ids| is number of different pairs of (feature id, segment id) starting from
  // |p| plus going to |p|. The size 0, 1 or 2 is considered |p| is not a junction of roads.
  // If the size is 3 or more it means |p| is an intersection of 3 or more roads.
  return ids.size() >= 3;
}

Score ScoreCandidatePointsGetter::GetScoreByDistance(m2::PointD const & point,
                                                     m2::PointD const & candidate)
{
  // Maximum possible score for the distance between an openlr segment ends and an osm segments.
  Score constexpr kMaxScoreForDist = 70;
  // If the distance between an openlr segments end and an osm segments end is less or equal
  // |kMaxScoreDistM| the point gets |kMaxScoreForDist| score.
  double constexpr kMaxScoreDistM = 5.0;
  // According to the standard openlr edge should be started from a junction. Despite the fact
  // that openlr and osm are based on different graphs, the score of junction should be increased.
  double const junctionFactor = IsJunction(candidate) ? 1.1 : 1.0;

  double const distM = mercator::DistanceOnEarth(point, candidate);
  double const score =
      distM <= kMaxScoreDistM
          ? kMaxScoreForDist * junctionFactor
          : static_cast<double>(kMaxScoreForDist) * junctionFactor / (1.0 + distM - kMaxScoreDistM);

  CHECK_GREATER_OR_EQUAL(score, 0.0, ());
  CHECK_LESS_OR_EQUAL(score, static_cast<double>(kMaxScoreForDist) * junctionFactor, ());
  return static_cast<Score>(score);
}
}  // namespace openlr
<commit_msg>[openlr] Using only roads as candidates.<commit_after>#include "openlr/score_candidate_points_getter.hpp"

#include "openlr/helpers.hpp"

#include "routing/road_graph.hpp"
#include "routing/routing_helpers.hpp"

#include "storage/country_info_getter.hpp"

#include "indexer/feature.hpp"
#include "indexer/feature_data.hpp"
#include "indexer/feature_decl.hpp"
#include "indexer/scales.hpp"

#include "geometry/mercator.hpp"
#include "geometry/point_with_altitude.hpp"

#include "base/assert.hpp"
#include "base/stl_helpers.hpp"

#include <algorithm>
#include <set>
#include <utility>

using namespace routing;

namespace
{
// Ends of segments and intermediate points of segments are considered only within this radius.
double const kRadius = 30.0;
} //  namespace

namespace openlr
{
void ScoreCandidatePointsGetter::GetJunctionPointCandidates(m2::PointD const & p, bool isLastPoint,
                                                            ScoreEdgeVec & edgeCandidates)
{
  ScorePointVec pointCandidates;
  auto const selectCandidates = [&p, &pointCandidates, this](FeatureType & ft) {
    ft.ParseGeometry(FeatureType::BEST_GEOMETRY);
    if (ft.GetGeomType() != feature::GeomType::Line || !routing::IsRoad(feature::TypesHolder(ft)))
      return;

    ft.ForEachPoint(
        [&p, &pointCandidates, this](m2::PointD const & candidate) {
          if (mercator::DistanceOnEarth(p, candidate) < kRadius)
            pointCandidates.emplace_back(GetScoreByDistance(p, candidate), candidate);
        },
        scales::GetUpperScale());
  };

  m_dataSource.ForEachInRect(selectCandidates, mercator::RectByCenterXYAndSizeInMeters(p, kRadius),
                             scales::GetUpperScale());

  base::SortUnique(pointCandidates);
  std::reverse(pointCandidates.begin(), pointCandidates.end());

  pointCandidates.resize(std::min(m_maxJunctionCandidates, pointCandidates.size()));

  for (auto const & pc : pointCandidates)
  {
    Graph::EdgeVector edges;
    if (!isLastPoint)
      m_graph.GetOutgoingEdges(geometry::PointWithAltitude(pc.m_point, 0 /* altitude */), edges);
    else
      m_graph.GetIngoingEdges(geometry::PointWithAltitude(pc.m_point, 0 /* altitude */), edges);

    for (auto const & e : edges)
      edgeCandidates.emplace_back(pc.m_score, e);
  }
}

void ScoreCandidatePointsGetter::EnrichWithProjectionPoints(m2::PointD const & p,
                                                            ScoreEdgeVec & edgeCandidates)
{
  m_graph.ResetFakes();

  std::vector<std::pair<Graph::Edge, geometry::PointWithAltitude>> vicinities;
  m_graph.FindClosestEdges(p, static_cast<uint32_t>(m_maxProjectionCandidates), vicinities);
  for (auto const & v : vicinities)
  {
    auto const & edge = v.first;
    auto const & proj = v.second;

    CHECK(edge.HasRealPart(), ());
    CHECK(!edge.IsFake(), ());

    if (mercator::DistanceOnEarth(p, proj.GetPoint()) >= kRadius)
      continue;

    edgeCandidates.emplace_back(GetScoreByDistance(p, proj.GetPoint()), edge);
  }
}

bool ScoreCandidatePointsGetter::IsJunction(m2::PointD const & p)
{
  Graph::EdgeVector outgoing;
  m_graph.GetRegularOutgoingEdges(geometry::PointWithAltitude(p, 0 /* altitude */), outgoing);

  Graph::EdgeVector ingoing;
  m_graph.GetRegularIngoingEdges(geometry::PointWithAltitude(p, 0 /* altitude */), ingoing);

  // Note. At mwm borders the size of |ids| may be bigger than two in case of straight
  // road because of road feature duplication at borders.
  std::set<std::pair<uint32_t, uint32_t>> ids;
  for (auto const & e : outgoing)
    ids.insert(std::make_pair(e.GetFeatureId().m_index, e.GetSegId()));

  for (auto const & e : ingoing)
    ids.insert(std::make_pair(e.GetFeatureId().m_index, e.GetSegId()));

  // Size of |ids| is number of different pairs of (feature id, segment id) starting from
  // |p| plus going to |p|. The size 0, 1 or 2 is considered |p| is not a junction of roads.
  // If the size is 3 or more it means |p| is an intersection of 3 or more roads.
  return ids.size() >= 3;
}

Score ScoreCandidatePointsGetter::GetScoreByDistance(m2::PointD const & point,
                                                     m2::PointD const & candidate)
{
  // Maximum possible score for the distance between an openlr segment ends and an osm segments.
  Score constexpr kMaxScoreForDist = 70;
  // If the distance between an openlr segments end and an osm segments end is less or equal
  // |kMaxScoreDistM| the point gets |kMaxScoreForDist| score.
  double constexpr kMaxScoreDistM = 5.0;
  // According to the standard openlr edge should be started from a junction. Despite the fact
  // that openlr and osm are based on different graphs, the score of junction should be increased.
  double const junctionFactor = IsJunction(candidate) ? 1.1 : 1.0;

  double const distM = mercator::DistanceOnEarth(point, candidate);
  double const score =
      distM <= kMaxScoreDistM
          ? kMaxScoreForDist * junctionFactor
          : static_cast<double>(kMaxScoreForDist) * junctionFactor / (1.0 + distM - kMaxScoreDistM);

  CHECK_GREATER_OR_EQUAL(score, 0.0, ());
  CHECK_LESS_OR_EQUAL(score, static_cast<double>(kMaxScoreForDist) * junctionFactor, ());
  return static_cast<Score>(score);
}
}  // namespace openlr
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

#include <process/process.hpp>
#include <process/future.hpp>

#include "common/try.hpp"
#include "common/resources.hpp"
#include "monitoring/resource_collector.hpp"
#include "slave/resource_monitor.hpp"

/* Tests for resource monitor
 * - just one test to make sure that it pushes through state correctly
 */

using namespace mesos;
using namespace mesos::internal;
using namespace mesos::internal::monitoring;
using namespace mesos::internal::slave;

using process::Clock;
using process::Future;
using std::string;
using testing::Expectation;
using testing::Return;

class MockCollector : public ResourceCollector
{
public:
  // TODO(sam): Fix/confirm change.
  MOCK_METHOD0(getMemoryUsage, Try<double>());
  MOCK_METHOD0(getCpuUsage, Try<Rate>());
  MOCK_METHOD0(collectUsage, void());
};

TEST(ResourceMonitorTest, MonitorsCorrectly)
{
  MockCollector* mock_collector = new MockCollector();

  // TODO(sam) put call requirements here!

  // Make sure collectUsage is called before retrieve mem/cpu usage.
  Expectation collect_usage = EXPECT_CALL(*mock_collector, collectUsage())
    .Times(1);

  // Set the memory usage the collector will return.
  double memoryUsage = 123456789.0;
  EXPECT_CALL(*mock_collector, getMemoryUsage())
    .After(collect_usage)
    .WillOnce(Return(Try<double>::some(memoryUsage)));

  // Set the cpu usage the collector will return.
  double duration = 13579.0, difference = 2468.0;
  EXPECT_CALL(*mock_collector, getCpuUsage())
    .After(collect_usage)
    .WillOnce(Return(Try<Rate>::some(Rate(duration, difference))));

  ResourceMonitor mocked_monitor(mock_collector);

  // Create fake IDs.
  FrameworkID framework_id;
  framework_id.set_value("framework_id1");
  ExecutorID executor_id;
  executor_id.set_value("executor_id1");

  // Collect the usage.
  Future<UsageMessage> usage_msg_future = mocked_monitor.collectUsage(
      framework_id, executor_id);

  // Setting a timeout in case it gets stuck.
  usage_msg_future.await(5);

  ASSERT_TRUE(usage_msg_future.isReady());

  UsageMessage usage_msg = usage_msg_future.get();

  // Make sure the returned UsageMessage matches the expected values.
  EXPECT_EQ(duration, usage_msg.duration());
  EXPECT_FALSE(usage_msg.timestamp() > Clock::now()); // To fix roundoff errors.

  // TODO(adegtiar or sam): make this the correct call.
  //EXPECT_EQ(framework_id, usage_msg.framework_id());
  //EXPECT_EQ(executor_id, usage_msg.executor_id());

  Resources usage = usage_msg.resources();
  EXPECT_EQ(memoryUsage, usage.get("mem_usage", Value::Scalar()).value());
  EXPECT_EQ(difference, usage.get("cpu_usage", Value::Scalar()).value());
}
<commit_msg>Updating a comment<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

#include <process/process.hpp>
#include <process/future.hpp>

#include "common/try.hpp"
#include "common/resources.hpp"
#include "monitoring/resource_collector.hpp"
#include "slave/resource_monitor.hpp"

/* Tests for resource monitor
 * - just one test to make sure that it pushes through state correctly
 */

using namespace mesos;
using namespace mesos::internal;
using namespace mesos::internal::monitoring;
using namespace mesos::internal::slave;

using process::Clock;
using process::Future;
using std::string;
using testing::Expectation;
using testing::Return;

class MockCollector : public ResourceCollector
{
public:
  // TODO(sam): Fix/confirm change.
  MOCK_METHOD0(getMemoryUsage, Try<double>());
  MOCK_METHOD0(getCpuUsage, Try<Rate>());
  MOCK_METHOD0(collectUsage, void());
};

TEST(ResourceMonitorTest, MonitorsCorrectly)
{
  MockCollector* mock_collector = new MockCollector();

  // TODO(sam) put call requirements here!

  // Make sure collectUsage is called before retrieve mem/cpu usage.
  Expectation collect_usage = EXPECT_CALL(*mock_collector, collectUsage())
    .Times(1);

  // Set the memory usage the collector will return.
  double memoryUsage = 123456789.0;
  EXPECT_CALL(*mock_collector, getMemoryUsage())
    .After(collect_usage)
    .WillOnce(Return(Try<double>::some(memoryUsage)));

  // Set the cpu usage the collector will return.
  double duration = 13579.0, difference = 2468.0;
  EXPECT_CALL(*mock_collector, getCpuUsage())
    .After(collect_usage)
    .WillOnce(Return(Try<Rate>::some(Rate(duration, difference))));

  ResourceMonitor mocked_monitor(mock_collector);

  // Create fake IDs.
  FrameworkID framework_id;
  framework_id.set_value("framework_id1");
  ExecutorID executor_id;
  executor_id.set_value("executor_id1");

  // Collect the usage.
  Future<UsageMessage> usage_msg_future = mocked_monitor.collectUsage(
      framework_id, executor_id);

  // Setting a timeout in case it gets stuck.
  usage_msg_future.await(5);

  ASSERT_TRUE(usage_msg_future.isReady());

  UsageMessage usage_msg = usage_msg_future.get();

  // Make sure the returned UsageMessage matches the expected values.
  EXPECT_EQ(duration, usage_msg.duration());
  EXPECT_FALSE(usage_msg.timestamp() > Clock::now()); // To fix roundoff errors.

  // TODO(adegtiar or sam): fix this check.
  //EXPECT_EQ(framework_id, usage_msg.framework_id());
  //EXPECT_EQ(executor_id, usage_msg.executor_id());

  Resources usage = usage_msg.resources();
  EXPECT_EQ(memoryUsage, usage.get("mem_usage", Value::Scalar()).value());
  EXPECT_EQ(difference, usage.get("cpu_usage", Value::Scalar()).value());
}
<|endoftext|>


<commit_before>/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        node->next = node->next->next;
    }
};
<commit_msg>Delete Node in a Linked List<commit_after>/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void deleteNode(ListNode* node) {
        node->val = node->next->val;
        node->next = node->next->next;
    }
};

<|endoftext|>


<commit_before>#ifdef __WINDOWS_OS__

#include "NamedPipeTransport.hpp"

namespace Ethereum{namespace Connector{

bool NamedPipeConnector::connect(NamedPipeSocket &socket, const char *path)
{
    HANDLE pipe = CreateFile(path, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
    if(!pipe)
    {
        return false;
    }
    socket.assign(pipe);
    return true;
}

}}

#endif
<commit_msg>fixed named pipe connect error detection<commit_after>#ifdef __WINDOWS_OS__

#include "NamedPipeTransport.hpp"

namespace Ethereum{namespace Connector{

bool NamedPipeConnector::connect(NamedPipeSocket &socket, const char *path)
{
    HANDLE pipe = CreateFile(path, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
    if(pipe==INVALID_HANDLE_VALUE)
    {
        return false;
    }
    socket.assign(pipe);
    return true;
}

}}

#endif
<|endoftext|>


<commit_before>class Solution {
public:
    int countSegments(string s) {
        if(s=="") return 0;
        int i=0,ans=0;
        bool prev;
        if(s[i]==' '){
            prev=true;
        }else{
            prev=false;
            ans=1;
        }
        while(i<s.length()){
            if(s[i]!=' ' && prev==true){
                ans++;
                prev=false;
            }else if(s[i]==' '){
                prev=true;
            }
            i++;
        }
        return ans;
    }
};
<commit_msg>Number of Segments in a String<commit_after>class Solution {
public:
    int countSegments(string s) {
        if(s=="") return 0;
        int i=0,ans=0;
        bool prev;
        if(s[i]==' '){
            prev=true;
        }else{
            prev=false;
            ans=1;
        }
        while(i<s.length()){
            if(s[i]!=' ' && prev==true){
                ans++;
                prev=false;
            }else if(s[i]==' '){
                prev=true;
            }
            i++;
        }
        return ans;
    }
};
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 1992-$THISYEAR$ $TROLLTECH$. All rights reserved.
**
** This file is part of the $MODULE$ of the Qt Toolkit.
**
** $TROLLTECH_DUAL_LICENSE$
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#include "qml.h"
#include "qmlviewer.h"
#include <QWidget>
#include <QDir>
#include "qfxtestengine.h"
#include <QApplication>
#include <QTranslator>
#include <QDebug>

void usage()
{
    qWarning("Usage: qmlviewer [options] <filename>");
    qWarning(" ");
    qWarning(" options:");
    qWarning("  -v, -version ............................. display version");
    qWarning("  -frameless ............................... run with no window frame");
    qWarning("  -skin <qvfbskindir> ...................... run with a skin window frame");
    qWarning("  -recordfile <output> ..................... set video recording file");
    qWarning("                                              - ImageMagick 'convert' for GIF)");
    qWarning("                                              - png file for raw frames");
    qWarning("                                              - 'ffmpeg' for other formats");
    qWarning("  -recorddither ordered|threshold|floyd .... set GIF dither recording mode");
    qWarning("  -recordperiod <milliseconds> ............. set time between recording frames");
    qWarning("  -record arg .............................. add a recording process argument");
    qWarning("  -autorecord [from-]<tomilliseconds> ...... set recording to start and stop");
    qWarning("  -devicekeys .............................. use numeric keys (see F1)");
    qWarning("  -cache ................................... disk cache remote content");
    qWarning("  -recordtest <directory> .................. record an autotest");
    qWarning("  -runtest <directory> ..................... run a previously recorded test");
    qWarning("  -translation <translationfile> ........... set the language to run in");
    qWarning("  -L <directory> ........................... prepend to the library search path");
    qWarning(" ");
    qWarning(" Press F1 for interactive help");
    exit(1);
}

int main(int argc, char ** argv)
{
    //### default to using raster graphics backend for now
    int newargc = argc + 2;
    char **newargv;
    bool gsSpecified = false;
    for (int i = 0; i < argc; ++i) {
        if (!qstrcmp(argv[i], "-graphicssystem")) {
            gsSpecified = true;
            newargc -= 2;
            break;
        }
    }
    newargv = new char * [newargc];
    for (int i = 0; i < argc; ++i) {
        newargv[i] = argv[i];
    }
    if (!gsSpecified) {
        char system[] = "-graphicssystem";
        newargv[argc] = system;
        char raster[] = "raster";
        newargv[argc+1] = raster;
    }

    QApplication app(newargc, newargv);
    app.setApplicationName("viewer");

    bool frameless = false;
    QString fileName;
    int period = 0;
    int autorecord_from = 0;
    int autorecord_to = 0;
    QString dither = "none";
    QString recordfile;
    QStringList recordargs;
    QStringList libraries;
    QString skin;
    bool devkeys = false;
    bool cache = false;
    QFxTestEngine::TestMode testMode = QFxTestEngine::NoTest;
    QString testDir;
    QString translationFile;

    for (int i = 1; i < newargc; ++i) {
        QString arg = newargv[i];
        if (arg == "-frameless") {
            frameless = true;
        } else if (arg == "-skin") {
            skin = QString(newargv[++i]);
        } else if (arg == "-cache") {
            cache = true;
        } else if (arg == "-recordperiod") {
            period = QString(newargv[++i]).toInt();
        } else if (arg == "-recordfile") {
            recordfile = QString(newargv[++i]);
        } else if (arg == "-record") {
            recordargs << QString(newargv[++i]);
        } else if (arg == "-recorddither") {
            dither = QString(newargv[++i]);
        } else if (arg == "-autorecord") {
            QString range = QString(newargv[++i]);
            int dash = range.indexOf('-');
            if (dash > 0)
                autorecord_from = range.left(dash).toInt();
            autorecord_to = range.mid(dash+1).toInt();
        } else if (arg == "-devicekeys") {
            devkeys = true;
        } else if (arg == "-recordtest") {
            testMode = QFxTestEngine::RecordTest;
            if(i + 1 >= newargc)
                usage();
            testDir = newargv[i + 1];
            ++i;
        } else if (arg == "-runtest") {
            testMode = QFxTestEngine::PlaybackTest;
            if(i + 1 >= newargc)
                usage();
            testDir = newargv[i + 1];
            ++i;
        } else if (arg == QLatin1String("-v") || arg == QLatin1String("-version")) {
            fprintf(stderr, "Qt Declarative UI Viewer version %s\n", QT_VERSION_STR);
            return 0;
        } else if (arg == "-translation") {
            if(i + 1 >= newargc)
                usage();
            translationFile = newargv[i + 1];
            ++i;
        } else if (arg == "-L") {
            libraries << QString(newargv[++i]);
        } else if (arg[0] != '-') {
            fileName = arg;
        } else if (1 || arg == "-help") {
            usage();
        }
    }

    QTranslator qmlTranslator;
    if (!translationFile.isEmpty()) {
        qmlTranslator.load(translationFile);
        app.installTranslator(&qmlTranslator);
    }

    QmlViewer viewer(testMode, testDir, 0, frameless ? Qt::FramelessWindowHint : Qt::Widget);
    foreach (QString lib, libraries)
        viewer.addLibraryPath(lib);
    viewer.setCacheEnabled(cache);
    viewer.setRecordFile(recordfile);
    if (period>0)
        viewer.setRecordPeriod(period);
    if (autorecord_to)
        viewer.setAutoRecord(autorecord_from,autorecord_to);
    if (!skin.isEmpty() && QDir(skin).exists())
        viewer.setSkin(skin);
    if (devkeys)
        viewer.setDeviceKeys(true);
    viewer.setRecordDither(dither);
    viewer.setRecordArgs(recordargs);
    if (!fileName.isEmpty())
        viewer.openQml(fileName);
    else
        viewer.open();
    viewer.show();

    return app.exec();
}

<commit_msg>Simplify setting default graphicssystem.<commit_after>/****************************************************************************
**
** Copyright (C) 1992-$THISYEAR$ $TROLLTECH$. All rights reserved.
**
** This file is part of the $MODULE$ of the Qt Toolkit.
**
** $TROLLTECH_DUAL_LICENSE$
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/

#include "qml.h"
#include "qmlviewer.h"
#include <QWidget>
#include <QDir>
#include "qfxtestengine.h"
#include <QApplication>
#include <QTranslator>
#include <QDebug>

void usage()
{
    qWarning("Usage: qmlviewer [options] <filename>");
    qWarning(" ");
    qWarning(" options:");
    qWarning("  -v, -version ............................. display version");
    qWarning("  -frameless ............................... run with no window frame");
    qWarning("  -skin <qvfbskindir> ...................... run with a skin window frame");
    qWarning("  -recordfile <output> ..................... set video recording file");
    qWarning("                                              - ImageMagick 'convert' for GIF)");
    qWarning("                                              - png file for raw frames");
    qWarning("                                              - 'ffmpeg' for other formats");
    qWarning("  -recorddither ordered|threshold|floyd .... set GIF dither recording mode");
    qWarning("  -recordperiod <milliseconds> ............. set time between recording frames");
    qWarning("  -record arg .............................. add a recording process argument");
    qWarning("  -autorecord [from-]<tomilliseconds> ...... set recording to start and stop");
    qWarning("  -devicekeys .............................. use numeric keys (see F1)");
    qWarning("  -cache ................................... disk cache remote content");
    qWarning("  -recordtest <directory> .................. record an autotest");
    qWarning("  -runtest <directory> ..................... run a previously recorded test");
    qWarning("  -translation <translationfile> ........... set the language to run in");
    qWarning("  -L <directory> ........................... prepend to the library search path");
    qWarning(" ");
    qWarning(" Press F1 for interactive help");
    exit(1);
}

int main(int argc, char ** argv)
{
    //### default to using raster graphics backend for now
    bool gsSpecified = false;
    for (int i = 0; i < argc; ++i) {
        QString arg = argv[i];
        if (arg == "-graphicssystem") {
            gsSpecified = true;
            break;
        }
    }
    if (!gsSpecified)
        QApplication::setGraphicsSystem("raster");

    QApplication app(argc, argv);
    app.setApplicationName("viewer");

    bool frameless = false;
    QString fileName;
    int period = 0;
    int autorecord_from = 0;
    int autorecord_to = 0;
    QString dither = "none";
    QString recordfile;
    QStringList recordargs;
    QStringList libraries;
    QString skin;
    bool devkeys = false;
    bool cache = false;
    QFxTestEngine::TestMode testMode = QFxTestEngine::NoTest;
    QString testDir;
    QString translationFile;

    for (int i = 1; i < argc; ++i) {
        QString arg = argv[i];
        if (arg == "-frameless") {
            frameless = true;
        } else if (arg == "-skin") {
            skin = QString(argv[++i]);
        } else if (arg == "-cache") {
            cache = true;
        } else if (arg == "-recordperiod") {
            period = QString(argv[++i]).toInt();
        } else if (arg == "-recordfile") {
            recordfile = QString(argv[++i]);
        } else if (arg == "-record") {
            recordargs << QString(argv[++i]);
        } else if (arg == "-recorddither") {
            dither = QString(argv[++i]);
        } else if (arg == "-autorecord") {
            QString range = QString(argv[++i]);
            int dash = range.indexOf('-');
            if (dash > 0)
                autorecord_from = range.left(dash).toInt();
            autorecord_to = range.mid(dash+1).toInt();
        } else if (arg == "-devicekeys") {
            devkeys = true;
        } else if (arg == "-recordtest") {
            testMode = QFxTestEngine::RecordTest;
            if(i + 1 >= argc)
                usage();
            testDir = argv[i + 1];
            ++i;
        } else if (arg == "-runtest") {
            testMode = QFxTestEngine::PlaybackTest;
            if(i + 1 >= argc)
                usage();
            testDir = argv[i + 1];
            ++i;
        } else if (arg == QLatin1String("-v") || arg == QLatin1String("-version")) {
            fprintf(stderr, "Qt Declarative UI Viewer version %s\n", QT_VERSION_STR);
            return 0;
        } else if (arg == "-translation") {
            if(i + 1 >= argc)
                usage();
            translationFile = argv[i + 1];
            ++i;
        } else if (arg == "-L") {
            libraries << QString(argv[++i]);
        } else if (arg[0] != '-') {
            fileName = arg;
        } else if (1 || arg == "-help") {
            usage();
        }
    }

    QTranslator qmlTranslator;
    if (!translationFile.isEmpty()) {
        qmlTranslator.load(translationFile);
        app.installTranslator(&qmlTranslator);
    }

    QmlViewer viewer(testMode, testDir, 0, frameless ? Qt::FramelessWindowHint : Qt::Widget);
    foreach (QString lib, libraries)
        viewer.addLibraryPath(lib);
    viewer.setCacheEnabled(cache);
    viewer.setRecordFile(recordfile);
    if (period>0)
        viewer.setRecordPeriod(period);
    if (autorecord_to)
        viewer.setAutoRecord(autorecord_from,autorecord_to);
    if (!skin.isEmpty() && QDir(skin).exists())
        viewer.setSkin(skin);
    if (devkeys)
        viewer.setDeviceKeys(true);
    viewer.setRecordDither(dither);
    viewer.setRecordArgs(recordargs);
    if (!fileName.isEmpty())
        viewer.openQml(fileName);
    else
        viewer.open();
    viewer.show();

    return app.exec();
}

<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperTopic.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */
#include <functional>
#include <boost/test/unit_test.hpp>
#include <libp2p/Host.h>
#include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;

BOOST_AUTO_TEST_SUITE(whisper)

BOOST_AUTO_TEST_CASE(topic)
{
	g_logVerbosity = 20;

	bool started = false;
	unsigned result = 0;
	std::thread listener([&]()
	{
		setThreadName("other");

		Host ph("Test", NetworkPreferences(50303, "", false, true));
		auto wh = ph.registerCapability(new WhisperHost());
		ph.start();

		started = true;

		/// Only interested in odd packets
		auto w = wh->installWatch(BuildTopicMask("odd"));

		for (int i = 0, last = 0; i < 200 && last < 81; ++i)
		{
			for (auto i: wh->checkWatch(w))
			{
				Message msg = wh->envelope(i).open();
				last = RLP(msg.payload()).toInt<unsigned>();
				cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
				result += last;
			}
			this_thread::sleep_for(chrono::milliseconds(50));
		}
	});

	while (!started)
		this_thread::sleep_for(chrono::milliseconds(50));

	Host ph("Test", NetworkPreferences(50300, "", false, true));
	auto wh = ph.registerCapability(new WhisperHost());
	this_thread::sleep_for(chrono::milliseconds(500));
	ph.start();
	this_thread::sleep_for(chrono::milliseconds(500));
	ph.connect("127.0.0.1", 50303);

	KeyPair us = KeyPair::create();
	for (int i = 0; i < 10; ++i)
	{
		wh->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"));
		this_thread::sleep_for(chrono::milliseconds(250));
	}

	listener.join();
	g_logVerbosity = 0;

	BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Reduce verbosity.<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file whisperTopic.cpp
 * @author Gav Wood <i@gavwood.com>
 * @date 2014
 */
#include <functional>
#include <boost/test/unit_test.hpp>
#include <libp2p/Host.h>
#include <libwhisper/WhisperPeer.h>
#include <libwhisper/WhisperHost.h>
using namespace std;
using namespace dev;
using namespace dev::p2p;
using namespace dev::shh;

BOOST_AUTO_TEST_SUITE(whisper)

BOOST_AUTO_TEST_CASE(topic)
{
	cnote << "Testing Whisper...";
	g_logVerbosity = 0;

	bool started = false;
	unsigned result = 0;
	std::thread listener([&]()
	{
		setThreadName("other");

		Host ph("Test", NetworkPreferences(50303, "", false, true));
		auto wh = ph.registerCapability(new WhisperHost());
		ph.start();

		started = true;

		/// Only interested in odd packets
		auto w = wh->installWatch(BuildTopicMask("odd"));

		for (int i = 0, last = 0; i < 200 && last < 81; ++i)
		{
			for (auto i: wh->checkWatch(w))
			{
				Message msg = wh->envelope(i).open();
				last = RLP(msg.payload()).toInt<unsigned>();
				cnote << "New message from:" << msg.from().abridged() << RLP(msg.payload()).toInt<unsigned>();
				result += last;
			}
			this_thread::sleep_for(chrono::milliseconds(50));
		}
	});

	while (!started)
		this_thread::sleep_for(chrono::milliseconds(50));

	Host ph("Test", NetworkPreferences(50300, "", false, true));
	auto wh = ph.registerCapability(new WhisperHost());
	this_thread::sleep_for(chrono::milliseconds(500));
	ph.start();
	this_thread::sleep_for(chrono::milliseconds(500));
	ph.connect("127.0.0.1", 50303);

	KeyPair us = KeyPair::create();
	for (int i = 0; i < 10; ++i)
	{
		wh->post(us.sec(), RLPStream().append(i * i).out(), BuildTopic(i)(i % 2 ? "odd" : "even"));
		this_thread::sleep_for(chrono::milliseconds(250));
	}

	listener.join();
	g_logVerbosity = 0;

	BOOST_REQUIRE_EQUAL(result, 1 + 9 + 25 + 49 + 81);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>