<commit_before>// $Id$

AliEmcalPhysicsSelectionTask* AddTaskEmcalPhysicsSelection(
  Bool_t exFOnly,
  Bool_t wHistos   = kTRUE,
  UInt_t triggers  = 0,
  Double_t minE    = -1,
  Double_t minPt   = -1,
  Double_t vz      = -1,
  Bool_t vzdiff    = kFALSE,
  Double_t cmin    = -1,
  Double_t cmax    = -1,
  Double_t minCellTrackScale = -1,
  Double_t maxCellTrackScale = -1
)
{
  // Add EMCAL physics selection task.

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEmcalPhysicsSelection", "No analysis manager found.");
    return 0;
  }

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskEmcalPhysicsSelection", "This task requires an input event handler");
    return NULL;
  }

  Bool_t isMC = (mgr->GetMCtruthEventHandler()) ? kTRUE:kFALSE;
  AliEmcalPhysicsSelectionTask *pseltask = new AliEmcalPhysicsSelectionTask("EmcalPSel");
  pseltask->SetDoWriteHistos(wHistos);
  AliEmcalPhysicsSelection *physSel = static_cast<AliEmcalPhysicsSelection*>(pseltask->GetPhysicsSelection());
  if (physSel) {
    physSel->SetSkipFastOnly(exFOnly);
    if (isMC)
      physSel->SetAnalyzeMC();
    physSel->SetClusMinE(minE);
    physSel->SetTrackMinPt(minPt);
    physSel->SetTriggers(triggers);
    physSel->SetCentRange(cmin,cmax);
    physSel->SetZVertex(vz);
    physSel->SetCheckZvertexDiff(vzdiff);
    physSel->SetCellTrackScale(minCellTrackScale,maxCellTrackScale);
  } else {
    ::Error("AddTaskEmcalPhysicsSelection", "No AliEmcalPhysicsSelection object found.");
  }

  mgr->AddTask(pseltask);

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput = mgr->CreateContainer("cstatsout",
                TList::Class(),
                AliAnalysisManager::kOutputContainer,
                "EventStat_temp.root");

  mgr->ConnectInput(pseltask,  0, cinput);
  mgr->ConnectOutput(pseltask, 1, coutput);

  return pseltask;
}
<commit_msg>Added a bypass variable in the AddTaskEmcalPhysicsSelection macro<commit_after>// $Id$

AliEmcalPhysicsSelectionTask* AddTaskEmcalPhysicsSelection(
  Bool_t exFOnly,
  Bool_t wHistos   = kTRUE,
  UInt_t triggers  = 0,
  Double_t minE    = -1,
  Double_t minPt   = -1,
  Double_t vz      = -1,
  Bool_t vzdiff    = kFALSE,
  Double_t cmin    = -1,
  Double_t cmax    = -1,
  Double_t minCellTrackScale = -1,
  Double_t maxCellTrackScale = -1,
  Bool_t byPassPhysSelTask = kFALSE
)
{
  if(byPassPhysSelTask)
    return 0;

  // Add EMCAL physics selection task.

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskEmcalPhysicsSelection", "No analysis manager found.");
    return 0;
  }

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskEmcalPhysicsSelection", "This task requires an input event handler");
    return NULL;
  }

  Bool_t isMC = (mgr->GetMCtruthEventHandler()) ? kTRUE:kFALSE;
  AliEmcalPhysicsSelectionTask *pseltask = new AliEmcalPhysicsSelectionTask("EmcalPSel");
  pseltask->SetDoWriteHistos(wHistos);
  AliEmcalPhysicsSelection *physSel = static_cast<AliEmcalPhysicsSelection*>(pseltask->GetPhysicsSelection());
  if (physSel) {
    physSel->SetSkipFastOnly(exFOnly);
    if (isMC)
      physSel->SetAnalyzeMC();
    physSel->SetClusMinE(minE);
    physSel->SetTrackMinPt(minPt);
    physSel->SetTriggers(triggers);
    physSel->SetCentRange(cmin,cmax);
    physSel->SetZVertex(vz);
    physSel->SetCheckZvertexDiff(vzdiff);
    physSel->SetCellTrackScale(minCellTrackScale,maxCellTrackScale);
  } else {
    ::Error("AddTaskEmcalPhysicsSelection", "No AliEmcalPhysicsSelection object found.");
  }

  mgr->AddTask(pseltask);

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput = mgr->CreateContainer("cstatsout",
                TList::Class(),
                AliAnalysisManager::kOutputContainer,
                "EventStat_temp.root");

  mgr->ConnectInput(pseltask,  0, cinput);
  mgr->ConnectOutput(pseltask, 1, coutput);

  return pseltask;
}
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 6/14/2020, 3:06:06 AM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i{2LL}; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i{1LL}; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "0" << endl;
  exit(0);
}

// ----- Solve -----

constexpr int C{18};

ll comb(ll n, ll k)
{
  ll ans{1};
  for (auto i{0LL}; i < k; ++i)
  {
    ans *= n - i;
    ans /= i + 1;
  }
  return ans;
}

class Solve
{
  int N, S, T;
  int M;
  ll K;
  vector<int> A;

public:
  Solve(int N) : N{N}, A(N)
  {
    cin >> K >> S >> T;
    for (auto i{0}; i < N; ++i)
    {
      cin >> A[i];
    }
#if DEBUG == 1
    cerr << "N = " << N << endl;
    for (auto i{0}; i < N; ++i)
    {
      cerr << "A[" << i << "] = " << A[i] << endl;
    }
#endif
    normalize();
#if DEBUG == 1
    cerr << "N = " << N << endl;
    for (auto i{0}; i < N; ++i)
    {
      cerr << "A[" << i << "] = " << A[i] << endl;
    }
    cerr << "M = " << M << endl;
#endif
  }

  void flush()
  {
    ll ans{0};
    for (auto mask{0}; mask < 1 << M; ++mask)
    {
      if (popcount(mask) & 1)
      {
        ans -= calc(mask);
      }
      else
      {
        ans += calc(mask);
      }
    }
    cout << ans << endl;
  }

private:
  ll calc(int mask)
  {
    map<int, ll> X;
    for (auto i{0}; i < N; ++i)
    {
      int tmp{A[i] & mask};
      X[tmp];
      X[tmp]++;
    }
    ll ans{1};
    for (auto [mask, cnt] : X)
    {
      for (auto i{1}; i <= min(K, cnt); ++i)
      {
        ans += comb(cnt, i);
      }
    }
    return ans;
  }

  void normalize()
  {
    vector<bool> ok(N, true);
    for (auto i{0}; i < C; ++i)
    {
      auto s{static_cast<bool>(S >> i & 1)};
      auto t{static_cast<bool>(T >> i & 1)};
      if (s && !t)
      {
        No();
      }
      if (s ^ !t)
      {
        for (auto j{0}; j < N; ++j)
        {
          if ((A[j] >> i & 1) != static_cast<int>(s))
          {
            ok[j] = false;
          }
        }
      }
    }
    vector<int> B;
    for (auto i{0}; i < C; ++i)
    {
      if (ok[i])
      {
        B.push_back(A[i]);
      }
    }
#if DEBUG == 1
    cerr << "B.size() = " << B.size() << endl;
#endif
    swap(A, B);
    N = static_cast<int>(A.size());
    int k{0};
    B = vector<int>(N, 0);
    for (auto i{0}; i < C; ++i)
    {
      auto s{static_cast<bool>(S >> i & 1)};
      auto t{static_cast<bool>(T >> i & 1)};
      if (!(!s && t))
      {
        continue;
      }
      for (auto j{0}; j < N; ++j)
      {
        B[j] |= (A[j] >> i & 1) << k;
      }
      ++k;
    }
    swap(A, B);
    M = k;
  }
};

// ----- main() -----

int main()
{
  int N;
  cin >> N;
  Solve solve(N);
  solve.flush();
}
<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 6/14/2020, 3:06:06 AM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i{2LL}; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i{1LL}; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "0" << endl;
  exit(0);
}

// ----- Solve -----

constexpr int C{18};

ll comb(ll n, ll k)
{
  ll ans{1};
  for (auto i{0LL}; i < k; ++i)
  {
    ans *= n - i;
    ans /= i + 1;
  }
  return ans;
}

class Solve
{
  int N, S, T;
  int M;
  ll K;
  vector<int> A;

public:
  Solve(int N) : N{N}, A(N)
  {
    cin >> K >> S >> T;
    for (auto i{0}; i < N; ++i)
    {
      cin >> A[i];
    }
#if DEBUG == 1
    cerr << "N = " << N << endl;
    for (auto i{0}; i < N; ++i)
    {
      cerr << "A[" << i << "] = " << A[i] << endl;
    }
#endif
    normalize();
#if DEBUG == 1
    cerr << "N = " << N << endl;
    for (auto i{0}; i < N; ++i)
    {
      cerr << "A[" << i << "] = " << A[i] << endl;
    }
    cerr << "M = " << M << endl;
#endif
  }

  void flush()
  {
    ll ans{0};
    for (auto mask{0}; mask < 1 << M; ++mask)
    {
      if (popcount(mask) & 1)
      {
        ans -= calc(mask);
      }
      else
      {
        ans += calc(mask);
      }
    }
    cout << ans << endl;
  }

private:
  ll calc(int mask)
  {
    map<int, ll> X;
    for (auto i{0}; i < N; ++i)
    {
      int tmp{A[i] & mask};
      X[tmp];
      X[tmp]++;
    }
    ll ans{1};
    for (auto [mask, cnt] : X)
    {
      for (auto i{1}; i <= min(K, cnt); ++i)
      {
        ans += comb(cnt, i);
      }
    }
    return ans;
  }

  void normalize()
  {
    vector<bool> ok(N, true);
    for (auto i{0}; i < C; ++i)
    {
      auto s{static_cast<bool>(S >> i & 1)};
      auto t{static_cast<bool>(T >> i & 1)};
      if (s && !t)
      {
        No();
      }
      if (s ^ !t)
      {
        for (auto j{0}; j < N; ++j)
        {
          if ((A[j] >> i & 1) != static_cast<int>(s))
          {
            ok[j] = false;
          }
        }
      }
    }
    vector<int> B;
#if DEBUG == 1
    cerr << "B.size() = " << B.size() << endl;
#endif
    for (auto i{0}; i < C; ++i)
    {
      if (ok[i])
      {
        B.push_back(A[i]);
      }
    }
#if DEBUG == 1
    cerr << "B.size() = " << B.size() << endl;
#endif
    swap(A, B);
    N = static_cast<int>(A.size());
    int k{0};
    B = vector<int>(N, 0);
    for (auto i{0}; i < C; ++i)
    {
      auto s{static_cast<bool>(S >> i & 1)};
      auto t{static_cast<bool>(T >> i & 1)};
      if (!(!s && t))
      {
        continue;
      }
      for (auto j{0}; j < N; ++j)
      {
        B[j] |= (A[j] >> i & 1) << k;
      }
      ++k;
    }
    swap(A, B);
    M = k;
  }
};

// ----- main() -----

int main()
{
  int N;
  cin >> N;
  Solve solve(N);
  solve.flush();
}
<|endoftext|>


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

#include "net/proxy/proxy_resolver_mac.h"

#include <CoreFoundation/CoreFoundation.h>

#include "base/logging.h"
#include "base/mac/foundation_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "net/base/net_errors.h"
#include "net/proxy/proxy_info.h"
#include "net/proxy/proxy_server.h"

#if defined(OS_IOS)
#include <CFNetwork/CFProxySupport.h>
#else
#include <CoreServices/CoreServices.h>
#endif

namespace {

// Utility function to map a CFProxyType to a ProxyServer::Scheme.
// If the type is unknown, returns ProxyServer::SCHEME_INVALID.
net::ProxyServer::Scheme GetProxyServerScheme(CFStringRef proxy_type) {
  if (CFEqual(proxy_type, kCFProxyTypeNone))
    return net::ProxyServer::SCHEME_DIRECT;
  if (CFEqual(proxy_type, kCFProxyTypeHTTP))
    return net::ProxyServer::SCHEME_HTTP;
  if (CFEqual(proxy_type, kCFProxyTypeHTTPS)) {
    // The "HTTPS" on the Mac side here means "proxy applies to https://" URLs;
    // the proxy itself is still expected to be an HTTP proxy.
    return net::ProxyServer::SCHEME_HTTP;
  }
  if (CFEqual(proxy_type, kCFProxyTypeSOCKS)) {
    // We can't tell whether this was v4 or v5. We will assume it is
    // v5 since that is the only version OS X supports.
    return net::ProxyServer::SCHEME_SOCKS5;
  }
  return net::ProxyServer::SCHEME_INVALID;
}

// Callback for CFNetworkExecuteProxyAutoConfigurationURL. |client| is a pointer
// to a CFTypeRef.  This stashes either |error| or |proxies| in that location.
void ResultCallback(void* client, CFArrayRef proxies, CFErrorRef error) {
  DCHECK((proxies != NULL) == (error == NULL));

  CFTypeRef* result_ptr = reinterpret_cast<CFTypeRef*>(client);
  DCHECK(result_ptr != NULL);
  DCHECK(*result_ptr == NULL);

  if (error != NULL) {
    *result_ptr = CFRetain(error);
  } else {
    *result_ptr = CFRetain(proxies);
  }
  CFRunLoopStop(CFRunLoopGetCurrent());
}

}  // namespace

namespace net {

ProxyResolverMac::ProxyResolverMac()
    : ProxyResolver(false /*expects_pac_bytes*/) {
}

ProxyResolverMac::~ProxyResolverMac() {}

// Gets the proxy information for a query URL from a PAC. Implementation
// inspired by http://developer.apple.com/samplecode/CFProxySupportTool/
int ProxyResolverMac::GetProxyForURL(const GURL& query_url,
                                     ProxyInfo* results,
                                     const CompletionCallback& /*callback*/,
                                     RequestHandle* /*request*/,
                                     const BoundNetLog& net_log) {
  base::ScopedCFTypeRef<CFStringRef> query_ref(
      base::SysUTF8ToCFStringRef(query_url.spec()));
  base::ScopedCFTypeRef<CFURLRef> query_url_ref(
      CFURLCreateWithString(kCFAllocatorDefault, query_ref.get(), NULL));
  if (!query_url_ref.get())
    return ERR_FAILED;
  base::ScopedCFTypeRef<CFStringRef> pac_ref(base::SysUTF8ToCFStringRef(
      script_data_->type() == ProxyResolverScriptData::TYPE_AUTO_DETECT
          ? std::string()
          : script_data_->url().spec()));
  base::ScopedCFTypeRef<CFURLRef> pac_url_ref(
      CFURLCreateWithString(kCFAllocatorDefault, pac_ref.get(), NULL));
  if (!pac_url_ref.get())
    return ERR_FAILED;

  // Work around <rdar://problem/5530166>. This dummy call to
  // CFNetworkCopyProxiesForURL initializes some state within CFNetwork that is
  // required by CFNetworkExecuteProxyAutoConfigurationURL.

  CFArrayRef dummy_result = CFNetworkCopyProxiesForURL(query_url_ref.get(),
                                                       NULL);
  if (dummy_result)
    CFRelease(dummy_result);

  // We cheat here. We need to act as if we were synchronous, so we pump the
  // runloop ourselves. Our caller moved us to a new thread anyway, so this is
  // OK to do. (BTW, CFNetworkExecuteProxyAutoConfigurationURL returns a
  // runloop source we need to release despite its name.)

  CFTypeRef result = NULL;
  CFStreamClientContext context = { 0, &result, NULL, NULL, NULL };
  base::ScopedCFTypeRef<CFRunLoopSourceRef> runloop_source(
      CFNetworkExecuteProxyAutoConfigurationURL(
          pac_url_ref.get(), query_url_ref.get(), ResultCallback, &context));
  if (!runloop_source)
    return ERR_FAILED;

  const CFStringRef private_runloop_mode =
      CFSTR("org.chromium.ProxyResolverMac");

  CFRunLoopAddSource(CFRunLoopGetCurrent(), runloop_source.get(),
                     private_runloop_mode);
  CFRunLoopRunInMode(private_runloop_mode, DBL_MAX, false);
  CFRunLoopRemoveSource(CFRunLoopGetCurrent(), runloop_source.get(),
                        private_runloop_mode);
  DCHECK(result != NULL);

  if (CFGetTypeID(result) == CFErrorGetTypeID()) {
    // TODO(avi): do something better than this
    CFRelease(result);
    return ERR_FAILED;
  }
  base::ScopedCFTypeRef<CFArrayRef> proxy_array_ref(
      base::mac::CFCastStrict<CFArrayRef>(result));
  DCHECK(proxy_array_ref != NULL);

  // This string will be an ordered list of <proxy-uri> entries, separated by
  // semi-colons. It is the format that ProxyInfo::UseNamedProxy() expects.
  //    proxy-uri = [<proxy-scheme>"://"]<proxy-host>":"<proxy-port>
  // (This also includes entries for direct connection, as "direct://").
  std::string proxy_uri_list;

  CFIndex proxy_array_count = CFArrayGetCount(proxy_array_ref.get());
  for (CFIndex i = 0; i < proxy_array_count; ++i) {
    CFDictionaryRef proxy_dictionary = base::mac::CFCastStrict<CFDictionaryRef>(
        CFArrayGetValueAtIndex(proxy_array_ref.get(), i));
    DCHECK(proxy_dictionary != NULL);

    // The dictionary may have the following keys:
    // - kCFProxyTypeKey : The type of the proxy
    // - kCFProxyHostNameKey
    // - kCFProxyPortNumberKey : The meat we're after.
    // - kCFProxyUsernameKey
    // - kCFProxyPasswordKey : Despite the existence of these keys in the
    //                         documentation, they're never populated. Even if a
    //                         username/password were to be set in the network
    //                         proxy system preferences, we'd need to fetch it
    //                         from the Keychain ourselves. CFProxy is such a
    //                         tease.
    // - kCFProxyAutoConfigurationURLKey : If the PAC file specifies another
    //                                     PAC file, I'm going home.

    CFStringRef proxy_type = base::mac::GetValueFromDictionary<CFStringRef>(
        proxy_dictionary, kCFProxyTypeKey);
    ProxyServer proxy_server = ProxyServer::FromDictionary(
        GetProxyServerScheme(proxy_type),
        proxy_dictionary,
        kCFProxyHostNameKey,
        kCFProxyPortNumberKey);
    if (!proxy_server.is_valid())
      continue;

    if (!proxy_uri_list.empty())
      proxy_uri_list += ";";
    proxy_uri_list += proxy_server.ToURI();
  }

  if (!proxy_uri_list.empty())
    results->UseNamedProxy(proxy_uri_list);
  // Else do nothing (results is already guaranteed to be in the default state).

  return OK;
}

void ProxyResolverMac::CancelRequest(RequestHandle request) {
  NOTREACHED();
}

LoadState ProxyResolverMac::GetLoadState(RequestHandle request) const {
  NOTREACHED();
  return LOAD_STATE_IDLE;
}

void ProxyResolverMac::CancelSetPacScript() {
  NOTREACHED();
}

int ProxyResolverMac::SetPacScript(
    const scoped_refptr<ProxyResolverScriptData>& script_data,
    const CompletionCallback& /*callback*/) {
  script_data_ = script_data;
  return OK;
}

}  // namespace net
<commit_msg>ProxyResolverMac: invalidate resolver source.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/proxy/proxy_resolver_mac.h"

#include <CoreFoundation/CoreFoundation.h>

#include "base/logging.h"
#include "base/mac/foundation_util.h"
#include "base/mac/scoped_cftyperef.h"
#include "base/strings/string_util.h"
#include "base/strings/sys_string_conversions.h"
#include "net/base/net_errors.h"
#include "net/proxy/proxy_info.h"
#include "net/proxy/proxy_server.h"

#if defined(OS_IOS)
#include <CFNetwork/CFProxySupport.h>
#else
#include <CoreServices/CoreServices.h>
#endif

namespace {

// Utility function to map a CFProxyType to a ProxyServer::Scheme.
// If the type is unknown, returns ProxyServer::SCHEME_INVALID.
net::ProxyServer::Scheme GetProxyServerScheme(CFStringRef proxy_type) {
  if (CFEqual(proxy_type, kCFProxyTypeNone))
    return net::ProxyServer::SCHEME_DIRECT;
  if (CFEqual(proxy_type, kCFProxyTypeHTTP))
    return net::ProxyServer::SCHEME_HTTP;
  if (CFEqual(proxy_type, kCFProxyTypeHTTPS)) {
    // The "HTTPS" on the Mac side here means "proxy applies to https://" URLs;
    // the proxy itself is still expected to be an HTTP proxy.
    return net::ProxyServer::SCHEME_HTTP;
  }
  if (CFEqual(proxy_type, kCFProxyTypeSOCKS)) {
    // We can't tell whether this was v4 or v5. We will assume it is
    // v5 since that is the only version OS X supports.
    return net::ProxyServer::SCHEME_SOCKS5;
  }
  return net::ProxyServer::SCHEME_INVALID;
}

// Callback for CFNetworkExecuteProxyAutoConfigurationURL. |client| is a pointer
// to a CFTypeRef.  This stashes either |error| or |proxies| in that location.
void ResultCallback(void* client, CFArrayRef proxies, CFErrorRef error) {
  DCHECK((proxies != NULL) == (error == NULL));

  CFTypeRef* result_ptr = reinterpret_cast<CFTypeRef*>(client);
  DCHECK(result_ptr != NULL);
  DCHECK(*result_ptr == NULL);

  if (error != NULL) {
    *result_ptr = CFRetain(error);
  } else {
    *result_ptr = CFRetain(proxies);
  }
  CFRunLoopStop(CFRunLoopGetCurrent());
}

}  // namespace

namespace net {

ProxyResolverMac::ProxyResolverMac()
    : ProxyResolver(false /*expects_pac_bytes*/) {
}

ProxyResolverMac::~ProxyResolverMac() {}

// Gets the proxy information for a query URL from a PAC. Implementation
// inspired by http://developer.apple.com/samplecode/CFProxySupportTool/
int ProxyResolverMac::GetProxyForURL(const GURL& query_url,
                                     ProxyInfo* results,
                                     const CompletionCallback& /*callback*/,
                                     RequestHandle* /*request*/,
                                     const BoundNetLog& net_log) {
  base::ScopedCFTypeRef<CFStringRef> query_ref(
      base::SysUTF8ToCFStringRef(query_url.spec()));
  base::ScopedCFTypeRef<CFURLRef> query_url_ref(
      CFURLCreateWithString(kCFAllocatorDefault, query_ref.get(), NULL));
  if (!query_url_ref.get())
    return ERR_FAILED;
  base::ScopedCFTypeRef<CFStringRef> pac_ref(base::SysUTF8ToCFStringRef(
      script_data_->type() == ProxyResolverScriptData::TYPE_AUTO_DETECT
          ? std::string()
          : script_data_->url().spec()));
  base::ScopedCFTypeRef<CFURLRef> pac_url_ref(
      CFURLCreateWithString(kCFAllocatorDefault, pac_ref.get(), NULL));
  if (!pac_url_ref.get())
    return ERR_FAILED;

  // Work around <rdar://problem/5530166>. This dummy call to
  // CFNetworkCopyProxiesForURL initializes some state within CFNetwork that is
  // required by CFNetworkExecuteProxyAutoConfigurationURL.

  CFArrayRef dummy_result = CFNetworkCopyProxiesForURL(query_url_ref.get(),
                                                       NULL);
  if (dummy_result)
    CFRelease(dummy_result);

  // We cheat here. We need to act as if we were synchronous, so we pump the
  // runloop ourselves. Our caller moved us to a new thread anyway, so this is
  // OK to do. (BTW, CFNetworkExecuteProxyAutoConfigurationURL returns a
  // runloop source we need to release despite its name.)

  CFTypeRef result = NULL;
  CFStreamClientContext context = { 0, &result, NULL, NULL, NULL };
  base::ScopedCFTypeRef<CFRunLoopSourceRef> runloop_source(
      CFNetworkExecuteProxyAutoConfigurationURL(
          pac_url_ref.get(), query_url_ref.get(), ResultCallback, &context));
  if (!runloop_source)
    return ERR_FAILED;

  const CFStringRef private_runloop_mode =
      CFSTR("org.chromium.ProxyResolverMac");

  CFRunLoopAddSource(CFRunLoopGetCurrent(), runloop_source.get(),
                     private_runloop_mode);
  CFRunLoopRunInMode(private_runloop_mode, DBL_MAX, false);
  CFRunLoopSourceInvalidate(runloop_source.get());
  DCHECK(result != NULL);

  if (CFGetTypeID(result) == CFErrorGetTypeID()) {
    // TODO(avi): do something better than this
    CFRelease(result);
    return ERR_FAILED;
  }
  base::ScopedCFTypeRef<CFArrayRef> proxy_array_ref(
      base::mac::CFCastStrict<CFArrayRef>(result));
  DCHECK(proxy_array_ref != NULL);

  // This string will be an ordered list of <proxy-uri> entries, separated by
  // semi-colons. It is the format that ProxyInfo::UseNamedProxy() expects.
  //    proxy-uri = [<proxy-scheme>"://"]<proxy-host>":"<proxy-port>
  // (This also includes entries for direct connection, as "direct://").
  std::string proxy_uri_list;

  CFIndex proxy_array_count = CFArrayGetCount(proxy_array_ref.get());
  for (CFIndex i = 0; i < proxy_array_count; ++i) {
    CFDictionaryRef proxy_dictionary = base::mac::CFCastStrict<CFDictionaryRef>(
        CFArrayGetValueAtIndex(proxy_array_ref.get(), i));
    DCHECK(proxy_dictionary != NULL);

    // The dictionary may have the following keys:
    // - kCFProxyTypeKey : The type of the proxy
    // - kCFProxyHostNameKey
    // - kCFProxyPortNumberKey : The meat we're after.
    // - kCFProxyUsernameKey
    // - kCFProxyPasswordKey : Despite the existence of these keys in the
    //                         documentation, they're never populated. Even if a
    //                         username/password were to be set in the network
    //                         proxy system preferences, we'd need to fetch it
    //                         from the Keychain ourselves. CFProxy is such a
    //                         tease.
    // - kCFProxyAutoConfigurationURLKey : If the PAC file specifies another
    //                                     PAC file, I'm going home.

    CFStringRef proxy_type = base::mac::GetValueFromDictionary<CFStringRef>(
        proxy_dictionary, kCFProxyTypeKey);
    ProxyServer proxy_server = ProxyServer::FromDictionary(
        GetProxyServerScheme(proxy_type),
        proxy_dictionary,
        kCFProxyHostNameKey,
        kCFProxyPortNumberKey);
    if (!proxy_server.is_valid())
      continue;

    if (!proxy_uri_list.empty())
      proxy_uri_list += ";";
    proxy_uri_list += proxy_server.ToURI();
  }

  if (!proxy_uri_list.empty())
    results->UseNamedProxy(proxy_uri_list);
  // Else do nothing (results is already guaranteed to be in the default state).

  return OK;
}

void ProxyResolverMac::CancelRequest(RequestHandle request) {
  NOTREACHED();
}

LoadState ProxyResolverMac::GetLoadState(RequestHandle request) const {
  NOTREACHED();
  return LOAD_STATE_IDLE;
}

void ProxyResolverMac::CancelSetPacScript() {
  NOTREACHED();
}

int ProxyResolverMac::SetPacScript(
    const scoped_refptr<ProxyResolverScriptData>& script_data,
    const CompletionCallback& /*callback*/) {
  script_data_ = script_data;
  return OK;
}

}  // namespace net
<|endoftext|>


<commit_before>#include <iostream>
#include <math.h>

using namespace std;

class Mortgage {

public:
    void setLoanAmount(float amount) {
        this->loanAmount = amount;
    }
    void setInterestRate(float rate) {
        this->interestRate = rate * Mortgage::HUNDRED;
    }
    void setYears(float years) {
        this->numYears = years;
    }
    float getMonthlyPayment() {
        this->payment();
        return this->monthlyPayment;
    }

private:

    const float NUM_MONTHS = 12.0;  // Number of months in a year.
    const float ONE = 1.0;          // Const for one.
    const float HUNDRED = 100.0;    // Const for one hundred.

    float monthlyPayment = 0.0;     // Monthly Payment.
    float loanAmount = 0.0;         // The dollar amount of the loan.
    float interestRate = 0.0;       // The annual interest rate.
    float numYears = 0.0;           // The number of years of the loan.

    void payment() {
        // This function will calculate the monthly payment on a home loan.
        // Required Set: loanAmount, interestRate, numYears.
        this->monthlyPayment = (this->loanAmount * (this->interestRate / Mortgage::NUM_MONTHS) * this->term()) / (this->term() - Mortgage::ONE);
    }

    float term() {
        // Required Set: interestRate, numYears.
        return pow(Mortgage::ONE + (this->interestRate / Mortgage::NUM_MONTHS), (Mortgage::NUM_MONTHS * this->numYears));
    }

    bool checkInput(float input) {
        if (input < 0) {
            return false;
        }
        else {
            return true;
        }
    }

};

int main() {

    float years, rate, amount;

    Mortgage homeLoan;

    cout << "Loan Amount: $";
    cin >> amount;

    cout << "Interest Rate: %";
    cin >> rate;

    cout << "Number of Years for Loan: ";
    cin >> years;

    homeLoan.setInterestRate(rate);
    homeLoan.setLoanAmount(amount);
    homeLoan.setYears(years);

    cout.precision(2);

    cout << "Monthly Payment = $" << fixed << homeLoan.getMonthlyPayment();

    return 0;
}
<commit_msg>Update Homework-2.cpp<commit_after>//
//  main.cpp
//  HW3
//
//  Created by Vinlock on 1/28/16.
//  Copyright © 2016 PvP All Day. All rights reserved.
//

#include <iostream>
#include <math.h>

using namespace std;

class Mortgage {

public:
    void setLoanAmount(float amount) {
        this->loanAmount = amount;
    }
    void setInterestRate(float rate) {
        this->interestRate = rate / Mortgage::HUNDRED;
    }
    void setYears(float years) {
        this->numYears = years;
    }
    float getMonthlyPayment() {
        this->payment();
        return this->monthlyPayment;
    }

private:

    const float NUM_MONTHS = 12.0;  // Number of months in a year.
    const float ONE = 1.0;          // Const for one.
    const float HUNDRED = 100.0;    // Const for one hundred.

    float monthlyPayment = 0.0;     // Monthly Payment.
    float loanAmount = 0.0;         // The dollar amount of the loan.
    float interestRate = 0.0;       // The annual interest rate.
    float numYears = 0.0;           // The number of years of the loan.

    void payment() {
        // This function will calculate the monthly payment on a home loan.
        // Required Set: loanAmount, interestRate, numYears.
        this->monthlyPayment = (this->loanAmount * (this->interestRate / Mortgage::NUM_MONTHS) * this->term()) / (this->term() - Mortgage::ONE);
    }

    float term() {
        // Required Set: interestRate, numYears.
        return pow(Mortgage::ONE + (this->interestRate / Mortgage::NUM_MONTHS), (Mortgage::NUM_MONTHS * this->numYears));
    }

    bool checkInput(float input) {
        if (input < 0) {
            return false;
        }
        else {
            return true;
        }
    }

};

int main() {

    float years, rate, amount;

    Mortgage homeLoan;

    cout << "Loan Amount: $";
    cin >> amount;

    cout << "Interest Rate (Percent): %";
    cin >> rate;

    cout << "Number of Years for Loan: ";
    cin >> years;

    homeLoan.setInterestRate(rate);
    homeLoan.setLoanAmount(amount);
    homeLoan.setYears(years);

    cout.precision(2);

    cout << "Monthly Payment = $" << fixed << homeLoan.getMonthlyPayment();

    return 0;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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 "selxSuperElastixFilter.h"
#include "selxAnyFileReader.h"
#include "selxAnyFileWriter.h"
#include "selxLogger.h"

#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <stdexcept>

template< class T >
std::ostream &
operator<<( std::ostream & os, const std::vector< T > & v )
{
  std::copy( v.begin(), v.end(), std::ostream_iterator< T >( os, " " ) );
  return os;
}

namespace selx
{
  // helper function to parse command line arguments for log level
  std::istream& operator>>(std::istream& in, selx::LogLevel& loglevel)
  {
    std::string token;
    in >> token;
    if (token == "off")
      loglevel = selx::LogLevel::OFF;
    else if (token == "critical")
      loglevel = selx::LogLevel::CRT;
    else if (token == "error")
      loglevel = selx::LogLevel::ERR;
    else if (token == "warning")
      loglevel = selx::LogLevel::WRN;
    else if (token == "info")
      loglevel = selx::LogLevel::INF;
    else if (token == "debug")
      loglevel = selx::LogLevel::DBG;
    else if (token == "trace")
      loglevel = selx::LogLevel::TRC;
    else
      in.setstate(std::ios_base::failbit);
    return in;
  }
}

int
main( int ac, char * av[] )
{

  selx::Logger::Pointer logger = selx::Logger::New();
  logger->AddStream( "cout", std::cout );
  logger->SetLogLevel( selx::LogLevel::TRC );

  try
  {
    typedef std::vector< std::string > VectorOfStringsType;
    typedef std::vector< boost::filesystem::path > VectorOfPathsType;

    boost::filesystem::path logPath;
    // default log level
    selx::LogLevel logLevel = selx::LogLevel::WRN;

    boost::filesystem::path            configurationPath;
    VectorOfPathsType                   configurationPaths;

    VectorOfStringsType inputPairs;
    VectorOfStringsType outputPairs;

    boost::program_options::options_description desc("Allowed options");
    desc.add_options()
      ( "help", "produce help message" )
      ("conf", boost::program_options::value< VectorOfPathsType >(&configurationPaths)->required()->multitoken(), "Configuration file")
      ("in", boost::program_options::value< VectorOfStringsType >(&inputPairs)->multitoken(), "Input data: images, labels, meshes, etc. Usage <name>=<path>")
      ("out", boost::program_options::value< VectorOfStringsType >(&outputPairs)->multitoken(), "Output data: images, labels, meshes, etc. Usage <name>=<path>")
      ("graphout", boost::program_options::value< boost::filesystem::path >(), "Output Graphviz dot file")
      ("logfile", boost::program_options::value< boost::filesystem::path >(&logPath), "Log output file")
      ("loglevel", boost::program_options::value< selx::LogLevel >(&logLevel), "Log level")
      ;

    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::parse_command_line(ac, av, desc), vm);
    boost::program_options::notify(vm);

    if( vm.count( "help" ) )
    {
      std::cout << desc << "\n";
      return 0;
    }

    // optionally, stream to log file
    std::ofstream outfile;
    if ( vm.count("logfile") )
    {
      outfile =  std::ofstream(logPath.c_str());
      logger->AddStream("logfile", outfile);
    }

    logger->AddStream("SELXcout", std::cout);
    logger->SetLogLevel(logLevel);

    // instantiate a SuperElastixFilter that is loaded with default components
    selx::SuperElastixFilter::Pointer superElastixFilter = selx::SuperElastixFilter::New();

    superElastixFilter->SetLogger(logger);

    // create empty blueprint
    selx::Blueprint::Pointer blueprint = selx::Blueprint::New();
    blueprint->SetLogger(logger);
    for (const auto & configurationPath : configurationPaths)
    {
      blueprint->MergeFromFile(configurationPath.string());
    }

    if( vm.count( "graphout" ) )
    {
      blueprint->Write(vm["graphout"].as< boost::filesystem::path >().string());
    }

    // The Blueprint needs to be set to superElastixFilter before GetInputFileReader and GetOutputFileWriter should be called.
    superElastixFilter->SetBlueprint(blueprint);

    // Store the readers so that they will not be destroyed before the pipeline is executed.
    std::vector< selx::AnyFileReader::Pointer > fileReaders;
    // Store the writers for the update call
    std::vector< selx::AnyFileWriter::Pointer > fileWriters;

    if( vm.count( "in" ) )
    {
      logger->Log( selx::LogLevel::INF, "Preparing input data ... ");
      int index = 0;
      for( const auto & inputPair : inputPairs )
      {
        VectorOfStringsType nameAndPath;
        boost::split( nameAndPath, inputPair, boost::is_any_of( "=" ) );  // NameAndPath == { "name","path" }
        const std::string & name = nameAndPath[ 0 ];
        const std::string & path = nameAndPath[ 1 ];

        // since we do not know which reader type we should instantiate for input "name",
        // we ask SuperElastix for a reader that matches the type of the source component "name"
        logger->Log( selx::LogLevel::INF, "Preparing input " + name + " ..." );
        selx::AnyFileReader::Pointer reader = superElastixFilter->GetInputFileReader( name );
        reader->SetFileName( path );
        superElastixFilter->SetInput( name, reader->GetOutput() );
        fileReaders.push_back( reader );

        logger->Log( selx::LogLevel::INF, "Preparing input " + name +  "... Done" );
        std::cout << "Input data " << index << " " << name << " : " << path << "\n";
        ++index;
      }
      logger->Log( selx::LogLevel::INF, "Preparing input data ... Done");
    }
    else
    {
      logger->Log( selx::LogLevel::INF, "No input data specified.");
    }

    if( vm.count( "out" ) )
    {
      logger->Log( selx::LogLevel::INF, "Preparing output data ... ");
      int index = 0;
      for( const auto & outputPair : outputPairs )
      {
        VectorOfStringsType nameAndPath;
        boost::split( nameAndPath, outputPair, boost::is_any_of( "=" ) );  // NameAndPath == { "name","path" }
        const std::string & name = nameAndPath[ 0 ];
        const std::string & path = nameAndPath[ 1 ];

        // since we do not know which writer type we should instantiate for output "name",
        // we ask SuperElastix for a writer that matches the type of the sink component "name"
        logger->Log( selx::LogLevel::INF, "Preparing output " + name + " ..." );
        selx::AnyFileWriter::Pointer writer = superElastixFilter->GetOutputFileWriter( name );
        //ImageWriter2DType::Pointer writer = ImageWriter2DType::New();
        writer->SetFileName( path );
        //writer->SetInput(superElastixFilter->GetOutput<Image2DType>(name));
        writer->SetInput( superElastixFilter->GetOutput( name ) );
        fileWriters.push_back( writer );
        logger->Log( selx::LogLevel::INF, "Preparing output " + name + " ... Done" );
        ++index;

      }
    }
    else
    {
      logger->Log( selx::LogLevel::INF, "No output data specified.");
    }

    /* Execute SuperElastix by updating the writers */
    logger->Log( selx::LogLevel::INF, "Executing ...");
    for( auto & writer : fileWriters )
    {
      writer->Update();
    }
    logger->Log(selx:: LogLevel::INF, "Executing ... Done");
  }
  catch( std::exception & e )
  {
    logger->Log( selx::LogLevel::ERR, "Executing ... Error");
    std::cerr << "error: " << e.what() << "\n";
    return 1;
  }
  catch( ... )
  {
    logger->Log( selx::LogLevel::ERR, "Executing ... Error");
    std::cerr << "Exception of unknown type!\n";
  }

  return 0;
}
<commit_msg>GIT: Fix merge error (duplicate code); STYLE: Do not prepend cout stream name with SELX<commit_after>/*=========================================================================
 *
 *  Copyright Leiden University Medical Center, Erasmus University Medical
 *  Center and contributors
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  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 "selxSuperElastixFilter.h"
#include "selxAnyFileReader.h"
#include "selxAnyFileWriter.h"
#include "selxLogger.h"

#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include <iostream>
#include <algorithm>
#include <iterator>
#include <string>
#include <stdexcept>

template< class T >
std::ostream &
operator<<( std::ostream & os, const std::vector< T > & v )
{
  std::copy( v.begin(), v.end(), std::ostream_iterator< T >( os, " " ) );
  return os;
}

namespace selx
{
  // helper function to parse command line arguments for log level
  std::istream& operator>>(std::istream& in, selx::LogLevel& loglevel)
  {
    std::string token;
    in >> token;
    if (token == "off")
      loglevel = selx::LogLevel::OFF;
    else if (token == "critical")
      loglevel = selx::LogLevel::CRT;
    else if (token == "error")
      loglevel = selx::LogLevel::ERR;
    else if (token == "warning")
      loglevel = selx::LogLevel::WRN;
    else if (token == "info")
      loglevel = selx::LogLevel::INF;
    else if (token == "debug")
      loglevel = selx::LogLevel::DBG;
    else if (token == "trace")
      loglevel = selx::LogLevel::TRC;
    else
      in.setstate(std::ios_base::failbit);
    return in;
  }
}

int
main( int ac, char * av[] )
{

  selx::Logger::Pointer logger = selx::Logger::New();

  try
  {
    typedef std::vector< std::string > VectorOfStringsType;
    typedef std::vector< boost::filesystem::path > VectorOfPathsType;

    boost::filesystem::path logPath;
    // default log level
    selx::LogLevel logLevel = selx::LogLevel::WRN;

    boost::filesystem::path            configurationPath;
    VectorOfPathsType                   configurationPaths;

    VectorOfStringsType inputPairs;
    VectorOfStringsType outputPairs;

    boost::program_options::options_description desc("Allowed options");
    desc.add_options()
      ( "help", "produce help message" )
      ("conf", boost::program_options::value< VectorOfPathsType >(&configurationPaths)->required()->multitoken(), "Configuration file")
      ("in", boost::program_options::value< VectorOfStringsType >(&inputPairs)->multitoken(), "Input data: images, labels, meshes, etc. Usage <name>=<path>")
      ("out", boost::program_options::value< VectorOfStringsType >(&outputPairs)->multitoken(), "Output data: images, labels, meshes, etc. Usage <name>=<path>")
      ("graphout", boost::program_options::value< boost::filesystem::path >(), "Output Graphviz dot file")
      ("logfile", boost::program_options::value< boost::filesystem::path >(&logPath), "Log output file")
      ("loglevel", boost::program_options::value< selx::LogLevel >(&logLevel), "Log level")
      ;

    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::parse_command_line(ac, av, desc), vm);
    boost::program_options::notify(vm);

    if( vm.count( "help" ) )
    {
      std::cout << desc << "\n";
      return 0;
    }

    // optionally, stream to log file
    std::ofstream outfile;
    if ( vm.count("logfile") )
    {
      outfile =  std::ofstream(logPath.c_str());
      logger->AddStream("logfile", outfile);
    }

    logger->AddStream("cout", std::cout);
    logger->SetLogLevel(logLevel);

    // instantiate a SuperElastixFilter that is loaded with default components
    selx::SuperElastixFilter::Pointer superElastixFilter = selx::SuperElastixFilter::New();

    superElastixFilter->SetLogger(logger);

    // create empty blueprint
    selx::Blueprint::Pointer blueprint = selx::Blueprint::New();
    blueprint->SetLogger(logger);
    for (const auto & configurationPath : configurationPaths)
    {
      blueprint->MergeFromFile(configurationPath.string());
    }

    if( vm.count( "graphout" ) )
    {
      blueprint->Write(vm["graphout"].as< boost::filesystem::path >().string());
    }

    // The Blueprint needs to be set to superElastixFilter before GetInputFileReader and GetOutputFileWriter should be called.
    superElastixFilter->SetBlueprint(blueprint);

    // Store the readers so that they will not be destroyed before the pipeline is executed.
    std::vector< selx::AnyFileReader::Pointer > fileReaders;
    // Store the writers for the update call
    std::vector< selx::AnyFileWriter::Pointer > fileWriters;

    if( vm.count( "in" ) )
    {
      logger->Log( selx::LogLevel::INF, "Preparing input data ... ");
      int index = 0;
      for( const auto & inputPair : inputPairs )
      {
        VectorOfStringsType nameAndPath;
        boost::split( nameAndPath, inputPair, boost::is_any_of( "=" ) );  // NameAndPath == { "name","path" }
        const std::string & name = nameAndPath[ 0 ];
        const std::string & path = nameAndPath[ 1 ];

        // since we do not know which reader type we should instantiate for input "name",
        // we ask SuperElastix for a reader that matches the type of the source component "name"
        logger->Log( selx::LogLevel::INF, "Preparing input " + name + " ..." );
        selx::AnyFileReader::Pointer reader = superElastixFilter->GetInputFileReader( name );
        reader->SetFileName( path );
        superElastixFilter->SetInput( name, reader->GetOutput() );
        fileReaders.push_back( reader );

        logger->Log( selx::LogLevel::INF, "Preparing input " + name +  "... Done" );
        std::cout << "Input data " << index << " " << name << " : " << path << "\n";
        ++index;
      }
      logger->Log( selx::LogLevel::INF, "Preparing input data ... Done");
    }
    else
    {
      logger->Log( selx::LogLevel::INF, "No input data specified.");
    }

    if( vm.count( "out" ) )
    {
      logger->Log( selx::LogLevel::INF, "Preparing output data ... ");
      int index = 0;
      for( const auto & outputPair : outputPairs )
      {
        VectorOfStringsType nameAndPath;
        boost::split( nameAndPath, outputPair, boost::is_any_of( "=" ) );  // NameAndPath == { "name","path" }
        const std::string & name = nameAndPath[ 0 ];
        const std::string & path = nameAndPath[ 1 ];

        // since we do not know which writer type we should instantiate for output "name",
        // we ask SuperElastix for a writer that matches the type of the sink component "name"
        logger->Log( selx::LogLevel::INF, "Preparing output " + name + " ..." );
        selx::AnyFileWriter::Pointer writer = superElastixFilter->GetOutputFileWriter( name );
        //ImageWriter2DType::Pointer writer = ImageWriter2DType::New();
        writer->SetFileName( path );
        //writer->SetInput(superElastixFilter->GetOutput<Image2DType>(name));
        writer->SetInput( superElastixFilter->GetOutput( name ) );
        fileWriters.push_back( writer );
        logger->Log( selx::LogLevel::INF, "Preparing output " + name + " ... Done" );
        ++index;

      }
    }
    else
    {
      logger->Log( selx::LogLevel::INF, "No output data specified.");
    }

    /* Execute SuperElastix by updating the writers */
    logger->Log( selx::LogLevel::INF, "Executing ...");
    for( auto & writer : fileWriters )
    {
      writer->Update();
    }
    logger->Log(selx:: LogLevel::INF, "Executing ... Done");
  }
  catch( std::exception & e )
  {
    logger->Log( selx::LogLevel::ERR, "Executing ... Error");
    std::cerr << "error: " << e.what() << "\n";
    return 1;
  }
  catch( ... )
  {
    logger->Log( selx::LogLevel::ERR, "Executing ... Error");
    std::cerr << "Exception of unknown type!\n";
  }

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>nspluginwrapper compat fixes, part 1: Set the correct size in NP_GetEntryPoints. The old code was assigning the size of the _pointer_ (i.e., 4). Apparently most browsers ignore this or else O3D wouldn't have worked anywhere, but nspluginwrapper started to care about this very much somewhere between 1.2.2 and 1.3.1-Pre (20090625). With the old code it stops before even calling our NPP_New because it thinks we don't have one.<commit_after><|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//
// Arion
//
// Extract metadata and create beautiful thumbnails of your images.
//
// ------------
//   main.cpp
// ------------
//
// Copyright (c) 2015 Paul Filitchkin, Snapwire
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in
//      the documentation and/or other materials provided with the
//      distribution.
//
//    * Neither the name of the organization nor the names of its contributors
//      may be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//------------------------------------------------------------------------------

// Local
#include "models/operation.hpp"
#include "models/resize.hpp"
#include "models/read_meta.hpp"
#include "utils/utils.hpp"
#include "arion.hpp"

// Boost
#include <boost/exception/info.hpp>
#include <boost/exception/error_info.hpp>
#include <boost/exception/all.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>

// Stdlib
#include <iostream>
#include <string>

using namespace boost::program_options;
using namespace std;

#define ARION_VERSION "0.3.3"

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void showHelp(options_description &desc) {
  cerr << desc << endl;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
int main(int argc, char *argv[]) {
  try {
    positional_options_description p;
    p.add("input", 1);

    string description = "Arion v";
    description += ARION_VERSION;
    description += "\n\n Arguments";

    options_description desc(description);

    desc.add_options()
        ("help", "Produce this help message")
        ("version", "Print version")
        ("input", value<string>(), "The input operations to execute in JSON");

    variables_map vm;

    store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);

    notify(vm);

    string inputJson;

    if (vm.count("help")) {
      showHelp(desc);
      return 1;
    }

    if (vm.count("version")) {
      cout << "{\"version\":\"" << ARION_VERSION << "\"}" << endl;
      return 0;
    }

    if (vm.count("input")) {
      inputJson = vm["input"].as<string>();
    } else {
      cout << "You must provide the input operations to execute" << endl << endl;
      showHelp(desc);
      return 1;
    }

    Arion arion;

    if (!arion.setup(inputJson)) {
      cout << arion.getJson();
      exit(-1);
    }

    bool result = arion.run();

    cout << arion.getJson();

    if (result) {
      exit(0);
    } else {
      exit(-1);
    }
  }
  catch (std::exception &e) {
    Utils::exitWithError(e.what());
  }

  return 0;
}
<commit_msg>0.3.4<commit_after>//------------------------------------------------------------------------------
//
// Arion
//
// Extract metadata and create beautiful thumbnails of your images.
//
// ------------
//   main.cpp
// ------------
//
// Copyright (c) 2015 Paul Filitchkin, Snapwire
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in
//      the documentation and/or other materials provided with the
//      distribution.
//
//    * Neither the name of the organization nor the names of its contributors
//      may be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//------------------------------------------------------------------------------

// Local
#include "models/operation.hpp"
#include "models/resize.hpp"
#include "models/read_meta.hpp"
#include "utils/utils.hpp"
#include "arion.hpp"

// Boost
#include <boost/exception/info.hpp>
#include <boost/exception/error_info.hpp>
#include <boost/exception/all.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>

// Stdlib
#include <iostream>
#include <string>

using namespace boost::program_options;
using namespace std;

#define ARION_VERSION "0.3.4"

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void showHelp(options_description &desc) {
  cerr << desc << endl;
}

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
int main(int argc, char *argv[]) {
  try {
    positional_options_description p;
    p.add("input", 1);

    string description = "Arion v";
    description += ARION_VERSION;
    description += "\n\n Arguments";

    options_description desc(description);

    desc.add_options()
        ("help", "Produce this help message")
        ("version", "Print version")
        ("input", value<string>(), "The input operations to execute in JSON");

    variables_map vm;

    store(command_line_parser(argc, argv).options(desc).positional(p).run(), vm);

    notify(vm);

    string inputJson;

    if (vm.count("help")) {
      showHelp(desc);
      return 1;
    }

    if (vm.count("version")) {
      cout << "{\"version\":\"" << ARION_VERSION << "\"}" << endl;
      return 0;
    }

    if (vm.count("input")) {
      inputJson = vm["input"].as<string>();
    } else {
      cout << "You must provide the input operations to execute" << endl << endl;
      showHelp(desc);
      return 1;
    }

    Arion arion;

    if (!arion.setup(inputJson)) {
      cout << arion.getJson();
      exit(-1);
    }

    bool result = arion.run();

    cout << arion.getJson();

    if (result) {
      exit(0);
    } else {
      exit(-1);
    }
  }
  catch (std::exception &e) {
    Utils::exitWithError(e.what());
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <allegro5\allegro.h>
#include "objects.h"

//Global variables
const int WIDTH = 800;
const int HEIGHT = 600;

int main()
{
	//primitve variables
	bool done = false; //event loop fundamental variable

	//Allegro variables
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;

	//inits
	if(!al_init())
		return -1;

	display = al_create_display(WIDTH, HEIGHT);
	if(!display)
		return -1;

	al_install_keyboard();

	event_queue = al_create_event_queue();

	//event registers
	al_register_event_source(event_queue, al_get_display_event_source(display));
	al_register_event_source(event_queue, al_get_keyboard_event_source());

	//gameloop
	while(!done)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);

		if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = true;
		}
	}

	//deallocating memory used for allegro objects
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);
	return 0;
}<commit_msg>Included timer into the gameloop + minor changes<commit_after>#include <allegro5\allegro.h>
#include "objects.h"

//Global variables
const int WIDTH = 800;
const int HEIGHT = 600;
bool keys[] = {false, false, false, false};
int main()
{
	//primitve variables
	bool done = false; //event loop fundamental variable
	bool redraw = true; //check whether the display needs an update
	const int FPS = 60;
	//Allegro variables
	ALLEGRO_DISPLAY *display = NULL;
	ALLEGRO_EVENT_QUEUE *event_queue = NULL;
	ALLEGRO_TIMER *timer = NULL;

	//inits
	if(!al_init())
		return -1;

	display = al_create_display(WIDTH, HEIGHT);
	if(!display)
		return -1;

	al_install_keyboard();

	event_queue = al_create_event_queue();
	timer = al_create_timer(1.0 / FPS);

	//event registers
	al_register_event_source(event_queue, al_get_display_event_source(display));
	al_register_event_source(event_queue, al_get_keyboard_event_source());
	al_register_event_source(event_queue, al_get_timer_event_source(timer));

	al_start_timer(timer);
	//gameloop
	while(!done)
	{
		ALLEGRO_EVENT ev;
		al_wait_for_event(event_queue, &ev);
		if(ev.type == ALLEGRO_EVENT_TIMER)
		{
			redraw = true;
		}
		else if(ev.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
		{
			done = true; //closing the game after clicking X on top-right corner
		}

		if(redraw && al_is_event_queue_empty(event_queue))
		{
			redraw = false;

			al_flip_display();
			al_clear_to_color(al_map_rgb(0,0,0)); //black background
		}
	}

	//deallocating memory used for allegro objects
	al_destroy_display(display);
	al_destroy_event_queue(event_queue);
	al_destroy_timer(timer);
	return 0;
}<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>

/*
 * Add command line arguments
 * ideas:
 * difficulty (speed), color, graphics
 * debugging, etc.
 */

int main( void )
{
  //load board
  //set up screen
  while( true ) //game loop
    {
      //take user input
      //action from input
      //check for collisions
      //check for lines? (maybe should go somewhere else)
      //update board
      //update screen
      if( true ) //end game conditional
	break;
    }
  exit( EXIT_SUCCESS );
}
<commit_msg>Add getopt skeleton<commit_after>#include <cstdlib>
#include <iostream>
#include <GetOpt.h>

/*
 * Add command line arguments
 * ideas:
 * difficulty (speed), color, graphics
 * debugging, etc.
 */

int main( int argc, char **argv )
{
  GetOpt getopt( argc, argv, "lscgd:" );
  int opt;
  int level;
  bool debug = false;
  while( ( opt = getopt() ) != EOF )
    {
      switch( opt )
	{
	case 'l':
	  level = atoi( getopt.optarg );
	  break;
	case 'd':
	  debug = true;
	  break;
	case 's':
	  break;
	case 'c':
	  break;
	case 'g':
	  break;
	default:
	  break;
	}
    }
  //load board
  //set up screen
  while( true ) //game loop
    {
      //take user input
      //action from input
      //check for collisions
      //check for lines? (maybe should go somewhere else)
      //update board
      //update screen
      if( true ) //end game conditional
	break;
    }
  exit( EXIT_SUCCESS );
}
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2014 Jonathan Gillett, Joseph Heron, Khalil Fazal, Daniel Smullen
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <Writer.hpp>
#include <Reader.hpp>
#include <unistd.h>

//Declare the maximum buffer size for interacting with the socket.
#define MAX_BUFFER_SIZE 256

int open(const char* hostname, const uint16_t port) {
    // The socket address
    struct sockaddr_in address;

    // The socket host
    struct hostent* host = gethostbyname(hostname);

    // The socket's file descriptor
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    // allocate address with null bytes
    bzero((char *) &address, sizeof(address));

    // set the address format to IPV4
    address.sin_family = AF_INET;

    // set the host in the address
    memmove((char *) &address.sin_addr.s_addr, (char *) host->h_addr, host->h_length);

    // set the port in the address
    address.sin_port = htons(port);

    // connect to the socket
    connect(sockfd, (struct sockaddr *) &address, sizeof(address));

    // return the socket
    return sockfd;
}

int main(int argc, char** argv) {
    (void) argc;
    (void) argv;

	//Declare a socket instance here.
	/*struct sockaddr_in server;
	string address = "192.168.0.1";
	server.sin_port = htons(1234);
	inet_aton(address., &server.sin_addr.s_addr);

	//Open the socket. If it fails to bind, terminate.
	int s = socket(AF_INET, SOCK_STREAM, 0);
	if (s == -1) {
		cout << "Invalid socket descriptor.";
		return -1;
	} else {
		cout << "Socket bound.";
	}

	//Connect to the socket. If it fails to connect, terminate.
	cout << "Connecting to socket on address: " << address << " port: "
			<< server.sin_port << endl;
	if (connect(s, (struct sockaddr *) &server, sizeof(server)) == -1) {
		cout << "Socket connection failed.";
		return -1;
	}*/

    int s = open("192.168.0.1", 1234);

	//Instantiate reader thread here; bind to connected socket.
	Reader r(s, MAX_BUFFER_SIZE);
	//Instantiate writer thread here; bind to connected socket.
	Writer w(s, MAX_BUFFER_SIZE);

	//Signal the writer thread to subscribe to the events.
	//Put the following into the buffer, and notify the writer thread:
	//w.sendCommand("request(100,view)\n");

	//Begin main control loop:
	for(;;){
		//Check if we've received something from the socket.
		//Output it to the console.
		cout << r.readCommand() << endl;
	}

	//Join and release the reader thread.
	r.release();
	//Join and release the writer thread.
	w.release();

	return 0;
}
<commit_msg>added send command for initialization.<commit_after>/**
 * Copyright (C) 2014 Jonathan Gillett, Joseph Heron, Khalil Fazal, Daniel Smullen
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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 General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>

#include <Writer.hpp>
#include <Reader.hpp>
#include <unistd.h>

//Declare the maximum buffer size for interacting with the socket.
#define MAX_BUFFER_SIZE 256

int open(const char* hostname, const uint16_t port) {
    // The socket address
    struct sockaddr_in address;

    // The socket host
    struct hostent* host = gethostbyname(hostname);

    // The socket's file descriptor
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    // allocate address with null bytes
    bzero((char *) &address, sizeof(address));

    // set the address format to IPV4
    address.sin_family = AF_INET;

    // set the host in the address
    memmove((char *) &address.sin_addr.s_addr, (char *) host->h_addr, host->h_length);

    // set the port in the address
    address.sin_port = htons(port);

    // connect to the socket
    connect(sockfd, (struct sockaddr *) &address, sizeof(address));

    // return the socket
    return sockfd;
}

int main(int argc, char** argv) {
    (void) argc;
    (void) argv;

	//Declare a socket instance here.
	/*struct sockaddr_in server;
	string address = "192.168.0.1";
	server.sin_port = htons(1234);
	inet_aton(address., &server.sin_addr.s_addr);

	//Open the socket. If it fails to bind, terminate.
	int s = socket(AF_INET, SOCK_STREAM, 0);
	if (s == -1) {
		cout << "Invalid socket descriptor.";
		return -1;
	} else {
		cout << "Socket bound.";
	}

	//Connect to the socket. If it fails to connect, terminate.
	cout << "Connecting to socket on address: " << address << " port: "
			<< server.sin_port << endl;
	if (connect(s, (struct sockaddr *) &server, sizeof(server)) == -1) {
		cout << "Socket connection failed.";
		return -1;
	}*/

    int s = open("192.168.0.1", 1234);

	//Instantiate reader thread here; bind to connected socket.
	Reader r(s, MAX_BUFFER_SIZE);
	//Instantiate writer thread here; bind to connected socket.
	Writer w(s, MAX_BUFFER_SIZE);

    //1. Request control of the train
    //w.sendCommand("request(1005,control,force)\n");

	//2. Signal the writer thread to subscribe to the events.
	//   Put the following into the buffer, and notify the writer thread:
	//w.sendCommand("request(100,view)\n");

    //3. Get Control of F1
    //w.sendCommand("request(20002,control,force)\n");

    // TODO: sleep(100 ms)
    usleep(100000);

    //4. Get Control of F2
    //w.sendCommand("request(20000,control,force)\n");

    // TODO: sleep(100 ms)
    usleep(100000);

    //5. Get Control of J1
    //w.sendCommand("request(20001,control,force)\n");

    // TODO: sleep(100 ms)
    usleep(100000);

    //6. Get Control of J2
    //w.sendCommand("request(20003,control,force)\n");

    //7.

	//Begin main control loop:
	while (true) {
		//Check if we've received something from the socket.
		//Output it to the console.
		cout << r.readCommand() << endl;
	}

	//Join and release the reader thread.
	r.release();
	//Join and release the writer thread.
	w.release();

	return 0;
}
<|endoftext|>


<commit_before>#include "mraa.h"
#include <chrono>
#include <thread>
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

enum COMMAND
{
    IDLE = 0,
    FORWARD = 1,
    REVERSE = 2,
    LEFT = 4,
    RIGHT = 8
};
const char* COMMAND_NAMES[] = {"IDLE","FORWARD","REVERSE","INVALID","LEFT","INVALID","INVALID","INVALID","RIGHT"};

struct context
{
    mraa_gpio_context drive_context;
    mraa_gpio_context reverse_context;
};

int getCommand();
void loop(context& gpio_context);

int gMagnitude = 0;
bool gReverseEnabled = false;
const char* RC_ADDRESS = "http://192.168.1.243:8080/CommandServer/currentCommand";

#define DRIVE_MOTOR_GPIO 31 //GP44
#define REVERSE_ENGAGE_GPIO 32 //GP46
#define DEFAULT_WAIT_TIME_MS 300

int main(int argc, char** argv)
{
    curl_global_init(CURL_GLOBAL_DEFAULT);
    mraa_init();
    mraa_gpio_context drive_context = mraa_gpio_init(DRIVE_MOTOR_GPIO);
    if(drive_context == NULL || mraa_gpio_dir(drive_context, MRAA_GPIO_OUT) != MRAA_SUCCESS) exit(1);
    mraa_gpio_write(drive_context, false);
    mraa_gpio_context reverse_context = mraa_gpio_init(REVERSE_ENGAGE_GPIO);
    if(reverse_context == NULL || mraa_gpio_dir(reverse_context, MRAA_GPIO_OUT) != MRAA_SUCCESS) exit(1);
    mraa_gpio_write(reverse_context, false);

    printf("%s Wifi RC Interface\n", mraa_get_platform_name());

    context session;
    session.drive_context = drive_context;
    session.reverse_context = reverse_context;
    while(true) loop(session);

    curl_global_cleanup();
    mraa_deinit();

    return 0;

}

size_t curl_write_function(void* buffer, size_t size, size_t nmemb, int* p)
{
    static const char* NAME_STRING = "Name";
    static const char* VALUE_STRING = "Value";
    static const char* RESPONSE_STRING = "Response";
    static const char* TERMINAL_STRING = "Terminal";
    static const char* directionTerminal = "direction";
    static const char* magnitudeTerminal = "magnitude";

    char test[64];
    char name[64];
    char value[64];
    char* parse = strstr((char*)buffer, RESPONSE_STRING)+strlen(RESPONSE_STRING)+1;
    memset(test, '\0', 64);
    memcpy(test, parse+3, strlen(RESPONSE_STRING));
    while(strcmp(test, RESPONSE_STRING))
    {
        parse = strstr(parse, TERMINAL_STRING)+strlen(TERMINAL_STRING)+1;
        parse = strstr(parse, NAME_STRING)+strlen(NAME_STRING)+1;
        int length = strchr(parse, '<')-parse;
        memset(name, '\0', 64);
        memcpy(name, parse, length);
        parse = strstr(parse, VALUE_STRING)+strlen(VALUE_STRING)+1;
        length = strchr(parse, '<')-parse;
        memset(value, '\0', 64);
        memcpy(value, parse, length);
        parse = strstr(parse, TERMINAL_STRING)+strlen(TERMINAL_STRING)+1;
        memset(test, '\0', 64);
        memcpy(test, parse+3, strlen(RESPONSE_STRING));
        if(!strcmp(name, directionTerminal))
        {
            *p = atoi(value);
        }
        if(!strcmp(name, magnitudeTerminal))
        {
            gMagnitude = atoi(value);
        }
    }

    return size*nmemb;
}

int getCommand()
{
    int command = IDLE;
    CURL* pCURL = curl_easy_init();
    if(pCURL)
    {
        int temp;
        curl_easy_setopt(pCURL, CURLOPT_URL, RC_ADDRESS);
        curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, curl_write_function);
        curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, &temp);
        CURLcode result = curl_easy_perform(pCURL);
        if(result == CURLE_OK)
        {
            command = temp;
        }
        curl_easy_cleanup(pCURL);
    }

    return command;

}

void enableReverse(bool enabled, context& gpio_context)
{
    mraa_gpio_write(gpio_context.drive_context, false);
    std::this_thread::sleep_for(std::chrono::milliseconds(DEFAULT_WAIT_TIME_MS));
    mraa_gpio_write(gpio_context.reverse_context, enabled);
    gReverseEnabled = enabled;
}

void loop(context& gpio_context)
{
    int raw = getCommand();

    int value = raw;
    if(value > 3) value &= 0xC;
    printf("%s\n", COMMAND_NAMES[value]);

    bool killReverse = true;
    bool shouldDrive = false;
    switch(raw &= 0x3)
    {
        case FORWARD:
            shouldDrive = true;
            break;
        case REVERSE:
            killReverse = false;
            if(!gReverseEnabled) enableReverse(true, gpio_context);
            shouldDrive = true;
            break;
        case IDLE:
        default:
            break;
    }
    if(gReverseEnabled && killReverse) enableReverse(false, gpio_context);
    mraa_gpio_write(gpio_context.drive_context, shouldDrive);
    std::this_thread::sleep_for(std::chrono::milliseconds(gMagnitude > 0 ? gMagnitude: DEFAULT_WAIT_TIME_MS));
}
<commit_msg>Prep for programmatic headlight control<commit_after>#include "mraa.h"
#include <chrono>
#include <thread>
#include <stdio.h>
#include <string.h>
#include <curl/curl.h>

enum COMMAND
{
    IDLE = 0,
    FORWARD = 1,
    REVERSE = 2,
    LEFT = 4,
    RIGHT = 8
};
const char* COMMAND_NAMES[] = {"IDLE","FORWARD","REVERSE","INVALID","LEFT","INVALID","INVALID","INVALID","RIGHT"};

struct context
{
    mraa_gpio_context drive_context;
    mraa_gpio_context reverse_context;
    mraa_gpio_context light_context;
};

int getCommand();
void loop(context& gpio_context);

int gMagnitude = 0;
bool gReverseEnabled = false;
const char* RC_ADDRESS = "http://192.168.1.243:8080/CommandServer/currentCommand";

#define DRIVE_MOTOR_GPIO 31 //GP44
#define REVERSE_ENGAGE_GPIO 32 //GP46
#define LIGHT_GPIO 33 //GP48
#define DEFAULT_WAIT_TIME_MS 300

int main(int argc, char** argv)
{
    curl_global_init(CURL_GLOBAL_DEFAULT);
    mraa_init();
    mraa_gpio_context drive_context = mraa_gpio_init(DRIVE_MOTOR_GPIO);
    if(drive_context == NULL || mraa_gpio_dir(drive_context, MRAA_GPIO_OUT) != MRAA_SUCCESS) exit(1);
    mraa_gpio_write(drive_context, false);
    mraa_gpio_context reverse_context = mraa_gpio_init(REVERSE_ENGAGE_GPIO);
    if(reverse_context == NULL || mraa_gpio_dir(reverse_context, MRAA_GPIO_OUT) != MRAA_SUCCESS) exit(1);
    mraa_gpio_write(reverse_context, false);
    mraa_gpio_context light_context = mraa_gpio_init(LIGHT_GPIO);
    if(light_context == NULL || mraa_gpio_dir(light_context, MRAA_GPIO_OUT) != MRAA_SUCCESS) exit(1);
    mraa_gpio_write(light_context, false);

    printf("%s Wifi RC Interface\n", mraa_get_platform_name());

    context session;
    session.drive_context = drive_context;
    session.reverse_context = reverse_context;
    session.light_context = light_context;

    while(true) loop(session);

    curl_global_cleanup();
    mraa_deinit();

    return 0;

}

size_t curl_write_function(void* buffer, size_t size, size_t nmemb, int* p)
{
    static const char* NAME_STRING = "Name";
    static const char* VALUE_STRING = "Value";
    static const char* RESPONSE_STRING = "Response";
    static const char* TERMINAL_STRING = "Terminal";
    static const char* directionTerminal = "direction";
    static const char* magnitudeTerminal = "magnitude";

    char test[64];
    char name[64];
    char value[64];
    char* parse = strstr((char*)buffer, RESPONSE_STRING)+strlen(RESPONSE_STRING)+1;
    memset(test, '\0', 64);
    memcpy(test, parse+3, strlen(RESPONSE_STRING));
    while(strcmp(test, RESPONSE_STRING))
    {
        parse = strstr(parse, TERMINAL_STRING)+strlen(TERMINAL_STRING)+1;
        parse = strstr(parse, NAME_STRING)+strlen(NAME_STRING)+1;
        int length = strchr(parse, '<')-parse;
        memset(name, '\0', 64);
        memcpy(name, parse, length);
        parse = strstr(parse, VALUE_STRING)+strlen(VALUE_STRING)+1;
        length = strchr(parse, '<')-parse;
        memset(value, '\0', 64);
        memcpy(value, parse, length);
        parse = strstr(parse, TERMINAL_STRING)+strlen(TERMINAL_STRING)+1;
        memset(test, '\0', 64);
        memcpy(test, parse+3, strlen(RESPONSE_STRING));
        if(!strcmp(name, directionTerminal))
        {
            *p = atoi(value);
        }
        if(!strcmp(name, magnitudeTerminal))
        {
            gMagnitude = atoi(value);
        }
    }

    return size*nmemb;
}

int getCommand()
{
    int command = IDLE;
    CURL* pCURL = curl_easy_init();
    if(pCURL)
    {
        int temp;
        curl_easy_setopt(pCURL, CURLOPT_URL, RC_ADDRESS);
        curl_easy_setopt(pCURL, CURLOPT_WRITEFUNCTION, curl_write_function);
        curl_easy_setopt(pCURL, CURLOPT_WRITEDATA, &temp);
        CURLcode result = curl_easy_perform(pCURL);
        if(result == CURLE_OK)
        {
            command = temp;
        }
        curl_easy_cleanup(pCURL);
    }

    return command;

}

void enableReverse(bool enabled, context& gpio_context)
{
    mraa_gpio_write(gpio_context.drive_context, false);
    std::this_thread::sleep_for(std::chrono::milliseconds(DEFAULT_WAIT_TIME_MS));
    mraa_gpio_write(gpio_context.reverse_context, enabled);
    gReverseEnabled = enabled;
}

void loop(context& gpio_context)
{
    int raw = getCommand();

    int value = raw;
    if(value > 3) value &= 0xC;
    printf("%s\n", COMMAND_NAMES[value]);

    bool killReverse = true;
    bool shouldDrive = false;
    switch(raw &= 0x3)
    {
        case FORWARD:
            shouldDrive = true;
            break;
        case REVERSE:
            killReverse = false;
            if(!gReverseEnabled) enableReverse(true, gpio_context);
            shouldDrive = true;
            break;
        case IDLE:
        default:
            break;
    }
    if(gReverseEnabled && killReverse) enableReverse(false, gpio_context);
    mraa_gpio_write(gpio_context.drive_context, shouldDrive);
    std::this_thread::sleep_for(std::chrono::milliseconds(gMagnitude > 0 ? gMagnitude: DEFAULT_WAIT_TIME_MS));
}
<|endoftext|>