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

#include "net/http/disk_cache_based_quic_server_info.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/message_loop/message_loop.h"
#include "net/base/net_errors.h"
#include "net/http/mock_http_cache.h"
#include "net/quic/crypto/quic_server_info.h"
#include "net/quic/quic_session_key.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

// This is an empty transaction, needed to register the URL and the test mode.
const MockTransaction kHostInfoTransaction1 = {
  "quicserverinfo:https://www.google.com:443",
  "",
  base::Time(),
  "",
  net::LOAD_NORMAL,
  "",
  "",
  base::Time(),
  "",
  TEST_MODE_NORMAL,
  NULL,
  0
};

const MockTransaction kHostInfoTransaction2 = {
  "quicserverinfo:http://www.google.com:80",
  "",
  base::Time(),
  "",
  net::LOAD_NORMAL,
  "",
  "",
  base::Time(),
  "",
  TEST_MODE_NORMAL,
  NULL,
  0
};

// Tests that we can delete a DiskCacheBasedQuicServerInfo object in a
// completion callback for DiskCacheBasedQuicServerInfo::WaitForDataReady.
TEST(DiskCacheBasedQuicServerInfo, DeleteInCallback) {
  // Use the blocking mock backend factory to force asynchronous completion
  // of quic_server_info->WaitForDataReady(), so that the callback will run.
  MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
  MockHttpCache cache(factory);
  net::QuicSessionKey server_key("www.verisign.com", 443, true);
  scoped_ptr<net::QuicServerInfo> quic_server_info(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  net::TestCompletionCallback callback;
  int rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::ERR_IO_PENDING, rv);
  // Now complete the backend creation and let the callback run.
  factory->FinishCreation();
  EXPECT_EQ(net::OK, callback.GetResult(rv));
}

// Tests the basic logic of storing, retrieving and updating data.
TEST(DiskCacheBasedQuicServerInfo, Update) {
  MockHttpCache cache;
  AddMockTransaction(&kHostInfoTransaction1);
  net::TestCompletionCallback callback;

  net::QuicSessionKey server_key("www.google.com", 443, true);
  scoped_ptr<net::QuicServerInfo> quic_server_info(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  int rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  net::QuicServerInfo::State* state = quic_server_info->mutable_state();
  EXPECT_TRUE(state->certs.empty());
  const string server_config_a = "server_config_a";
  const string source_address_token_a = "source_address_token_a";
  const string server_config_sig_a = "server_config_sig_a";
  const string cert_a = "cert_a";
  const string cert_b = "cert_b";

  state->server_config = server_config_a;
  state->source_address_token = source_address_token_a;
  state->server_config_sig = server_config_sig_a;
  state->certs.push_back(cert_a);
  quic_server_info->Persist();

  // Wait until Persist() does the work.
  base::MessageLoop::current()->RunUntilIdle();

  // Open the stored QuicServerInfo.
  quic_server_info.reset(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  // And now update the data.
  state = quic_server_info->mutable_state();
  state->certs.push_back(cert_b);

  // Fail instead of DCHECKing double creates.
  cache.disk_cache()->set_double_create_check(false);
  quic_server_info->Persist();
  base::MessageLoop::current()->RunUntilIdle();

  // Verify that the state was updated.
  quic_server_info.reset(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  const net::QuicServerInfo::State& state1 = quic_server_info->state();
  EXPECT_TRUE(quic_server_info->IsDataReady());
  EXPECT_EQ(server_config_a, state1.server_config);
  EXPECT_EQ(source_address_token_a, state1.source_address_token);
  EXPECT_EQ(server_config_sig_a, state1.server_config_sig);
  EXPECT_EQ(2U, state1.certs.size());
  EXPECT_EQ(cert_a, state1.certs[0]);
  EXPECT_EQ(cert_b, state1.certs[1]);

  RemoveMockTransaction(&kHostInfoTransaction1);
}

// Test that demonstrates different info is returned when the ports differ.
TEST(DiskCacheBasedQuicServerInfo, UpdateDifferentPorts) {
  MockHttpCache cache;
  AddMockTransaction(&kHostInfoTransaction1);
  AddMockTransaction(&kHostInfoTransaction2);
  net::TestCompletionCallback callback;

  // Persist data for port 443.
  net::QuicSessionKey server_key1("www.google.com", 443, true);
  scoped_ptr<net::QuicServerInfo> quic_server_info1(
      new net::DiskCacheBasedQuicServerInfo(server_key1, cache.http_cache()));
  quic_server_info1->Start();
  int rv = quic_server_info1->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  net::QuicServerInfo::State* state1 = quic_server_info1->mutable_state();
  EXPECT_TRUE(state1->certs.empty());
  const string server_config_a = "server_config_a";
  const string source_address_token_a = "source_address_token_a";
  const string server_config_sig_a = "server_config_sig_a";
  const string cert_a = "cert_a";

  state1->server_config = server_config_a;
  state1->source_address_token = source_address_token_a;
  state1->server_config_sig = server_config_sig_a;
  state1->certs.push_back(cert_a);
  quic_server_info1->Persist();

  // Wait until Persist() does the work.
  base::MessageLoop::current()->RunUntilIdle();

  // Persist data for port 80.
  net::QuicSessionKey server_key2("www.google.com", 80, false);
  scoped_ptr<net::QuicServerInfo> quic_server_info2(
      new net::DiskCacheBasedQuicServerInfo(server_key2, cache.http_cache()));
  quic_server_info2->Start();
  rv = quic_server_info2->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  net::QuicServerInfo::State* state2 = quic_server_info2->mutable_state();
  EXPECT_TRUE(state2->certs.empty());
  const string server_config_b = "server_config_b";
  const string source_address_token_b = "source_address_token_b";
  const string server_config_sig_b = "server_config_sig_b";
  const string cert_b = "cert_b";

  state2->server_config = server_config_b;
  state2->source_address_token = source_address_token_b;
  state2->server_config_sig = server_config_sig_b;
  state2->certs.push_back(cert_b);
  quic_server_info2->Persist();

  // Wait until Persist() does the work.
  base::MessageLoop::current()->RunUntilIdle();

  // Verify the stored QuicServerInfo for port 443.
  scoped_ptr<net::QuicServerInfo> quic_server_info(
      new net::DiskCacheBasedQuicServerInfo(server_key1, cache.http_cache()));
  quic_server_info->Start();
  rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  const net::QuicServerInfo::State& state_a = quic_server_info->state();
  EXPECT_TRUE(quic_server_info->IsDataReady());
  EXPECT_EQ(server_config_a, state_a.server_config);
  EXPECT_EQ(source_address_token_a, state_a.source_address_token);
  EXPECT_EQ(server_config_sig_a, state_a.server_config_sig);
  EXPECT_EQ(1U, state_a.certs.size());
  EXPECT_EQ(cert_a, state_a.certs[0]);

  // Verify the stored QuicServerInfo for port 80.
  quic_server_info.reset(
      new net::DiskCacheBasedQuicServerInfo(server_key2, cache.http_cache()));
  quic_server_info->Start();
  rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  const net::QuicServerInfo::State& state_b = quic_server_info->state();
  EXPECT_TRUE(quic_server_info->IsDataReady());
  EXPECT_EQ(server_config_b, state_b.server_config);
  EXPECT_EQ(source_address_token_b, state_b.source_address_token);
  EXPECT_EQ(server_config_sig_b, state_b.server_config_sig);
  EXPECT_EQ(1U, state_b.certs.size());
  EXPECT_EQ(cert_b, state_b.certs[0]);

  RemoveMockTransaction(&kHostInfoTransaction2);
  RemoveMockTransaction(&kHostInfoTransaction1);
}

}  // namespace
<commit_msg>QUIC - Added unit test for IsDataReady to verify that it returns false if there is a pending write.  IsDataReady is called before we save the server config to disk cache.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/http/disk_cache_based_quic_server_info.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/compiler_specific.h"
#include "base/message_loop/message_loop.h"
#include "net/base/net_errors.h"
#include "net/http/mock_http_cache.h"
#include "net/quic/crypto/quic_server_info.h"
#include "net/quic/quic_session_key.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

// This is an empty transaction, needed to register the URL and the test mode.
const MockTransaction kHostInfoTransaction1 = {
  "quicserverinfo:https://www.google.com:443",
  "",
  base::Time(),
  "",
  net::LOAD_NORMAL,
  "",
  "",
  base::Time(),
  "",
  TEST_MODE_NORMAL,
  NULL,
  0
};

const MockTransaction kHostInfoTransaction2 = {
  "quicserverinfo:http://www.google.com:80",
  "",
  base::Time(),
  "",
  net::LOAD_NORMAL,
  "",
  "",
  base::Time(),
  "",
  TEST_MODE_NORMAL,
  NULL,
  0
};

// Tests that we can delete a DiskCacheBasedQuicServerInfo object in a
// completion callback for DiskCacheBasedQuicServerInfo::WaitForDataReady.
TEST(DiskCacheBasedQuicServerInfo, DeleteInCallback) {
  // Use the blocking mock backend factory to force asynchronous completion
  // of quic_server_info->WaitForDataReady(), so that the callback will run.
  MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
  MockHttpCache cache(factory);
  net::QuicSessionKey server_key("www.verisign.com", 443, true);
  scoped_ptr<net::QuicServerInfo> quic_server_info(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  net::TestCompletionCallback callback;
  int rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::ERR_IO_PENDING, rv);
  // Now complete the backend creation and let the callback run.
  factory->FinishCreation();
  EXPECT_EQ(net::OK, callback.GetResult(rv));
}

// Tests the basic logic of storing, retrieving and updating data.
TEST(DiskCacheBasedQuicServerInfo, Update) {
  MockHttpCache cache;
  AddMockTransaction(&kHostInfoTransaction1);
  net::TestCompletionCallback callback;

  net::QuicSessionKey server_key("www.google.com", 443, true);
  scoped_ptr<net::QuicServerInfo> quic_server_info(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  int rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  net::QuicServerInfo::State* state = quic_server_info->mutable_state();
  EXPECT_TRUE(state->certs.empty());
  const string server_config_a = "server_config_a";
  const string source_address_token_a = "source_address_token_a";
  const string server_config_sig_a = "server_config_sig_a";
  const string cert_a = "cert_a";
  const string cert_b = "cert_b";

  state->server_config = server_config_a;
  state->source_address_token = source_address_token_a;
  state->server_config_sig = server_config_sig_a;
  state->certs.push_back(cert_a);
  quic_server_info->Persist();

  // Wait until Persist() does the work.
  base::MessageLoop::current()->RunUntilIdle();

  // Open the stored QuicServerInfo.
  quic_server_info.reset(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  // And now update the data.
  state = quic_server_info->mutable_state();
  state->certs.push_back(cert_b);

  // Fail instead of DCHECKing double creates.
  cache.disk_cache()->set_double_create_check(false);
  quic_server_info->Persist();
  base::MessageLoop::current()->RunUntilIdle();

  // Verify that the state was updated.
  quic_server_info.reset(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  const net::QuicServerInfo::State& state1 = quic_server_info->state();
  EXPECT_TRUE(quic_server_info->IsDataReady());
  EXPECT_EQ(server_config_a, state1.server_config);
  EXPECT_EQ(source_address_token_a, state1.source_address_token);
  EXPECT_EQ(server_config_sig_a, state1.server_config_sig);
  EXPECT_EQ(2U, state1.certs.size());
  EXPECT_EQ(cert_a, state1.certs[0]);
  EXPECT_EQ(cert_b, state1.certs[1]);

  RemoveMockTransaction(&kHostInfoTransaction1);
}

// Test that demonstrates different info is returned when the ports differ.
TEST(DiskCacheBasedQuicServerInfo, UpdateDifferentPorts) {
  MockHttpCache cache;
  AddMockTransaction(&kHostInfoTransaction1);
  AddMockTransaction(&kHostInfoTransaction2);
  net::TestCompletionCallback callback;

  // Persist data for port 443.
  net::QuicSessionKey server_key1("www.google.com", 443, true);
  scoped_ptr<net::QuicServerInfo> quic_server_info1(
      new net::DiskCacheBasedQuicServerInfo(server_key1, cache.http_cache()));
  quic_server_info1->Start();
  int rv = quic_server_info1->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  net::QuicServerInfo::State* state1 = quic_server_info1->mutable_state();
  EXPECT_TRUE(state1->certs.empty());
  const string server_config_a = "server_config_a";
  const string source_address_token_a = "source_address_token_a";
  const string server_config_sig_a = "server_config_sig_a";
  const string cert_a = "cert_a";

  state1->server_config = server_config_a;
  state1->source_address_token = source_address_token_a;
  state1->server_config_sig = server_config_sig_a;
  state1->certs.push_back(cert_a);
  quic_server_info1->Persist();

  // Wait until Persist() does the work.
  base::MessageLoop::current()->RunUntilIdle();

  // Persist data for port 80.
  net::QuicSessionKey server_key2("www.google.com", 80, false);
  scoped_ptr<net::QuicServerInfo> quic_server_info2(
      new net::DiskCacheBasedQuicServerInfo(server_key2, cache.http_cache()));
  quic_server_info2->Start();
  rv = quic_server_info2->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  net::QuicServerInfo::State* state2 = quic_server_info2->mutable_state();
  EXPECT_TRUE(state2->certs.empty());
  const string server_config_b = "server_config_b";
  const string source_address_token_b = "source_address_token_b";
  const string server_config_sig_b = "server_config_sig_b";
  const string cert_b = "cert_b";

  state2->server_config = server_config_b;
  state2->source_address_token = source_address_token_b;
  state2->server_config_sig = server_config_sig_b;
  state2->certs.push_back(cert_b);
  quic_server_info2->Persist();

  // Wait until Persist() does the work.
  base::MessageLoop::current()->RunUntilIdle();

  // Verify the stored QuicServerInfo for port 443.
  scoped_ptr<net::QuicServerInfo> quic_server_info(
      new net::DiskCacheBasedQuicServerInfo(server_key1, cache.http_cache()));
  quic_server_info->Start();
  rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  const net::QuicServerInfo::State& state_a = quic_server_info->state();
  EXPECT_TRUE(quic_server_info->IsDataReady());
  EXPECT_EQ(server_config_a, state_a.server_config);
  EXPECT_EQ(source_address_token_a, state_a.source_address_token);
  EXPECT_EQ(server_config_sig_a, state_a.server_config_sig);
  EXPECT_EQ(1U, state_a.certs.size());
  EXPECT_EQ(cert_a, state_a.certs[0]);

  // Verify the stored QuicServerInfo for port 80.
  quic_server_info.reset(
      new net::DiskCacheBasedQuicServerInfo(server_key2, cache.http_cache()));
  quic_server_info->Start();
  rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  const net::QuicServerInfo::State& state_b = quic_server_info->state();
  EXPECT_TRUE(quic_server_info->IsDataReady());
  EXPECT_EQ(server_config_b, state_b.server_config);
  EXPECT_EQ(source_address_token_b, state_b.source_address_token);
  EXPECT_EQ(server_config_sig_b, state_b.server_config_sig);
  EXPECT_EQ(1U, state_b.certs.size());
  EXPECT_EQ(cert_b, state_b.certs[0]);

  RemoveMockTransaction(&kHostInfoTransaction2);
  RemoveMockTransaction(&kHostInfoTransaction1);
}

// Test IsDataReady when there is a pending write.
TEST(DiskCacheBasedQuicServerInfo, IsDataReady) {
  MockHttpCache cache;
  AddMockTransaction(&kHostInfoTransaction1);
  net::TestCompletionCallback callback;

  net::QuicSessionKey server_key("www.google.com", 443, true);
  scoped_ptr<net::QuicServerInfo> quic_server_info(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  EXPECT_TRUE(quic_server_info->IsDataReady());
  int rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_TRUE(quic_server_info->IsDataReady());
  EXPECT_EQ(net::OK, callback.GetResult(rv));

  net::QuicServerInfo::State* state = quic_server_info->mutable_state();
  EXPECT_TRUE(state->certs.empty());
  const string server_config_a = "server_config_a";
  const string source_address_token_a = "source_address_token_a";
  const string server_config_sig_a = "server_config_sig_a";
  const string cert_a = "cert_a";

  state->server_config = server_config_a;
  state->source_address_token = source_address_token_a;
  state->server_config_sig = server_config_sig_a;
  state->certs.push_back(cert_a);
  EXPECT_TRUE(quic_server_info->IsDataReady());
  quic_server_info->Persist();

  // Once we call Persist, IsDataReady should return false until Persist has
  // completed.
  EXPECT_FALSE(quic_server_info->IsDataReady());

  // Wait until Persist() does the work.
  base::MessageLoop::current()->RunUntilIdle();

  EXPECT_TRUE(quic_server_info->IsDataReady());

  // Verify that the state was updated.
  quic_server_info.reset(
      new net::DiskCacheBasedQuicServerInfo(server_key, cache.http_cache()));
  quic_server_info->Start();
  rv = quic_server_info->WaitForDataReady(callback.callback());
  EXPECT_EQ(net::OK, callback.GetResult(rv));
  EXPECT_TRUE(quic_server_info->IsDataReady());

  const net::QuicServerInfo::State& state1 = quic_server_info->state();
  EXPECT_TRUE(quic_server_info->IsDataReady());
  EXPECT_EQ(server_config_a, state1.server_config);
  EXPECT_EQ(source_address_token_a, state1.source_address_token);
  EXPECT_EQ(server_config_sig_a, state1.server_config_sig);
  EXPECT_EQ(1U, state1.certs.size());
  EXPECT_EQ(cert_a, state1.certs[0]);

  RemoveMockTransaction(&kHostInfoTransaction1);
}

}  // namespace
<|endoftext|>


<commit_before>#include <string>
#include <vector>

#include <iostream>
#include <iomanip>

#include "CharCounter.h"
#include "Dictionary.h"

static Dictionary dict;

void output(const std::string& result, const std::vector<std::string>& prefixes = {}) {
  static unsigned long count = 0;
  std::cout << std::setw(10) << ++count << ": ";

  for (const std::string& prefix : prefixes) {
    std::cout << prefix << " ";
  }

   std::cout << result << std::endl;
}

void findAnagrams(Dictionary::Iterator* it, CharCounter* counter) {
  if (counter->empty()) {
    output(it->word());
    return;
  }

  for (unsigned i = 0; i < counter->unique(); ++i) {
    char ch = (*counter)[i];

    if (it->move(ch)) {
      counter->remove(i);

      findAnagrams(it, counter);

      counter->restore(ch, i);
      it->back();
    }
  }
}

void findMultiwordAnagrams(Dictionary::Iterator* it, CharCounter* counter, std::vector<std::string>* prefixes) {
  if (counter->empty() && it->isWord()) {
    output(it->word(), *prefixes);
    return;
  }

  for (unsigned i = 0; i < counter->unique(); ++i) {
    char ch = (*counter)[i];

    if (it->move(ch)) {
      counter->remove(i);

      if (it->isWord()) {
        Dictionary::Iterator new_it(dict.iterator());

        prefixes->emplace_back(it->word());

        findMultiwordAnagrams(&new_it, counter, prefixes);

        prefixes->pop_back();
      }

      findMultiwordAnagrams(it, counter, prefixes);

      counter->restore(ch, i);
      it->back();
    }
  }
}

#include <fstream>

int main(int argc, char* argv[]) {
  std::ifstream wordlist("good_dictionary");
  dict.readFromFile(wordlist);

  for (int i = 1; i < argc; ++i) {
    CharCounter counter(argv[i]);
    std::cout << argv[i] << ": " << counter << std::endl;

    Dictionary::Iterator it(dict.iterator());

    //findAnagrams(&it, &counter);
    std::vector<std::string> prefixes;
    findMultiwordAnagrams(&it, &counter, &prefixes);
  }
}
<commit_msg>Command line options<commit_after>#include <string>
#include <vector>

#include <iostream>
#include <iomanip>

#include "CharCounter.h"
#include "Dictionary.h"

static Dictionary dict;

void output(const std::string& result, const std::vector<std::string>& prefixes = {}) {
  for (const std::string& prefix : prefixes) {
    std::cout << prefix << " ";
  }

   std::cout << result << std::endl;
}

void findAnagrams(Dictionary::Iterator* it, CharCounter* counter) {
  if (counter->empty()) {
    if (it->isWord()) output(it->word());
    return;
  }

  for (unsigned i = 0; i < counter->unique(); ++i) {
    char ch = (*counter)[i];

    if (it->move(ch)) {
      counter->remove(i);

      findAnagrams(it, counter);

      counter->restore(ch, i);
      it->back();
    }
  }
}

void findMultiwordAnagrams(Dictionary::Iterator* it, CharCounter* counter, std::vector<std::string>* prefixes) {
  if (counter->empty()) {
    if (it->isWord()) output(it->word(), *prefixes);
    return;
  }

  for (unsigned i = 0; i < counter->unique(); ++i) {
    char ch = (*counter)[i];

    if (it->move(ch)) {
      counter->remove(i);

      if (it->isWord()) {
        Dictionary::Iterator new_it(dict.iterator());

        prefixes->emplace_back(it->word());

        findMultiwordAnagrams(&new_it, counter, prefixes);

        prefixes->pop_back();
      }

      findMultiwordAnagrams(it, counter, prefixes);

      counter->restore(ch, i);
      it->back();
    }
  }
}

#include <fstream>

void printUsage(const char* prog_name) {
  std::cerr << "Find all anagrams of a word or phrase. The anagrams are output one per line.\n"
            << "\n"
            << "Usage:\n"
            << "\t" << prog_name << " [-s] [-d DICTIONARY_FILE] PHRASE...\n"
               "\n"
               "\tPHRASE\tThe word or words of which to find anagrams.\n"
               "\n"
               "\t-d\tSpecify which dictionary file to use. Default: \"dictionary\"\n"
               "\t-h\tDisplay this message. In case you forgot something?\n"
               "\t-s\tOnly find single-word anagrams.\n"
            << std::endl;
}

template<typename T>
bool parseOptions(int argc, char* argv[], T* settings) {
  for (int i = 1; i < argc; ++i) {
    if (argv[i][0] == '-') {
      for (char *c = &argv[i][1]; *c != '\0'; ++c) {
        switch (*c) {
        case 'd':
          if (i < (argc-1)){
            settings->dictionary = argv[++i];
          }
          else {
            printf("No value provided for -%c option.\n", *c);
            return false;
          }
          break;
        case 'h': printUsage(argv[0]); return false;
        case 's': settings->single_word = true; break;
        default:
          printf("Unknown option \"%s\".\n", argv[i]);
          printUsage(argv[0]);
          return false;
        }
      }
    }
    else {
      settings->phrase += argv[i];
    }
  }

  return true;
}

int main(int argc, char* argv[]) {
  using namespace std;

  struct {
    bool single_word = false;
    std::string dictionary = "dictionary";
    std::string phrase;
  } settings;

  if (!parseOptions(argc, argv, &settings)) {
    return 1;
  }

  if (!Dictionary::processWord(&settings.phrase)) {
    cerr << "Illegal character in " << settings.phrase
         << ". Only the 26 characters of the Latin alphabet are allowed." << endl;
    return 1;
  }

  std::ifstream wordlist(settings.dictionary);

  if (!wordlist.is_open()) {
    cerr << "Cannot find dictionary file \"" << settings.dictionary << "\"." << endl;
    return 1;
  }

  dict.readFromFile(wordlist);

  CharCounter counter(settings.phrase);
  Dictionary::Iterator it(dict.iterator());
if (settings.single_word) {
    findAnagrams(&it, &counter);
  }
  else {
    std::vector<std::string> prefixes;
    findMultiwordAnagrams(&it, &counter, &prefixes);
  }

  return 0;
}
<|endoftext|>


<commit_before>//=============================================================================
// ■ tiled_map.cpp
//-----------------------------------------------------------------------------
//   Tile地图
//=============================================================================

#include "tiled_map.hpp"

namespace VM76 {

	void TiledMap::init_cinstances (Tiles* cinstance[]) {
		#define FILL_ID(id, f) cinstance[id - 1] = new f;

		FILL_ID(Grass, MultiFaceCubeTile(49,49,0,2,49,49))
		FILL_ID(Stone, SimpleCubeTile(1))
		FILL_ID(Dirt, SimpleCubeTile(2))
		FILL_ID(Glass, SimpleCubeTile(3))
		FILL_ID(WoodPlank, SimpleCubeTile(4))
		FILL_ID(HalfBrick, MultiFaceCubeTile(5,5,6,6,5,5))
		FILL_ID(Brick, SimpleCubeTile(7))
		FILL_ID(TNT, MultiFaceCubeTile(8,8,9,10,8,8))
		FILL_ID(CobbleStone, SimpleCubeTile(16))

		// Fill the rest with MISSING TEXTURE
		for (int i = CobbleStone; i < 16; i ++) {
			FILL_ID(i + 1, SimpleCubeTile(31))
		}

		#undef FILL_ID
	}

	Tiles* TiledMap::get_instances (int id) {
		switch (id) {
			case Grass:
				return new MultiFaceCubeTile(49,49,0,2,49,49);
				break;
			case Stone:
				return new SimpleCubeTile(1);
				break;
			case Dirt:
				return new SimpleCubeTile(2);
				break;
			case Glass:
				return new SimpleCubeTile(3);
				break;
			case WoodPlank:
				return new SimpleCubeTile(4);
				break;
			case HalfBrick:
				return new MultiFaceCubeTile(5,5,6,6,5,5);
				break;
			case Brick:
				return new SimpleCubeTile(7);
				break;
			case TNT:
				return new MultiFaceCubeTile(8,8,9,10,8,8);
				break;
			case CobbleStone:
				return new SimpleCubeTile(16);
				break;
			default:
				return NULL;
				break;
		}
	}

	TiledMap::TiledMap(int x, int y, int z, glm::vec3 wp, DataMap* m) {
		width = x; length = z; height = y;

		//init_cinstances(cinstance);
		memset(cinstance, 0, sizeof(cinstance));
		map = m;

		mount_point = wp;
	}

	void TiledMap::bake_tiles() {
		int count[16][6];

		glm::mat4* temp[16][6];
		for (int x = 0; x < 16; x++)
			for (int y = 0; y < 6; y++)
				temp[x][y] = (glm::mat4*) malloc(sizeof(glm::mat4) * 8192);

		memset(count, 0, sizeof(count));

		for (int x = mount_point.x; x < mount_point.x + width; x++) {
			for (int z = mount_point.z; z < length + mount_point.z; z++) {
				for (int y = mount_point.y; y < height + mount_point.y; y++) {
					int id = map->tidQuery(x, y, z);
					if (id > 0) {
						id --;

						glm::mat4 tr = glm::translate(glm::mat4(1.0), glm::vec3(x,y,z));
						if (map->tidQuery(x, y, z - 1) == 0) {
							temp[id][0][count[id][0]] = tr;
							count[id][0] ++;
						}

						if (map->tidQuery(x, y, z + 1) == 0) {
							temp[id][1][count[id][1]] = tr;
							count[id][1] ++;
						}

						if (map->tidQuery(x, y + 1, z) == 0) {
							temp[id][2][count[id][2]] = tr;
							count[id][2] ++;
						}

						if (map->tidQuery(x, y - 1, z) == 0) {
							temp[id][3][count[id][3]] = tr;
							count[id][3] ++;
						}

						if (map->tidQuery(x - 1, y, z) == 0) {
							temp[id][4][count[id][4]] = tr;
							count[id][4] ++;
						}

						if (map->tidQuery(x + 1, y, z) == 0) {
							temp[id][5][count[id][5]] = tr;
							count[id][5] ++;
						}
					}
				}
			}
		}

		for (int id = 0; id < 16; id ++) {

			bool has_block_valid = false;
			for (int x = 0; x < 6; x++) if (count[id][x]) {
				has_block_valid = true;
				break;
			}

			if (has_block_valid) {
				if (!cinstance[id]) cinstance[id] = get_instances(id + 1);

				for (int x = 0; x < 6; x++) {
					if (count[id][x] > 0) {
						xefree(cinstance[id]->mat[x]);

						cinstance[id]->mat[x] = new glm::mat4[count[id][x]];
						memcpy(cinstance[id]->mat[x], temp[id][x], sizeof(glm::mat4) * count[id][x]);
					}
				}
			} else if (cinstance[id]) {
				VMDE_Dispose(cinstance[id]);
			}
		}

		for (int x = 0; x < 16; x++)
			for (int y = 0; y < 6; y++)
				xefree(temp[x][y]);

		for (int id = 0; id < 16; id++) {
			if (cinstance[id]) cinstance[id]->update_instance(
				count[id][0],count[id][1],count[id][2],
				count[id][3],count[id][4],count[id][5]
			);
		}
	}

	void TiledMap::render() {
		for (int i = 0; i < 16; i++)
			if (cinstance[i]) cinstance[i]->render();
	}

	void TiledMap::dispose() {
		for (int i = 0; i < 16; i++)
			if (cinstance[i]) VMDE_Dispose(cinstance[i]);
	}
}
<commit_msg>好好利用get_instance<commit_after>//=============================================================================
// ■ tiled_map.cpp
//-----------------------------------------------------------------------------
//   Tile地图
//=============================================================================

#include "tiled_map.hpp"

namespace VM76 {

	void TiledMap::init_cinstances (Tiles* cinstance[]) {
		for (int i = 0; i < 16; i ++)
			cinstance[i] = get_instances(i + 1);
	}

	Tiles* TiledMap::get_instances (int id) {
		switch (id) {
			case Grass:
				return new MultiFaceCubeTile(49,49,0,2,49,49);
				break;
			case Stone:
				return new SimpleCubeTile(1);
				break;
			case Dirt:
				return new SimpleCubeTile(2);
				break;
			case Glass:
				return new SimpleCubeTile(3);
				break;
			case WoodPlank:
				return new SimpleCubeTile(4);
				break;
			case HalfBrick:
				return new MultiFaceCubeTile(5,5,6,6,5,5);
				break;
			case Brick:
				return new SimpleCubeTile(7);
				break;
			case TNT:
				return new MultiFaceCubeTile(8,8,9,10,8,8);
				break;
			case CobbleStone:
				return new SimpleCubeTile(16);
				break;
			default:
				return new SimpleCubeTile(31);
				break;
		}
	}

	TiledMap::TiledMap(int x, int y, int z, glm::vec3 wp, DataMap* m) {
		width = x; length = z; height = y;

		//init_cinstances(cinstance);
		memset(cinstance, 0, sizeof(cinstance));
		map = m;

		mount_point = wp;
	}

	void TiledMap::bake_tiles() {
		int count[16][6];

		glm::mat4* temp[16][6];
		for (int x = 0; x < 16; x++)
			for (int y = 0; y < 6; y++)
				temp[x][y] = (glm::mat4*) malloc(sizeof(glm::mat4) * 8192);

		memset(count, 0, sizeof(count));

		for (int x = mount_point.x; x < mount_point.x + width; x++) {
			for (int z = mount_point.z; z < length + mount_point.z; z++) {
				for (int y = mount_point.y; y < height + mount_point.y; y++) {
					int id = map->tidQuery(x, y, z);
					if (id > 0) {
						id --;

						glm::mat4 tr = glm::translate(glm::mat4(1.0), glm::vec3(x,y,z));
						if (map->tidQuery(x, y, z - 1) == 0) {
							temp[id][0][count[id][0]] = tr;
							count[id][0] ++;
						}

						if (map->tidQuery(x, y, z + 1) == 0) {
							temp[id][1][count[id][1]] = tr;
							count[id][1] ++;
						}

						if (map->tidQuery(x, y + 1, z) == 0) {
							temp[id][2][count[id][2]] = tr;
							count[id][2] ++;
						}

						if (map->tidQuery(x, y - 1, z) == 0) {
							temp[id][3][count[id][3]] = tr;
							count[id][3] ++;
						}

						if (map->tidQuery(x - 1, y, z) == 0) {
							temp[id][4][count[id][4]] = tr;
							count[id][4] ++;
						}

						if (map->tidQuery(x + 1, y, z) == 0) {
							temp[id][5][count[id][5]] = tr;
							count[id][5] ++;
						}
					}
				}
			}
		}

		for (int id = 0; id < 16; id ++) {

			bool has_block_valid = false;
			for (int x = 0; x < 6; x++) if (count[id][x]) {
				has_block_valid = true;
				break;
			}

			if (has_block_valid) {
				if (!cinstance[id]) cinstance[id] = get_instances(id + 1);

				for (int x = 0; x < 6; x++) {
					if (count[id][x] > 0) {
						xefree(cinstance[id]->mat[x]);

						cinstance[id]->mat[x] = new glm::mat4[count[id][x]];
						memcpy(cinstance[id]->mat[x], temp[id][x], sizeof(glm::mat4) * count[id][x]);
					}
				}
			} else if (cinstance[id]) {
				VMDE_Dispose(cinstance[id]);
			}
		}

		for (int x = 0; x < 16; x++)
			for (int y = 0; y < 6; y++)
				xefree(temp[x][y]);

		for (int id = 0; id < 16; id++) {
			if (cinstance[id]) cinstance[id]->update_instance(
				count[id][0],count[id][1],count[id][2],
				count[id][3],count[id][4],count[id][5]
			);
		}
	}

	void TiledMap::render() {
		for (int i = 0; i < 16; i++)
			if (cinstance[i]) cinstance[i]->render();
	}

	void TiledMap::dispose() {
		for (int i = 0; i < 16; i++)
			if (cinstance[i]) VMDE_Dispose(cinstance[i]);
	}
}
<|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 "util/disk-info.h"

#ifdef __APPLE__
#include <sys/mount.h>
#else
#include <sys/vfs.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <iostream>
#include <fstream>
#include <sstream>

#include "util/debug-util.h"

#include "common/names.h"

using boost::algorithm::is_any_of;
using boost::algorithm::split;
using boost::algorithm::token_compress_on;
using boost::algorithm::trim;
using boost::algorithm::trim_right_if;

namespace impala {

bool DiskInfo::initialized_;
vector<DiskInfo::Disk> DiskInfo::disks_;
map<dev_t, int> DiskInfo::device_id_to_disk_id_;
map<string, int> DiskInfo::disk_name_to_disk_id_;

// Parses /proc/partitions to get the number of disks.  A bit of looking around
// seems to indicate this as the best way to do this.
// TODO: is there not something better than this?
void DiskInfo::GetDeviceNames() {
  // Format of this file is:
  //    major, minor, #blocks, name
  // We are only interesting in name which is formatted as device_name<partition #>
  // The same device will show up multiple times for each partition (e.g. sda1, sda2).
  ifstream partitions("/proc/partitions", ios::in);
  while (partitions.good() && !partitions.eof()) {
    string line;
    getline(partitions, line);
    trim(line);

    vector<string> fields;
    split(fields, line, is_any_of(" "), token_compress_on);
    if (fields.size() != 4) continue;
    string name = fields[3];
    if (name == "name") continue;

    // Remove the partition# from the name.  e.g. sda2 --> sda
    trim_right_if(name, is_any_of("0123456789"));

    // Create a mapping of all device ids (one per partition) to the disk id.
    int major_dev_id = atoi(fields[0].c_str());
    int minor_dev_id = atoi(fields[1].c_str());
    dev_t dev = makedev(major_dev_id, minor_dev_id);
    DCHECK(device_id_to_disk_id_.find(dev) == device_id_to_disk_id_.end());

    int disk_id = -1;
    map<string, int>::iterator it = disk_name_to_disk_id_.find(name);
    if (it == disk_name_to_disk_id_.end()) {
      // First time seeing this disk
      disk_id = disks_.size();
      disks_.push_back(Disk(name, disk_id));
      disk_name_to_disk_id_[name] = disk_id;
    } else {
      disk_id = it->second;
    }
    device_id_to_disk_id_[dev] = disk_id;
  }

  if (partitions.is_open()) partitions.close();

  if (disks_.empty()) {
    // If all else fails, return 1
    LOG(WARNING) << "Could not determine number of disks on this machine.";
    disks_.push_back(Disk("sda", 0));
    return;
  }

  // Determine if the disk is rotational or not.
  for (int i = 0; i < disks_.size(); ++i) {
    // We can check if it is rotational by reading:
    // /sys/block/<device>/queue/rotational
    // If the file is missing or has unexpected data, default to rotational.
    stringstream ss;
    ss << "/sys/block/" << disks_[i].name << "/queue/rotational";
    ifstream rotational(ss.str().c_str(), ios::in);
    if (rotational.good()) {
      string line;
      getline(rotational, line);
      if (line == "0") disks_[i].is_rotational = false;
    }
    if (rotational.is_open()) rotational.close();
  }
}

void DiskInfo::Init() {
  GetDeviceNames();
  initialized_ = true;
}

int DiskInfo::disk_id(const char* path) {
  struct stat s;
  stat(path, &s);
  map<dev_t, int>::iterator it = device_id_to_disk_id_.find(s.st_dev);
  if (it == device_id_to_disk_id_.end()) return -1;
  return it->second;
}

string DiskInfo::DebugString() {
  DCHECK(initialized_);
  stringstream stream;
  stream << "Disk Info: " << endl;
  stream << "  Num disks " << num_disks() << ": " << endl;
  for (int i = 0; i < disks_.size(); ++i) {
    stream << "    " << disks_[i].name
           << " (rotational=" << (disks_[i].is_rotational ? "true" : "false") << ")\n";
  }
  stream << endl;
  return stream.str();
}

}
<commit_msg>sys/types.h no longer includes sys/sysmacros.h<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 "util/disk-info.h"

#ifdef __APPLE__
#include <sys/mount.h>
#else
#include <sys/vfs.h>
#endif
#include <sys/types.h>
#include <sys/sysmacros.h>
#include <sys/stat.h>
#include <unistd.h>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <iostream>
#include <fstream>
#include <sstream>

#include "util/debug-util.h"

#include "common/names.h"

using boost::algorithm::is_any_of;
using boost::algorithm::split;
using boost::algorithm::token_compress_on;
using boost::algorithm::trim;
using boost::algorithm::trim_right_if;

namespace impala {

bool DiskInfo::initialized_;
vector<DiskInfo::Disk> DiskInfo::disks_;
map<dev_t, int> DiskInfo::device_id_to_disk_id_;
map<string, int> DiskInfo::disk_name_to_disk_id_;

// Parses /proc/partitions to get the number of disks.  A bit of looking around
// seems to indicate this as the best way to do this.
// TODO: is there not something better than this?
void DiskInfo::GetDeviceNames() {
  // Format of this file is:
  //    major, minor, #blocks, name
  // We are only interesting in name which is formatted as device_name<partition #>
  // The same device will show up multiple times for each partition (e.g. sda1, sda2).
  ifstream partitions("/proc/partitions", ios::in);
  while (partitions.good() && !partitions.eof()) {
    string line;
    getline(partitions, line);
    trim(line);

    vector<string> fields;
    split(fields, line, is_any_of(" "), token_compress_on);
    if (fields.size() != 4) continue;
    string name = fields[3];
    if (name == "name") continue;

    // Remove the partition# from the name.  e.g. sda2 --> sda
    trim_right_if(name, is_any_of("0123456789"));

    // Create a mapping of all device ids (one per partition) to the disk id.
    int major_dev_id = atoi(fields[0].c_str());
    int minor_dev_id = atoi(fields[1].c_str());
    dev_t dev = makedev(major_dev_id, minor_dev_id);
    DCHECK(device_id_to_disk_id_.find(dev) == device_id_to_disk_id_.end());

    int disk_id = -1;
    map<string, int>::iterator it = disk_name_to_disk_id_.find(name);
    if (it == disk_name_to_disk_id_.end()) {
      // First time seeing this disk
      disk_id = disks_.size();
      disks_.push_back(Disk(name, disk_id));
      disk_name_to_disk_id_[name] = disk_id;
    } else {
      disk_id = it->second;
    }
    device_id_to_disk_id_[dev] = disk_id;
  }

  if (partitions.is_open()) partitions.close();

  if (disks_.empty()) {
    // If all else fails, return 1
    LOG(WARNING) << "Could not determine number of disks on this machine.";
    disks_.push_back(Disk("sda", 0));
    return;
  }

  // Determine if the disk is rotational or not.
  for (int i = 0; i < disks_.size(); ++i) {
    // We can check if it is rotational by reading:
    // /sys/block/<device>/queue/rotational
    // If the file is missing or has unexpected data, default to rotational.
    stringstream ss;
    ss << "/sys/block/" << disks_[i].name << "/queue/rotational";
    ifstream rotational(ss.str().c_str(), ios::in);
    if (rotational.good()) {
      string line;
      getline(rotational, line);
      if (line == "0") disks_[i].is_rotational = false;
    }
    if (rotational.is_open()) rotational.close();
  }
}

void DiskInfo::Init() {
  GetDeviceNames();
  initialized_ = true;
}

int DiskInfo::disk_id(const char* path) {
  struct stat s;
  stat(path, &s);
  map<dev_t, int>::iterator it = device_id_to_disk_id_.find(s.st_dev);
  if (it == device_id_to_disk_id_.end()) return -1;
  return it->second;
}

string DiskInfo::DebugString() {
  DCHECK(initialized_);
  stringstream stream;
  stream << "Disk Info: " << endl;
  stream << "  Num disks " << num_disks() << ": " << endl;
  for (int i = 0; i < disks_.size(); ++i) {
    stream << "    " << disks_[i].name
           << " (rotational=" << (disks_[i].is_rotational ? "true" : "false") << ")\n";
  }
  stream << endl;
  return stream.str();
}

}
<|endoftext|>


<commit_before>// Tools.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include "Tools.h"
#include "Program.h"
#include "interface/Tool.h"
#include "interface/PropertyChoice.h"
#include "CTool.h"
#include "CNCConfig.h"
#include "tinyxml/tinyxml.h"
#include <wx/stdpaths.h>

bool CTools::CanAdd(HeeksObj* object)
{
	return 	((object != NULL) && (object->GetType() == ToolType));
}

HeeksObj *CTools::MakeACopy(void) const
{
    return(new CTools(*this));  // Call the copy constructor.
}

CTools::CTools()
{
    CNCConfig config;
	config.Read(_T("title_format"), (int *) (&m_title_format), int(eGuageReplacesSize) );
}

CTools::CTools( const CTools & rhs ) : ObjList(rhs)
{
    m_title_format = rhs.m_title_format;
}

CTools & CTools::operator= ( const CTools & rhs )
{
    if (this != &rhs)
    {
        ObjList::operator=( rhs );
        m_title_format = rhs.m_title_format;
    }
    return(*this);
}

const wxBitmap &CTools::GetIcon()
{
	static wxBitmap* icon = NULL;
	if(icon == NULL)icon = new wxBitmap(wxImage(theApp.GetResFolder() + _T("/icons/tools.png")));
	return *icon;
}

/**
	We need to copy the tools from the CTools object passed in into our own
	list.  We don't want to duplicate tools that are already in our local tool table.
	If we import a tool, we need to make sure the tool number is unique within the
	whole tool table.  If we need to renumber a tool during this import, we need to
	also update any associated Operations objects that refer to this tool number
	so that they now point to the new tool number.
 */
void CTools::CopyFrom(const HeeksObj* object)
{
    /*
    if (object->GetType() == GetType())
    {
        for (HeeksObj *tool = object->GetFirstChild(); tool != NULL; tool = object->GetNextChild())
        {

        }
    }
    */
}

void CTools::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = heeksCAD->NewXMLElement( "Tools" );
	heeksCAD->LinkXMLEndChild( root,  element );
	WriteBaseXML(element);
}

//static
HeeksObj* CTools::ReadFromXMLElement(TiXmlElement* pElem)
{
	CTools* new_object = new CTools;
	new_object->ReadBaseXML(pElem);
	return new_object;
}

class ExportTools: public Tool{
	bool m_for_default;

	// Tool's virtual functions
	const wxChar* GetTitle(){return m_for_default ? _("Save As Default"):_("Export");}
	void Run()
	{
#if wxCHECK_VERSION(3, 0, 0)
		wxStandardPaths& standard_paths = wxStandardPaths::Get();
#else
		wxStandardPaths standard_paths;
#endif
		if (previous_path.Length() == 0) previous_path = _T("default.tooltable");

		if(m_for_default)
		{
			previous_path = theApp.GetResourceFilename(wxT("default.tooltable"), true);
		}
		else
		{
			// Prompt the user to select a file to import.
			wxFileDialog fd(heeksCAD->GetMainFrame(), _T("Select a file to export to"),
				standard_paths.GetUserConfigDir().c_str(), previous_path.c_str(),
				wxString(_("Known Files")) + _T(" |*.heeks;*.HEEKS;")
				+ _T("*.tool;*.TOOL;*.Tool;")
				+ _T("*.tools;*.TOOLS;*.Tools;")
				+ _T("*.tooltable;*.TOOLTABLE;*.ToolTable;"),
				wxFD_SAVE | wxFD_OVERWRITE_PROMPT );

			fd.SetFilterIndex(1);
			if (fd.ShowModal() == wxID_CANCEL) return;
			previous_path = fd.GetPath().c_str();
		}

		std::list<HeeksObj *> tools;
		for (HeeksObj *tool = theApp.m_program->Tools()->GetFirstChild();
			tool != NULL;
			tool = theApp.m_program->Tools()->GetNextChild() )
		{
			tools.push_back( tool );
		} // End for
		wprintf(wxT("Exporting tools as ") + previous_path  + wxT("\n"));
		heeksCAD->SaveXMLFile( tools, previous_path.c_str(), false );
	}
	wxString BitmapPath(){ return _T("export");}
	wxString previous_path;

public:
	ExportTools(bool for_default = false)
	{
		m_for_default = for_default;
	}
};

static ExportTools export_tools;
static ExportTools save_default_tools(true);

void ImportToolsFile( const wxChar *file_path )
{
    // Delete the speed references that we've already got.  Otherwise we end
    // up with duplicates.  Do this in two passes.  Otherwise we end up
    // traversing the same list that we're modifying.

    std::list<HeeksObj *> tools;
    for (HeeksObj *tool = theApp.m_program->Tools()->GetFirstChild();
        tool != NULL;
        tool = theApp.m_program->Tools()->GetNextChild() )
    {
        tools.push_back( tool );
    } // End for

    for (std::list<HeeksObj *>::iterator l_itObject = tools.begin(); l_itObject != tools.end(); l_itObject++)
    {
        heeksCAD->Remove( *l_itObject );
    } // End for

    // And read the default speed references.
    // heeksCAD->OpenXMLFile( _T("default.speeds"), true, theApp.m_program->m_tools );
    heeksCAD->OpenXMLFile( file_path, theApp.m_program->Tools() );
}

class ImportTools: public Tool{
	bool m_for_default;

	// Tool's virtual functions
	const wxChar* GetTitle(){return m_for_default ? _("Restore Default Tools"):_("Import");}
	void Run()
	{
#if wxCHECK_VERSION(3, 0, 0)
		wxStandardPaths& standard_paths = wxStandardPaths::Get();
#else
		wxStandardPaths standard_paths;
#endif
		if (previous_path.Length() == 0) previous_path = _T("default.tooltable");

		if(m_for_default)
		{
			previous_path = theApp.GetResourceFilename(wxT("default.tooltable"));
		}
		else
		{
			// Prompt the user to select a file to import.
			wxFileDialog fd(heeksCAD->GetMainFrame(), _T("Select a file to import"),
				standard_paths.GetUserConfigDir().c_str(), previous_path.c_str(),
				wxString(_("Known Files")) + _T(" |*.heeks;*.HEEKS;")
				+ _T("*.tool;*.TOOL;*.Tool;")
				+ _T("*.tools;*.TOOLS;*.Tools;")
				+ _T("*.tooltable;*.TOOLTABLE;*.ToolTable;"),
				wxFD_OPEN | wxFD_FILE_MUST_EXIST );
			fd.SetFilterIndex(1);
			if (fd.ShowModal() == wxID_CANCEL) return;
			previous_path = fd.GetPath().c_str();
		}

        ImportToolsFile( previous_path.c_str() );
	}
	wxString BitmapPath(){ return _T("import");}
	wxString previous_path;

public:
	ImportTools(bool for_default = false)
	{
		m_for_default = for_default;
	}
};

static ImportTools import_tools;
static ImportTools import_default_tools(true);

void CTools::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
	t_list->push_back(&save_default_tools);
	t_list->push_back(&import_default_tools);
	t_list->push_back(&import_tools);
	t_list->push_back(&export_tools);

	CHeeksCNCApp::GetNewToolTools(t_list);

	ObjList::GetTools(t_list, p);
}

static void on_set_title_format(int value, HeeksObj* object, bool from_undo_redo)
{
	((CTools *)object)->m_title_format = CTools::TitleFormat_t(value);

	CNCConfig config;
	config.Write(_T("title_format"), (int)(((CTools *)object)->m_title_format));
}

void CTools::GetProperties(std::list<Property *> *list)
{
	{
		std::list< wxString > choices;
		choices.push_back( _("Guage number replaces size") );
		choices.push_back( _("Include guage number and size") );

		list->push_back ( new PropertyChoice ( _("Title Format"),  choices, m_title_format, this, on_set_title_format ) );
	}
	HeeksObj::GetProperties(list);
}

<commit_msg>UI: explicit terms for tool table entries<commit_after>// Tools.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include "Tools.h"
#include "Program.h"
#include "interface/Tool.h"
#include "interface/PropertyChoice.h"
#include "CTool.h"
#include "CNCConfig.h"
#include "tinyxml/tinyxml.h"
#include <wx/stdpaths.h>

bool CTools::CanAdd(HeeksObj* object)
{
	return 	((object != NULL) && (object->GetType() == ToolType));
}

HeeksObj *CTools::MakeACopy(void) const
{
    return(new CTools(*this));  // Call the copy constructor.
}

CTools::CTools()
{
    CNCConfig config;
	config.Read(_T("title_format"), (int *) (&m_title_format), int(eGuageReplacesSize) );
}

CTools::CTools( const CTools & rhs ) : ObjList(rhs)
{
    m_title_format = rhs.m_title_format;
}

CTools & CTools::operator= ( const CTools & rhs )
{
    if (this != &rhs)
    {
        ObjList::operator=( rhs );
        m_title_format = rhs.m_title_format;
    }
    return(*this);
}

const wxBitmap &CTools::GetIcon()
{
	static wxBitmap* icon = NULL;
	if(icon == NULL)icon = new wxBitmap(wxImage(theApp.GetResFolder() + _T("/icons/tools.png")));
	return *icon;
}

/**
	We need to copy the tools from the CTools object passed in into our own
	list.  We don't want to duplicate tools that are already in our local tool table.
	If we import a tool, we need to make sure the tool number is unique within the
	whole tool table.  If we need to renumber a tool during this import, we need to
	also update any associated Operations objects that refer to this tool number
	so that they now point to the new tool number.
 */
void CTools::CopyFrom(const HeeksObj* object)
{
    /*
    if (object->GetType() == GetType())
    {
        for (HeeksObj *tool = object->GetFirstChild(); tool != NULL; tool = object->GetNextChild())
        {

        }
    }
    */
}

void CTools::WriteXML(TiXmlNode *root)
{
	TiXmlElement * element;
	element = heeksCAD->NewXMLElement( "Tools" );
	heeksCAD->LinkXMLEndChild( root,  element );
	WriteBaseXML(element);
}

//static
HeeksObj* CTools::ReadFromXMLElement(TiXmlElement* pElem)
{
	CTools* new_object = new CTools;
	new_object->ReadBaseXML(pElem);
	return new_object;
}

class ExportTools: public Tool{
	bool m_for_default;

	// Tool's virtual functions
	const wxChar* GetTitle(){return m_for_default ? _("Save As Default"):_("Export Tool Table...");}
	void Run()
	{
#if wxCHECK_VERSION(3, 0, 0)
		wxStandardPaths& standard_paths = wxStandardPaths::Get();
#else
		wxStandardPaths standard_paths;
#endif
		if (previous_path.Length() == 0) previous_path = _T("default.tooltable");

		if(m_for_default)
		{
			previous_path = theApp.GetResourceFilename(wxT("default.tooltable"), true);
		}
		else
		{
			// Prompt the user to select a file to import.
			wxFileDialog fd(heeksCAD->GetMainFrame(), _T("Select a file to export to"),
				standard_paths.GetUserConfigDir().c_str(), previous_path.c_str(),
				wxString(_("Known Files")) + _T(" |*.heeks;*.HEEKS;")
				+ _T("*.tool;*.TOOL;*.Tool;")
				+ _T("*.tools;*.TOOLS;*.Tools;")
				+ _T("*.tooltable;*.TOOLTABLE;*.ToolTable;"),
				wxFD_SAVE | wxFD_OVERWRITE_PROMPT );

			fd.SetFilterIndex(1);
			if (fd.ShowModal() == wxID_CANCEL) return;
			previous_path = fd.GetPath().c_str();
		}

		std::list<HeeksObj *> tools;
		for (HeeksObj *tool = theApp.m_program->Tools()->GetFirstChild();
			tool != NULL;
			tool = theApp.m_program->Tools()->GetNextChild() )
		{
			tools.push_back( tool );
		} // End for
		wprintf(wxT("Exporting tools as ") + previous_path  + wxT("\n"));
		heeksCAD->SaveXMLFile( tools, previous_path.c_str(), false );
	}
	wxString BitmapPath(){ return _T("export");}
	wxString previous_path;

public:
	ExportTools(bool for_default = false)
	{
		m_for_default = for_default;
	}
};

static ExportTools export_tools;
static ExportTools save_default_tools(true);

void ImportToolsFile( const wxChar *file_path )
{
    // Delete the speed references that we've already got.  Otherwise we end
    // up with duplicates.  Do this in two passes.  Otherwise we end up
    // traversing the same list that we're modifying.

    std::list<HeeksObj *> tools;
    for (HeeksObj *tool = theApp.m_program->Tools()->GetFirstChild();
        tool != NULL;
        tool = theApp.m_program->Tools()->GetNextChild() )
    {
        tools.push_back( tool );
    } // End for

    for (std::list<HeeksObj *>::iterator l_itObject = tools.begin(); l_itObject != tools.end(); l_itObject++)
    {
        heeksCAD->Remove( *l_itObject );
    } // End for

    // And read the default speed references.
    // heeksCAD->OpenXMLFile( _T("default.speeds"), true, theApp.m_program->m_tools );
    heeksCAD->OpenXMLFile( file_path, theApp.m_program->Tools() );
}

class ImportTools: public Tool{
	bool m_for_default;

	// Tool's virtual functions
	const wxChar* GetTitle(){return m_for_default ? _("Restore Default Tools"):_("Import Tool Table...");}
	void Run()
	{
#if wxCHECK_VERSION(3, 0, 0)
		wxStandardPaths& standard_paths = wxStandardPaths::Get();
#else
		wxStandardPaths standard_paths;
#endif
		if (previous_path.Length() == 0) previous_path = _T("default.tooltable");

		if(m_for_default)
		{
			previous_path = theApp.GetResourceFilename(wxT("default.tooltable"));
		}
		else
		{
			// Prompt the user to select a file to import.
			wxFileDialog fd(heeksCAD->GetMainFrame(), _T("Select a file to import"),
				standard_paths.GetUserConfigDir().c_str(), previous_path.c_str(),
				wxString(_("Known Files")) + _T(" |*.heeks;*.HEEKS;")
				+ _T("*.tool;*.TOOL;*.Tool;")
				+ _T("*.tools;*.TOOLS;*.Tools;")
				+ _T("*.tooltable;*.TOOLTABLE;*.ToolTable;"),
				wxFD_OPEN | wxFD_FILE_MUST_EXIST );
			fd.SetFilterIndex(1);
			if (fd.ShowModal() == wxID_CANCEL) return;
			previous_path = fd.GetPath().c_str();
		}

        ImportToolsFile( previous_path.c_str() );
	}
	wxString BitmapPath(){ return _T("import");}
	wxString previous_path;

public:
	ImportTools(bool for_default = false)
	{
		m_for_default = for_default;
	}
};

static ImportTools import_tools;
static ImportTools import_default_tools(true);

void CTools::GetTools(std::list<Tool*>* t_list, const wxPoint* p)
{
	t_list->push_back(&save_default_tools);
	t_list->push_back(&import_default_tools);
	t_list->push_back(&import_tools);
	t_list->push_back(&export_tools);

	CHeeksCNCApp::GetNewToolTools(t_list);

	ObjList::GetTools(t_list, p);
}

static void on_set_title_format(int value, HeeksObj* object, bool from_undo_redo)
{
	((CTools *)object)->m_title_format = CTools::TitleFormat_t(value);

	CNCConfig config;
	config.Write(_T("title_format"), (int)(((CTools *)object)->m_title_format));
}

void CTools::GetProperties(std::list<Property *> *list)
{
	{
		std::list< wxString > choices;
		choices.push_back( _("Guage number replaces size") );
		choices.push_back( _("Include guage number and size") );

		list->push_back ( new PropertyChoice ( _("Title Format"),  choices, m_title_format, this, on_set_title_format ) );
	}
	HeeksObj::GetProperties(list);
}

<|endoftext|>


<commit_before>/* This file is part of the KDE libraries
  Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License version 2 as published by the Free Software Foundation.

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

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.
*/

// $Id$

#include "katefiledialog.h"
#include "katefiledialog.moc"

#include <kcombobox.h>
#include <ktoolbar.h>
#include <kglobal.h>
#include <kcharsets.h>

#include <qstringlist.h>
#include <qtextcodec.h>

KateFileDialog::KateFileDialog (const QString& startDir,
                    const QString& encoding,
                    QWidget *parent,
                    const QString& caption,
                    KFileDialog::OperationMode opMode )
  : KFileDialog (startDir, QString::null, parent, "", true)
{
  QString sEncoding (encoding);

  setCaption (caption);

  toolBar()->insertCombo(QStringList(), 33333, false, 0L, 0L, 0L, true);

  QStringList filter;
  filter << "all/allfiles";
  filter << "text/plain";

  if (opMode == Opening) {
    setMode(KFile::Files);
    setMimeFilter (filter, "all/allfiles");
    }
  else {
    setMode(KFile::File);
    setOperationMode( Saving );
    setMimeFilter (filter, "text/plain");
    }

  m_encoding = toolBar()->getCombo(33333);

  m_encoding->clear ();
  QStringList encodings (KGlobal::charsets()->availableEncodingNames());
  int insert = 0;
  for (uint i=0; i < encodings.count(); i++)
  {
    bool found = false;
    QTextCodec *codecForEnc = KGlobal::charsets()->codecForName(encodings[i], found);

    if (found)
    {
      m_encoding->insertItem (encodings[i]);

      if ( codecForEnc->name() == encoding )
      {
        m_encoding->setCurrentItem(insert);
      }

      insert++;
    }
  }
}

KateFileDialog::~KateFileDialog ()
{

}

KateFileDialogData KateFileDialog::exec()
{
  int n = KDialogBase::exec();

  KateFileDialogData data = KateFileDialogData ();

  if (n)
  {
    data.encoding = m_encoding->currentText();
    data.url = selectedURL ();
    data.urls = selectedURLs ();
  }

  return data;
}

void KateFileDialog::slotApply()
{
}

// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>all files<commit_after>/* This file is part of the KDE libraries
  Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License version 2 as published by the Free Software Foundation.

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

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  Boston, MA 02111-1307, USA.
*/

// $Id$

#include "katefiledialog.h"
#include "katefiledialog.moc"

#include <kcombobox.h>
#include <ktoolbar.h>
#include <kglobal.h>
#include <kcharsets.h>

#include <qstringlist.h>
#include <qtextcodec.h>

KateFileDialog::KateFileDialog (const QString& startDir,
                    const QString& encoding,
                    QWidget *parent,
                    const QString& caption,
                    KFileDialog::OperationMode opMode )
  : KFileDialog (startDir, QString::null, parent, "", true)
{
  QString sEncoding (encoding);

  setCaption (caption);

  toolBar()->insertCombo(QStringList(), 33333, false, 0L, 0L, 0L, true);

  QStringList filter;
  filter << "all/allfiles";
  filter << "text/plain";

  if (opMode == Opening) {
    setMode(KFile::Files);
    setMimeFilter (filter, "all/allfiles");
    }
  else {
    setMode(KFile::File);
    setOperationMode( Saving );
    setMimeFilter (filter, "all/allfiles");
    }

  m_encoding = toolBar()->getCombo(33333);

  m_encoding->clear ();
  QStringList encodings (KGlobal::charsets()->availableEncodingNames());
  int insert = 0;
  for (uint i=0; i < encodings.count(); i++)
  {
    bool found = false;
    QTextCodec *codecForEnc = KGlobal::charsets()->codecForName(encodings[i], found);

    if (found)
    {
      m_encoding->insertItem (encodings[i]);

      if ( codecForEnc->name() == encoding )
      {
        m_encoding->setCurrentItem(insert);
      }

      insert++;
    }
  }
}

KateFileDialog::~KateFileDialog ()
{

}

KateFileDialogData KateFileDialog::exec()
{
  int n = KDialogBase::exec();

  KateFileDialogData data = KateFileDialogData ();

  if (n)
  {
    data.encoding = m_encoding->currentText();
    data.url = selectedURL ();
    data.urls = selectedURLs ();
  }

  return data;
}

void KateFileDialog::slotApply()
{
}

// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|>


<commit_before>/*
    Copyright (C) 2010  Collabora Multimedia.
      @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program 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 Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "query.h"
#include "element.h"
#include "../QGlib/error.h"
#include "../QGlib/string_p.h"
#include <QtCore/QUrl>
#include <QtCore/QDebug>
#include <gst/gst.h>

namespace QGst {

QString Query::typeName() const
{
    return QString::fromUtf8(GST_QUERY_TYPE_NAME(object<GstQuery>()));
}

QueryType Query::type() const
{
    return static_cast<QueryType>(GST_QUERY_TYPE(object<GstQuery>()));
}

SharedStructure Query::structure()
{
    return SharedStructure(gst_query_get_structure(object<GstQuery>()));
}

const SharedStructure Query::structure() const
{
    return SharedStructure(gst_query_get_structure(object<GstQuery>()));
}

void Query::ref()
{
    //We are not supposed to ref() query objects created with gst_query_new_* methods
    //Workaround while the global hash is not implemented for refcounting
    //gst_query_ref(object<GstQuery>());
}

void Query::unref()
{
    //We have to unref() the object only once
    //Workaround while the global hash is not implemented for refcounting, leak for now
    //gst_query_unref(object<GstQuery>());
}

//********************************************************

PositionQueryPtr PositionQuery::create(Format format)
{
    return PositionQueryPtr::wrap(gst_query_new_position(static_cast<GstFormat>(format)), false);
}

Format PositionQuery::format() const
{
    GstFormat f;
    gst_query_parse_position(object<GstQuery>(), &f, NULL);
    return static_cast<Format>(f);
}

qint64 PositionQuery::position() const
{
    gint64 p;
    gst_query_parse_position(object<GstQuery>(), NULL, &p);
    return p;
}

void PositionQuery::setValues(Format format, qint64 position)
{
    gst_query_set_position(object<GstQuery>(), static_cast<GstFormat>(format), position);
}

//********************************************************

DurationQueryPtr DurationQuery::create(Format format)
{
    return DurationQueryPtr::wrap(gst_query_new_duration(static_cast<GstFormat>(format)), false);
}

Format DurationQuery::format() const
{
    GstFormat f;
    gst_query_parse_duration(object<GstQuery>(), &f, NULL);
    return static_cast<Format>(f);
}

qint64 DurationQuery::duration() const
{
    gint64 d;
    gst_query_parse_duration(object<GstQuery>(), NULL, &d);
    return d;
}

void DurationQuery::setValues(Format format, qint64 duration)
{
    gst_query_set_duration(object<GstQuery>(), static_cast<GstFormat>(format), duration);
}

//********************************************************

LatencyQueryPtr LatencyQuery::create()
{
    return LatencyQueryPtr::wrap(gst_query_new_latency(), false);
}

bool LatencyQuery::hasLive() const
{
    gboolean l;
    gst_query_parse_latency(object<GstQuery>(), &l, NULL, NULL);
    return l;
}

ClockTime LatencyQuery::minimumLatency() const
{
    GstClockTime c;
    gst_query_parse_latency(object<GstQuery>(), NULL, &c, NULL);
    return c;
}

ClockTime LatencyQuery::maximumLatency() const
{
    GstClockTime c;
    gst_query_parse_latency(object<GstQuery>(), NULL, NULL, &c);
    return c;
}

void LatencyQuery::setValues(bool live, ClockTime minimumLatency, ClockTime maximumLatency)
{
    gst_query_set_latency(object<GstQuery>(), live, minimumLatency, maximumLatency);
}

//********************************************************

SeekingQueryPtr SeekingQuery::create(Format format)
{
    return SeekingQueryPtr::wrap(gst_query_new_seeking(static_cast<GstFormat>(format)), false);
}

Format SeekingQuery::format() const
{
    GstFormat f;
    gst_query_parse_seeking(object<GstQuery>(), &f, NULL, NULL, NULL);
    return static_cast<Format>(f);
}

bool SeekingQuery::seekable() const
{
    gboolean s;
    gst_query_parse_seeking(object<GstQuery>(), NULL, &s, NULL, NULL);
    return s;
}

qint64 SeekingQuery::segmentStart() const
{
    gint64 s;
    gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, &s, NULL);
    return s;
}

qint64 SeekingQuery::segmentEnd() const
{
    gint64 s;
    gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, NULL, &s);
    return s;
}

void SeekingQuery::setValues(Format format, bool seekable, qint64 segmentStart, qint64 segmentEnd)
{
    gst_query_set_seeking(object<GstQuery>(), static_cast<GstFormat>(format), seekable,
                          segmentStart, segmentEnd);
}

//********************************************************

SegmentQueryPtr SegmentQuery::create(Format format)
{
    return SegmentQueryPtr::wrap(gst_query_new_segment(static_cast<GstFormat>(format)), false);
}

double SegmentQuery::rate() const
{
    gdouble r;
    gst_query_parse_segment(object<GstQuery>(), &r, NULL, NULL, NULL);
    return r;
}

Format SegmentQuery::format() const
{
    GstFormat f;
    gst_query_parse_segment(object<GstQuery>(), NULL, &f, NULL, NULL);
    return static_cast<Format>(f);
}

qint64 SegmentQuery::startValue() const
{
    gint64 s;
    gst_query_parse_segment(object<GstQuery>(), NULL, NULL, &s, NULL);
    return s;
}

qint64 SegmentQuery::stopValue() const
{
    gint64 s;
    gst_query_parse_segment(object<GstQuery>(), NULL, NULL, NULL, &s);
    return s;
}

void SegmentQuery::setValues(Format format, double rate, qint64 startValue, qint64 stopValue)
{
    gst_query_set_segment(object<GstQuery>(), rate, static_cast<GstFormat>(format), startValue,
                          stopValue);
}

//********************************************************

ConvertQueryPtr ConvertQuery::create(Format sourceFormat, qint64 value, Format destinationFormat)
{
    return ConvertQueryPtr::wrap(gst_query_new_convert(static_cast<GstFormat>(sourceFormat), value,
                                   static_cast<GstFormat>(destinationFormat)), false);
}

Format ConvertQuery::sourceFormat() const
{
    GstFormat f;
    gst_query_parse_convert(object<GstQuery>(), &f, NULL, NULL, NULL);
    return static_cast<Format>(f);
}

qint64 ConvertQuery::sourceValue() const
{
    gint64 v;
    gst_query_parse_convert(object<GstQuery>(), NULL, &v, NULL, NULL);
    return v;
}

Format ConvertQuery::destinationFormat() const
{
    GstFormat f;
    gst_query_parse_convert(object<GstQuery>(), NULL, NULL, &f, NULL);
    return static_cast<Format>(f);
}

qint64 ConvertQuery::destinationValue() const
{
    gint64 v;
    gst_query_parse_convert(object<GstQuery>(), NULL, NULL, NULL, &v);
    return v;
}

void ConvertQuery::setValues(Format sourceFormat, qint64 sourceValue, Format destinationFormat,
                              qint64 destinationValue)
{
    gst_query_set_convert(object<GstQuery>(), static_cast<GstFormat>(sourceFormat), sourceValue,
                          static_cast<GstFormat>(destinationFormat), destinationValue);
}

//********************************************************

FormatsQueryPtr FormatsQuery::create()
{
    return FormatsQueryPtr::wrap(gst_query_new_formats(), false);
}

QList<Format> FormatsQuery::formats() const
{
    guint cnt;
    QList<Format> formats;
    gst_query_parse_formats_length(object<GstQuery>(), &cnt);
    GstFormat f;
    for (uint i=0; i<cnt; i++) {
        gst_query_parse_formats_nth(object<GstQuery>(), i, &f);
        formats << static_cast<Format>(f);
    }
    return formats;
}

void FormatsQuery::setValue(const QList<Format> & formats)
{
    int cnt = formats.count();
    if (cnt==0) return;
    GstFormat f[cnt];
    for (int i=0; i<cnt; i++) {
        f[i] = static_cast<GstFormat>(formats.at(i));
    }
    gst_query_set_formatsv(object<GstQuery>(), cnt, f);
}

//********************************************************

BufferingQueryPtr BufferingQuery::create(Format format)
{
    return BufferingQueryPtr::wrap(gst_query_new_buffering(static_cast<GstFormat>(format)), false);
}

bool BufferingQuery::isBusy() const
{
    gboolean b;
    gst_query_parse_buffering_percent(object<GstQuery>(), &b, NULL);
    return b;
}

int BufferingQuery::percent() const
{
    gint p;
    gst_query_parse_buffering_percent(object<GstQuery>(), NULL, &p);
    return p;
}

void BufferingQuery::setValues(bool busy, int percent)
{
    gst_query_set_buffering_percent(object<GstQuery>(), busy, percent);
}

BufferingMode BufferingQuery::mode() const
{
    GstBufferingMode m;
    gst_query_parse_buffering_stats(object<GstQuery>(), &m, NULL, NULL, NULL);
    return static_cast<BufferingMode>(m);
}

int BufferingQuery::averageIn() const
{
    gint a;
    gst_query_parse_buffering_stats(object<GstQuery>(), NULL, &a, NULL, NULL);
    return a;
}

int BufferingQuery::averageOut() const
{
    gint a;
    gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, &a, NULL);
    return a;

}

qint64 BufferingQuery::bufferingLeft() const
{
    gint64 l;
    gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, NULL, &l);
    return l;
}
;
void BufferingQuery::setValues(BufferingMode mode, int averageIn, int averageOut,
                              qint64 bufferingLeft)
{
    gst_query_set_buffering_stats(object<GstQuery>(), static_cast<GstBufferingMode>(mode),
                                  averageIn, averageOut, bufferingLeft);
}

Format BufferingQuery::format() const
{
    GstFormat f;
    gst_query_parse_buffering_range(object<GstQuery>(), &f, NULL, NULL, NULL);
    return static_cast<Format>(f);
}

qint64 BufferingQuery::rangeStart() const
{
    gint64 r;
    gst_query_parse_buffering_range(object<GstQuery>(), NULL, &r, NULL, NULL);
    return r;
}

qint64 BufferingQuery::rangeStop() const
{
    gint64 r;
    gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, &r, NULL);
    return r;
}

qint64 BufferingQuery::estimatedTotal() const
{
    gint64 r;
    gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, NULL, &r);
    return r;
}

void BufferingQuery::setValues(Format rangeFormat, qint64 rangeStart, qint64 rangeStop,
                              qint64 estimatedTotal)
{
    gst_query_set_buffering_range(object<GstQuery>(), static_cast<GstFormat>(rangeFormat),
                                  rangeStart, rangeStop, estimatedTotal);
}

//********************************************************

UriQueryPtr UriQuery::create()
{
    return UriQueryPtr::wrap(gst_query_new_uri(), false);
}

QUrl UriQuery::uri() const
{
    gchar *uri;
    gst_query_parse_uri(object<GstQuery>(), &uri);
    return QUrl::fromPercentEncoding(uri);
}

void UriQuery::setValue(const QUrl & uri)
{
    gst_query_set_uri(object<GstQuery>(), uri.toEncoded());
}

//********************************************************

} //namespace QGst

QGLIB_REGISTER_VALUEIMPL_IMPLEMENTATION(
    QGst::QueryPtr,
    QGst::QueryPtr::wrap(GST_QUERY(gst_value_get_mini_object(value))),
    gst_value_set_mini_object(value, GST_MINI_OBJECT(static_cast<GstQuery*>(data)))
)

QDebug operator<<(QDebug debug, QGst::QueryType type)
{
    debug.nospace() << gst_query_type_get_name(static_cast<GstQueryType>(type));
    return debug.space();
}

QDebug operator<<(QDebug debug, const QGst::QueryPtr & query)
{
    debug.nospace() << "QGst::Query(Type: " << query->type() << ")";
    return debug.space();
}

<commit_msg>Fix QGst::Query compilation with msvc.<commit_after>/*
    Copyright (C) 2010  Collabora Multimedia.
      @author Mauricio Piacentini <mauricio.piacentini@collabora.co.uk>

    This library is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published
    by the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    This program 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 Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "query.h"
#include "element.h"
#include "../QGlib/error.h"
#include "../QGlib/string_p.h"
#include <QtCore/QUrl>
#include <QtCore/QDebug>
#include <gst/gst.h>

namespace QGst {

QString Query::typeName() const
{
    return QString::fromUtf8(GST_QUERY_TYPE_NAME(object<GstQuery>()));
}

QueryType Query::type() const
{
    return static_cast<QueryType>(GST_QUERY_TYPE(object<GstQuery>()));
}

SharedStructure Query::structure()
{
    return SharedStructure(gst_query_get_structure(object<GstQuery>()));
}

const SharedStructure Query::structure() const
{
    return SharedStructure(gst_query_get_structure(object<GstQuery>()));
}

void Query::ref()
{
    //We are not supposed to ref() query objects created with gst_query_new_* methods
    //Workaround while the global hash is not implemented for refcounting
    //gst_query_ref(object<GstQuery>());
}

void Query::unref()
{
    //We have to unref() the object only once
    //Workaround while the global hash is not implemented for refcounting, leak for now
    //gst_query_unref(object<GstQuery>());
}

//********************************************************

PositionQueryPtr PositionQuery::create(Format format)
{
    return PositionQueryPtr::wrap(gst_query_new_position(static_cast<GstFormat>(format)), false);
}

Format PositionQuery::format() const
{
    GstFormat f;
    gst_query_parse_position(object<GstQuery>(), &f, NULL);
    return static_cast<Format>(f);
}

qint64 PositionQuery::position() const
{
    gint64 p;
    gst_query_parse_position(object<GstQuery>(), NULL, &p);
    return p;
}

void PositionQuery::setValues(Format format, qint64 position)
{
    gst_query_set_position(object<GstQuery>(), static_cast<GstFormat>(format), position);
}

//********************************************************

DurationQueryPtr DurationQuery::create(Format format)
{
    return DurationQueryPtr::wrap(gst_query_new_duration(static_cast<GstFormat>(format)), false);
}

Format DurationQuery::format() const
{
    GstFormat f;
    gst_query_parse_duration(object<GstQuery>(), &f, NULL);
    return static_cast<Format>(f);
}

qint64 DurationQuery::duration() const
{
    gint64 d;
    gst_query_parse_duration(object<GstQuery>(), NULL, &d);
    return d;
}

void DurationQuery::setValues(Format format, qint64 duration)
{
    gst_query_set_duration(object<GstQuery>(), static_cast<GstFormat>(format), duration);
}

//********************************************************

LatencyQueryPtr LatencyQuery::create()
{
    return LatencyQueryPtr::wrap(gst_query_new_latency(), false);
}

bool LatencyQuery::hasLive() const
{
    gboolean l;
    gst_query_parse_latency(object<GstQuery>(), &l, NULL, NULL);
    return l;
}

ClockTime LatencyQuery::minimumLatency() const
{
    GstClockTime c;
    gst_query_parse_latency(object<GstQuery>(), NULL, &c, NULL);
    return c;
}

ClockTime LatencyQuery::maximumLatency() const
{
    GstClockTime c;
    gst_query_parse_latency(object<GstQuery>(), NULL, NULL, &c);
    return c;
}

void LatencyQuery::setValues(bool live, ClockTime minimumLatency, ClockTime maximumLatency)
{
    gst_query_set_latency(object<GstQuery>(), live, minimumLatency, maximumLatency);
}

//********************************************************

SeekingQueryPtr SeekingQuery::create(Format format)
{
    return SeekingQueryPtr::wrap(gst_query_new_seeking(static_cast<GstFormat>(format)), false);
}

Format SeekingQuery::format() const
{
    GstFormat f;
    gst_query_parse_seeking(object<GstQuery>(), &f, NULL, NULL, NULL);
    return static_cast<Format>(f);
}

bool SeekingQuery::seekable() const
{
    gboolean s;
    gst_query_parse_seeking(object<GstQuery>(), NULL, &s, NULL, NULL);
    return s;
}

qint64 SeekingQuery::segmentStart() const
{
    gint64 s;
    gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, &s, NULL);
    return s;
}

qint64 SeekingQuery::segmentEnd() const
{
    gint64 s;
    gst_query_parse_seeking(object<GstQuery>(), NULL, NULL, NULL, &s);
    return s;
}

void SeekingQuery::setValues(Format format, bool seekable, qint64 segmentStart, qint64 segmentEnd)
{
    gst_query_set_seeking(object<GstQuery>(), static_cast<GstFormat>(format), seekable,
                          segmentStart, segmentEnd);
}

//********************************************************

SegmentQueryPtr SegmentQuery::create(Format format)
{
    return SegmentQueryPtr::wrap(gst_query_new_segment(static_cast<GstFormat>(format)), false);
}

double SegmentQuery::rate() const
{
    gdouble r;
    gst_query_parse_segment(object<GstQuery>(), &r, NULL, NULL, NULL);
    return r;
}

Format SegmentQuery::format() const
{
    GstFormat f;
    gst_query_parse_segment(object<GstQuery>(), NULL, &f, NULL, NULL);
    return static_cast<Format>(f);
}

qint64 SegmentQuery::startValue() const
{
    gint64 s;
    gst_query_parse_segment(object<GstQuery>(), NULL, NULL, &s, NULL);
    return s;
}

qint64 SegmentQuery::stopValue() const
{
    gint64 s;
    gst_query_parse_segment(object<GstQuery>(), NULL, NULL, NULL, &s);
    return s;
}

void SegmentQuery::setValues(Format format, double rate, qint64 startValue, qint64 stopValue)
{
    gst_query_set_segment(object<GstQuery>(), rate, static_cast<GstFormat>(format), startValue,
                          stopValue);
}

//********************************************************

ConvertQueryPtr ConvertQuery::create(Format sourceFormat, qint64 value, Format destinationFormat)
{
    return ConvertQueryPtr::wrap(gst_query_new_convert(static_cast<GstFormat>(sourceFormat), value,
                                   static_cast<GstFormat>(destinationFormat)), false);
}

Format ConvertQuery::sourceFormat() const
{
    GstFormat f;
    gst_query_parse_convert(object<GstQuery>(), &f, NULL, NULL, NULL);
    return static_cast<Format>(f);
}

qint64 ConvertQuery::sourceValue() const
{
    gint64 v;
    gst_query_parse_convert(object<GstQuery>(), NULL, &v, NULL, NULL);
    return v;
}

Format ConvertQuery::destinationFormat() const
{
    GstFormat f;
    gst_query_parse_convert(object<GstQuery>(), NULL, NULL, &f, NULL);
    return static_cast<Format>(f);
}

qint64 ConvertQuery::destinationValue() const
{
    gint64 v;
    gst_query_parse_convert(object<GstQuery>(), NULL, NULL, NULL, &v);
    return v;
}

void ConvertQuery::setValues(Format sourceFormat, qint64 sourceValue, Format destinationFormat,
                              qint64 destinationValue)
{
    gst_query_set_convert(object<GstQuery>(), static_cast<GstFormat>(sourceFormat), sourceValue,
                          static_cast<GstFormat>(destinationFormat), destinationValue);
}

//********************************************************

FormatsQueryPtr FormatsQuery::create()
{
    return FormatsQueryPtr::wrap(gst_query_new_formats(), false);
}

QList<Format> FormatsQuery::formats() const
{
    guint cnt;
    QList<Format> formats;
    gst_query_parse_formats_length(object<GstQuery>(), &cnt);
    GstFormat f;
    for (uint i=0; i<cnt; i++) {
        gst_query_parse_formats_nth(object<GstQuery>(), i, &f);
        formats << static_cast<Format>(f);
    }
    return formats;
}

void FormatsQuery::setValue(const QList<Format> & formats)
{
    int cnt = formats.count();
    if (cnt==0) return;
    GstFormat *f = new GstFormat[cnt];
    for (int i=0; i<cnt; i++) {
        f[i] = static_cast<GstFormat>(formats.at(i));
    }
    gst_query_set_formatsv(object<GstQuery>(), cnt, f);
    delete [] f;
}

//********************************************************

BufferingQueryPtr BufferingQuery::create(Format format)
{
    return BufferingQueryPtr::wrap(gst_query_new_buffering(static_cast<GstFormat>(format)), false);
}

bool BufferingQuery::isBusy() const
{
    gboolean b;
    gst_query_parse_buffering_percent(object<GstQuery>(), &b, NULL);
    return b;
}

int BufferingQuery::percent() const
{
    gint p;
    gst_query_parse_buffering_percent(object<GstQuery>(), NULL, &p);
    return p;
}

void BufferingQuery::setValues(bool busy, int percent)
{
    gst_query_set_buffering_percent(object<GstQuery>(), busy, percent);
}

BufferingMode BufferingQuery::mode() const
{
    GstBufferingMode m;
    gst_query_parse_buffering_stats(object<GstQuery>(), &m, NULL, NULL, NULL);
    return static_cast<BufferingMode>(m);
}

int BufferingQuery::averageIn() const
{
    gint a;
    gst_query_parse_buffering_stats(object<GstQuery>(), NULL, &a, NULL, NULL);
    return a;
}

int BufferingQuery::averageOut() const
{
    gint a;
    gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, &a, NULL);
    return a;

}

qint64 BufferingQuery::bufferingLeft() const
{
    gint64 l;
    gst_query_parse_buffering_stats(object<GstQuery>(), NULL, NULL, NULL, &l);
    return l;
}
;
void BufferingQuery::setValues(BufferingMode mode, int averageIn, int averageOut,
                              qint64 bufferingLeft)
{
    gst_query_set_buffering_stats(object<GstQuery>(), static_cast<GstBufferingMode>(mode),
                                  averageIn, averageOut, bufferingLeft);
}

Format BufferingQuery::format() const
{
    GstFormat f;
    gst_query_parse_buffering_range(object<GstQuery>(), &f, NULL, NULL, NULL);
    return static_cast<Format>(f);
}

qint64 BufferingQuery::rangeStart() const
{
    gint64 r;
    gst_query_parse_buffering_range(object<GstQuery>(), NULL, &r, NULL, NULL);
    return r;
}

qint64 BufferingQuery::rangeStop() const
{
    gint64 r;
    gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, &r, NULL);
    return r;
}

qint64 BufferingQuery::estimatedTotal() const
{
    gint64 r;
    gst_query_parse_buffering_range(object<GstQuery>(), NULL, NULL, NULL, &r);
    return r;
}

void BufferingQuery::setValues(Format rangeFormat, qint64 rangeStart, qint64 rangeStop,
                              qint64 estimatedTotal)
{
    gst_query_set_buffering_range(object<GstQuery>(), static_cast<GstFormat>(rangeFormat),
                                  rangeStart, rangeStop, estimatedTotal);
}

//********************************************************

UriQueryPtr UriQuery::create()
{
    return UriQueryPtr::wrap(gst_query_new_uri(), false);
}

QUrl UriQuery::uri() const
{
    gchar *uri;
    gst_query_parse_uri(object<GstQuery>(), &uri);
    return QUrl::fromPercentEncoding(uri);
}

void UriQuery::setValue(const QUrl & uri)
{
    gst_query_set_uri(object<GstQuery>(), uri.toEncoded());
}

//********************************************************

} //namespace QGst

QGLIB_REGISTER_VALUEIMPL_IMPLEMENTATION(
    QGst::QueryPtr,
    QGst::QueryPtr::wrap(GST_QUERY(gst_value_get_mini_object(value))),
    gst_value_set_mini_object(value, GST_MINI_OBJECT(static_cast<GstQuery*>(data)))
)

QDebug operator<<(QDebug debug, QGst::QueryType type)
{
    debug.nospace() << gst_query_type_get_name(static_cast<GstQueryType>(type));
    return debug.space();
}

QDebug operator<<(QDebug debug, const QGst::QueryPtr & query)
{
    debug.nospace() << "QGst::Query(Type: " << query->type() << ")";
    return debug.space();
}

<|endoftext|>


<commit_before>AliAnalysisTaskSE *AddTaskLambdac(TString finname,Bool_t storeNtuple,Bool_t readMC,Bool_t MCPid,Bool_t realPid,Bool_t resPid,Bool_t useKF,
					 Bool_t fillVarHists=kFALSE, Bool_t priorsHists=kFALSE, Bool_t multiplicityHists=kFALSE)
{
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskLambdac", "No analysis manager to connect to.");
    return NULL;
  }

  Bool_t stdcuts=kFALSE;
  TFile* filecuts;
  if( finname.EqualTo("") ) {
    stdcuts=kTRUE;
  } else {
      filecuts=TFile::Open(finname.Data());
      if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
	AliFatal("Input file not found : check your cut object");
      }
  }
  AliRDHFCutsLctopKpi* prodcuts=new AliRDHFCutsLctopKpi();
  if(stdcuts) prodcuts->SetStandardCutsPP2010();
  else   prodcuts = (AliRDHFCutsLctopKpi*)filecuts->Get("LctopKpiProdCuts");
  prodcuts->SetName("LctopKpiProdCuts");
  prodcuts->SetMinPtCandidate(-1.);
  prodcuts->SetMaxPtCandidate(10000.);

  AliRDHFCutsLctopKpi *analysiscuts = new AliRDHFCutsLctopKpi();
  if(stdcuts) analysiscuts->SetStandardCutsPP2010();
  else analysiscuts = (AliRDHFCutsLctopKpi*)filecuts->Get("LctopKpiAnalysisCuts");
  analysiscuts->SetName("LctopKpiAnalysisCuts");
  analysiscuts->SetMinPtCandidate(-1.);
  analysiscuts->SetMaxPtCandidate(10000.);

  // Aanalysis task
  AliAnalysisTaskSELambdac *lambdacTask = new AliAnalysisTaskSELambdac("LambdacAnalysis",storeNtuple,analysiscuts,prodcuts);
  lambdacTask->SetReadMC(readMC);
  if(MCPid) lambdacTask->SetMCPid();
  if(resPid) lambdacTask->SetResonantPid();
  if(realPid) lambdacTask->SetRealPid();
  lambdacTask->SetFillVarHists(fillVarHists);
  lambdacTask->SetPriorsHists(priorsHists);
  lambdacTask->SetMultiplicityHists(multiplicityHists);
  lambdacTask->SetAnalysis(kTRUE);

  lambdacTask->SetDebugLevel(0);
  if(useKF) {
    lambdacTask->SetUseKF();
    Float_t cuts[10]={0.1,0.1,1.5,0.5,0.1,1.5,0.5,0.1,1.5,0.5};
    lambdacTask->SetCutsKF(cuts);
  }
  mgr->AddTask(lambdacTask);

  //
  // Create containers for input/output
  TString outputfile = AliAnalysisManager::GetCommonFileName();
  outputfile += ":PWG3_D2H_InvMassLambdac";

  TString finDirname="First_PbPb";
  TString inname = "cinputLc";
  TString outname = "coutputLc";
  TString cutsname = "coutputLcCuts";
  TString normname = "coutputLcNorm";
  TString ntuplename = "coutputLc2";
  TString nev2 = "coutputNev";
  TString outname2 = "coutputLambdacMC";
  TString aPrioriname = "coutputAPriori";
  TString multiplicityname = "coutputMultiplicity";
  inname += finDirname.Data();
  outname += finDirname.Data();
  cutsname += finDirname.Data();
  normname += finDirname.Data();
  ntuplename += finDirname.Data();
  nev2 += finDirname.Data();
  outname2 += finDirname.Data();
  aPrioriname += finDirname.Data();
  multiplicityname += finDirname.Data();

  TString centr=Form("%.0f%.0f",analysiscuts->GetMinCentrality(),analysiscuts->GetMaxCentrality());
  inname += centr;
  outname += centr;
  cutsname += centr;
  normname += centr;
  ntuplename += centr;
  nev2 += centr;
  outname2 += centr;
  aPrioriname += centr;
  multiplicityname += centr;

  AliAnalysisDataContainer *cinputLambdac = mgr->CreateContainer(inname,TChain::Class(),
								 AliAnalysisManager::kInputContainer);
  mgr->ConnectInput(lambdacTask,0,mgr->GetCommonInputContainer());

  AliAnalysisDataContainer *coutputLambdacCuts = mgr->CreateContainer(cutsname,TList::Class(),
								      AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,2,coutputLambdacCuts);

  AliAnalysisDataContainer *coutputLambdac = mgr->CreateContainer(outname,TList::Class(),
								  AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,1,coutputLambdac);

  AliAnalysisDataContainer *coutputLambdacMC = mgr->CreateContainer(outname2,TList::Class(),
								    AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,3,coutputLambdacMC);

  AliAnalysisDataContainer *coutputLambdacNev = mgr->CreateContainer(nev2,TH1F::Class(),
								     AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,4,coutputLambdacNev);

  AliAnalysisDataContainer *coutputAPriori = mgr->CreateContainer(aPrioriname,TList::Class(),
								  AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,5,coutputAPriori);
  AliAnalysisDataContainer *coutputMultiplicity = mgr->CreateContainer(multiplicityname,TList::Class(),
								       AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,6,coutputMultiplicity);

  AliAnalysisDataContainer *coutputLambdacNorm = mgr->CreateContainer(normname,AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());

 mgr->ConnectOutput(lambdacTask,7,coutputLambdacNorm);

  if (storeNtuple) {
    AliAnalysisDataContainer *coutputLambdac2 = mgr->CreateContainer(ntuplename,TNtuple::Class(),
								     AliAnalysisManager::kOutputContainer,"InvMassLambdac_nt1.root");
    coutputLambdac2->SetSpecialOutput();
    mgr->ConnectOutput(lambdacTask,7,coutputLambdac2);
  }

  return lambdacTask;
}
<commit_msg>Update AddTask (Rossella)<commit_after>AliAnalysisTaskSE *AddTaskLambdac(TString finname,Bool_t storeNtuple,Bool_t readMC,Bool_t MCPid,Bool_t realPid,Bool_t resPid,Bool_t useKF,
				  Bool_t fillVarHists=kFALSE, Bool_t priorsHists=kFALSE, Bool_t multiplicityHists=kFALSE, TString postname="")
{
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskLambdac", "No analysis manager to connect to.");
    return NULL;
  }

  Bool_t stdcuts=kFALSE;
  TFile* filecuts;
  if( finname.EqualTo("") ) {
    stdcuts=kTRUE;
  } else {
      filecuts=TFile::Open(finname.Data());
      if(!filecuts ||(filecuts&& !filecuts->IsOpen())){
	AliFatal("Input file not found : check your cut object");
      }
  }
  AliRDHFCutsLctopKpi* prodcuts=new AliRDHFCutsLctopKpi();
  if(stdcuts) prodcuts->SetStandardCutsPP2010();
  else   prodcuts = (AliRDHFCutsLctopKpi*)filecuts->Get("LctopKpiProdCuts");
  prodcuts->SetName("LctopKpiProdCuts");
  prodcuts->SetMinPtCandidate(-1.);
  prodcuts->SetMaxPtCandidate(10000.);

  AliRDHFCutsLctopKpi *analysiscuts = new AliRDHFCutsLctopKpi();
  if(stdcuts) analysiscuts->SetStandardCutsPP2010();
  else analysiscuts = (AliRDHFCutsLctopKpi*)filecuts->Get("LctopKpiAnalysisCuts");
  analysiscuts->SetName("LctopKpiAnalysisCuts");
  analysiscuts->SetMinPtCandidate(-1.);
  analysiscuts->SetMaxPtCandidate(10000.);

  // Aanalysis task
  AliAnalysisTaskSELambdac *lambdacTask = new AliAnalysisTaskSELambdac("LambdacAnalysis",storeNtuple,analysiscuts,prodcuts);
  lambdacTask->SetReadMC(readMC);
  if(MCPid) lambdacTask->SetMCPid();
  if(resPid) lambdacTask->SetResonantPid();
  if(realPid) lambdacTask->SetRealPid();
  lambdacTask->SetFillVarHists(fillVarHists);
  lambdacTask->SetPriorsHists(priorsHists);
  lambdacTask->SetMultiplicityHists(multiplicityHists);
  lambdacTask->SetAnalysis(kTRUE);

  lambdacTask->SetDebugLevel(0);
  if(useKF) {
    lambdacTask->SetUseKF();
    Float_t cuts[10]={0.1,0.1,1.5,0.5,0.1,1.5,0.5,0.1,1.5,0.5};
    lambdacTask->SetCutsKF(cuts);
  }
  mgr->AddTask(lambdacTask);

  //
  // Create containers for input/output
  TString outputfile = AliAnalysisManager::GetCommonFileName();
  outputfile += ":PWG3_D2H_InvMassLambdac";

  TString finDirname="pp";
  TString inname = "cinputLc";
  TString outname = "coutputLc";
  TString cutsname = "coutputLcCuts";
  TString normname = "coutputLcNorm";
  TString ntuplename = "coutputLc2";
  TString nev2 = "coutputNev";
  TString outname2 = "coutputLambdacMC";
  TString aPrioriname = "coutputAPriori";
  TString multiplicityname = "coutputMultiplicity";
  inname += finDirname.Data();
  outname += finDirname.Data();
  cutsname += finDirname.Data();
  normname += finDirname.Data();
  ntuplename += finDirname.Data();
  nev2 += finDirname.Data();
  outname2 += finDirname.Data();
  aPrioriname += finDirname.Data();
  multiplicityname += finDirname.Data();

  inname +=  postname.Data();
  outname +=  postname.Data();
  cutsname +=  postname.Data();
  normname += postname.Data();
  ntuplename +=  postname.Data();
  nev2 +=  postname.Data();
  outname2 +=  postname.Data();
  aPrioriname +=  postname.Data();
  multiplicityname +=  postname.Data();

  AliAnalysisDataContainer *cinputLambdac = mgr->CreateContainer(inname,TChain::Class(),
								 AliAnalysisManager::kInputContainer);
  mgr->ConnectInput(lambdacTask,0,mgr->GetCommonInputContainer());

  AliAnalysisDataContainer *coutputLambdacCuts = mgr->CreateContainer(cutsname,TList::Class(),
								      AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,2,coutputLambdacCuts);

  AliAnalysisDataContainer *coutputLambdac = mgr->CreateContainer(outname,TList::Class(),
								  AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,1,coutputLambdac);

  AliAnalysisDataContainer *coutputLambdacMC = mgr->CreateContainer(outname2,TList::Class(),
								    AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,3,coutputLambdacMC);

  AliAnalysisDataContainer *coutputLambdacNev = mgr->CreateContainer(nev2,TH1F::Class(),
								     AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,4,coutputLambdacNev);

  AliAnalysisDataContainer *coutputAPriori = mgr->CreateContainer(aPrioriname,TList::Class(),
								  AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,5,coutputAPriori);
  AliAnalysisDataContainer *coutputMultiplicity = mgr->CreateContainer(multiplicityname,TList::Class(),
								       AliAnalysisManager::kOutputContainer,outputfile.Data());
  mgr->ConnectOutput(lambdacTask,6,coutputMultiplicity);

  AliAnalysisDataContainer *coutputLambdacNorm = mgr->CreateContainer(normname,AliNormalizationCounter::Class(),AliAnalysisManager::kOutputContainer,outputfile.Data());

 mgr->ConnectOutput(lambdacTask,7,coutputLambdacNorm);

  if (storeNtuple) {
    AliAnalysisDataContainer *coutputLambdac2 = mgr->CreateContainer(ntuplename,TNtuple::Class(),
								     AliAnalysisManager::kOutputContainer,"InvMassLambdac_nt1.root");
    coutputLambdac2->SetSpecialOutput();
    mgr->ConnectOutput(lambdacTask,7,coutputLambdac2);
  }

  return lambdacTask;
}
<|endoftext|>