<commit_before>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/1/10 22:00:41
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // 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} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    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, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &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, const Mint<MOD> &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>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// 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 << "No" << endl;
  exit(0);
}
// ----- main() -----
int main()
{
  int N;
  cin >> N;
  vector<mint> C(N);
  for (auto i = 0; i < N; i++)
  {
    cin >> C[i];
  }
  sort(C.begin(), C.end());
  mint ans{0};
  for (auto k = 0; k < N; k++)
  {
    ans += mint{4}.power(N - 1) * (N - k) * C[k];
  }
  cout << ans << endl;
}
<commit_msg>submit E.cpp to 'E - Change a Little Bit' (abc150) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/1/10 22:00:41
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // 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} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    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, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &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, const Mint<MOD> &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>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// 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 << "No" << endl;
  exit(0);
}
// ----- main() -----
int main()
{
  int N;
  cin >> N;
  vector<mint> C(N);
  for (auto i = 0; i < N; i++)
  {
    cin >> C[i];
  }
  sort(C.begin(), C.end());
  mint ans{0};
  for (auto k = 0; k < N; k++)
  {
    ans += mint{4}.power(N - 1) * (N - k + 1) * C[k];
  }
  cout << ans << endl;
}
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 6/16/2020, 3:58:40 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>
bool ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
    return true;
  }
  return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
    return true;
  }
  return false;
}
// ----- 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 << "No" << endl;
  exit(0);
}

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

constexpr ld Sup{100000};
constexpr ld Inf{-100000};

class Solve
{
  int N;
  vector<ld> X, Y;

public:
  Solve(int N) : N{N}, X(N), Y(N)
  {
    for (auto i{0}; i < N; ++i)
    {
      cin >> X[i] >> Y[i];
    }
  }

  void flush()
  {
    ld x{h()};
    ld y{g(x)};
    cout << fixed << setprecision(15) << f(x, y) << endl;
  }

private:
  ld h()
  {
    auto lb{Inf};
    auto ub{Sup};
    for (auto q{0}; q < 100; ++q)
    {
      auto l{(lb * 2 + ub) / 3};
      auto r{(lb + ub * 2) / 3};
      if (g(l) < g(r))
      {
        ub = r;
      }
      else
      {
        lb = l;
      }
    }
    return lb;
  }

  ld g(ld x)
  {
    auto lb{Inf};
    auto ub{Sup};
    for (auto q{0}; q < 100; ++q)
    {
      auto l{(lb * 2 + ub) / 3};
      auto r{(lb + ub * 2) / 3};
      if (f(x, l) < f(x, r))
      {
        ub = r;
      }
      else
      {
        lb = l;
      }
    }
    return lb;
  }

  ld f(ld x, ld y)
  {
    auto ans{Infty<ld>()};
    for (auto i{0}; i < N; ++i)
    {
      ch_min(ans, dist(x, y, X[i], Y[i]));
    }
    return ans;
  }

  ld dist(ld x, ld y, ld xx, ld yy)
  {
    auto t{x - xx};
    auto u{y - yy};
    return sqrt(t * t + u * u);
  }
};

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

int main()
{
  int N;
  cin >> N;
  Solve solve(N);
  solve.flush();
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 6/16/2020, 3:58:40 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>
bool ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
    return true;
  }
  return false;
}
template <typename T>
bool ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
    return true;
  }
  return false;
}
// ----- 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 << "No" << endl;
  exit(0);
}

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

constexpr ld Sup{100000};
constexpr ld Inf{-100000};

class Solve
{
  int N;
  vector<ld> X, Y;

public:
  Solve(int N) : N{N}, X(N), Y(N)
  {
    for (auto i{0}; i < N; ++i)
    {
      cin >> X[i] >> Y[i];
    }
  }

  void flush()
  {
    cout << fixed << setprecision(18) << h() << endl;
  }

private:
  ld h()
  {
    auto lb{Inf};
    auto ub{Sup};
    for (auto q{0}; q < 100; ++q)
    {
      auto l{(lb * 2 + ub) / 3};
      auto r{(lb + ub * 2) / 3};
      if (g(l) < g(r))
      {
        ub = r;
      }
      else
      {
        lb = l;
      }
    }
    return g(lb);
  }

  ld g(ld x)
  {
    auto lb{Inf};
    auto ub{Sup};
    for (auto q{0}; q < 100; ++q)
    {
      auto l{(lb * 2 + ub) / 3};
      auto r{(lb + ub * 2) / 3};
      if (f(x, l) < f(x, r))
      {
        ub = r;
      }
      else
      {
        lb = l;
      }
    }
    return f(x, lb);
  }

  ld f(ld x, ld y)
  {
    auto ans{Infty<ld>()};
    for (auto i{0}; i < N; ++i)
    {
      ch_min(ans, dist(x, y, X[i], Y[i]));
    }
    return ans;
  }

  ld dist(ld x, ld y, ld xx, ld yy)
  {
    auto t{x - xx};
    auto u{y - yy};
    return sqrt(t * t + u * u);
  }
};

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

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


<commit_before>#define DEBUG 1
/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2/3/2020, 3:59:35 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#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;
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{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // 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+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &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*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    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, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &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, const Mint<MOD> &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;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
constexpr int infty{1'000'000'000};
// 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 << -1 << endl;
  exit(0);
}
// ----- main() -----

int main()
{
  ll N, M;
  string S;
  cin >> N >> M >> S;
  reverse(S.begin(), S.end());
  vector<int> V(N + 1, -1);
  V[0] = 0;
  multiset<int> I;
  I.insert(V[0]);
  for (auto i = 1; i < N + 1; ++i)
  {
#if DEBUG == 1
    for (auto x : I)
    {
      cerr << x << " ";
    }
    cerr << endl;
#endif
    if (S[i] == '1')
    {
      V[i] = infty;
    }
    else
    {
      V[i] = *I.begin() + 1;
      cerr << "V[" << i << "] = " << V[i] << endl;
      if (V[i] > infty)
      {
        No();
      }
    }
    I.insert(V[i]);
    if (i - M >= 0)
    {
      I.erase(V[i - M]);
    }
  }
  reverse(V.begin(), V.end());
#if DEBUG == 1
  for (auto i = 0; i <= N; ++i)
  {
    cerr << "V[" << i << "] = " << V[i] << endl;
  }
#endif
  auto K{V[N]};
  int now{0};
  for (auto k = 1; k <= K; ++k)
  {
    for (auto m = now + 1; m <= min(now + M, N); ++m)
    {
      if (V[m] == K - k)
      {
        cout << m - now << endl;
        now = m;
        break;
      }
    }
  }
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2/3/2020, 3:59:35 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#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;
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{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // 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+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &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*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    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, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &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, const Mint<MOD> &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;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
constexpr int infty{1'000'000'000};
// 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 << -1 << endl;
  exit(0);
}
// ----- main() -----

int main()
{
  ll N, M;
  string S;
  cin >> N >> M >> S;
  reverse(S.begin(), S.end());
  vector<int> V(N + 1, -1);
  V[0] = 0;
  multiset<int> I;
  I.insert(V[0]);
  for (auto i = 1; i < N + 1; ++i)
  {
#if DEBUG == 1
    for (auto x : I)
    {
      cerr << x << " ";
    }
    cerr << endl;
#endif
    if (S[i] == '1')
    {
      V[i] = infty;
    }
    else
    {
      V[i] = *I.begin() + 1;
      if (V[i] > infty)
      {
        No();
      }
    }
#if DEBUG == 1
    cerr << "V[" << i << "] = " << V[i] << endl;
#endif
    I.insert(V[i]);
    if (i - M >= 0)
    {
      I.erase(V[i - M]);
    }
  }
  reverse(V.begin(), V.end());
#if DEBUG == 1
  for (auto i = 0; i <= N; ++i)
  {
    cerr << "V[" << i << "] = " << V[i] << endl;
  }
#endif
  auto K{V[N]};
  int now{0};
  for (auto k = 1; k <= K; ++k)
  {
    for (auto m = now + 1; m <= min(now + M, N); ++m)
    {
      if (V[m] == K - k)
      {
        cout << m - now << endl;
        now = m;
        break;
      }
    }
  }
}
<|endoftext|>


<commit_before>#ifdef CMAKE
#include <cstring>
#endif

#include "Stroke.h"

using namespace firestep;

template class Quad<int16_t>;
template class Quad<int32_t>;

Stroke::Stroke()
	: length(0), maxV(16), scale(1), curSeg(0), planMicros(0), tStart(0), dtTotal(0)
{}

SegIndex Stroke::goalSegment(Ticks t) {
	if (t < tStart || length == 0 || dtTotal==0) {
		return 0;
	}
	Ticks dt = t - tStart;
	if (dt >= dtTotal) {
		return length-1;
	}
	Ticks dtl = dt * length;
	return (dtl + length-1) / dtTotal;
}

Ticks Stroke::goalStartTicks(Ticks t) {
	if (t < tStart || length == 0 || dtTotal==0) {
		return 0;
	}
	Ticks dt = t - tStart;
	if (dt >= dtTotal) {
		return (dtTotal*(length-1))/length;
	}
	Ticks dtl = dt * length;
	SegIndex s = (dtl + length-1) / dtTotal;
	Ticks dtEnd = (s*dtTotal)/length;
#ifdef TEST_TRACE
	cout << "dtEnd:" << (long) dtEnd
		<< " s:" << (long) s
		<< " dtl:" << dtl
		<< " dt:" << dt
		<< " dtTotal:" << dtTotal
		<< " length:" << (long) length
		<< endl;
#endif
	return dtEnd;
}

Ticks Stroke::goalEndTicks(Ticks t) {
	if (t < tStart || length == 0 || dtTotal==0) {
		return 0;
	}
	Ticks dt = t - tStart;
	if (dt >= dtTotal) {
		return dtTotal;
	}
	Ticks dtl = dt * length;
	SegIndex s = (dtl + length-1) / dtTotal;
	Ticks dtEnd = ((s+1)*dtTotal)/length;
#ifdef TRACE
	cout << "dtEnd:" << (long) dtEnd
		<< " s:" << (long) s
		<< " dtl:" << dtl
		<< " dt:" << dt
		<< " dtTotal:" << dtTotal
		<< " length:" << (long) length
		<< endl;
#endif
	return dtEnd;
}

Quad<StepCoord> Stroke::goalPos(Ticks t) {
	Quad<StepCoord> v;
	SegIndex sGoal = goalSegment(t);
	Quad<StepCoord> dGoal;
	Ticks dtSegStart = goalStartTicks(t);
	Ticks dtSegEnd = goalEndTicks(t);
	Ticks dtSeg = dtSegEnd - dtSegStart;
	if (t <= tStart || dtTotal <= 0 || length <= 0 || dtSeg <= 0) {
		// do nothing
	} else if (tStart+dtTotal <= t) {
		dGoal = dEndPos;
	} else {
		Quad<StepCoord> posSegStart;
		for (SegIndex s=0; s<sGoal; s++) {
			v += seg[s]*scale;
			posSegStart += v;
		}
		Ticks dt = t - tStart;
		Ticks tNum = (dt>dtSegEnd ? dtSegEnd:dt) - dtSegStart;
		v += seg[sGoal]*scale;
		v *= tNum;
		v /= dtSeg;
		dGoal = posSegStart+v;
	}
	return dGoal;
}

template<class T> T abs(T a) { return a < 0 ? -a : a; };

Status Stroke::start(Ticks tStart) {
	this->tStart = tStart;

	if (dtTotal <= 0) {
		if (planMicros <= TICK_MICROSECONDS) {
			return STATUS_STROKE_PLANMICROS;
		}
		dtTotal = (planMicros + TICK_MICROSECONDS-1) / TICK_MICROSECONDS;
	}

	dPos = 0;
	Quad<StepCoord> end = goalPos(tStart+dtTotal-1);
	for (int i=0; i<4; i++) {
		if (maxV < abs(dEndPos.value[i] - end.value[i])) {
			return STATUS_STROKE_END_ERROR;
		}
	}
	return STATUS_OK;
}

bool Stroke::isDone() {
	return dPos == dEndPos;
}

Status Stroke::traverse(Ticks tCurrent, QuadStepper &stepper) {
	Quad<StepCoord> dGoal = goalPos(tCurrent);
	if (tStart <= 0) {
		return STATUS_STROKE_START;
	}
	if (tCurrent > tStart+dtTotal) {
		return STATUS_OK;
	}
	while (dPos != dGoal) {
		StepCoord d[4];
		StepCoord dMax = 0;
		for (uint8_t i=0; i<4; i++) {
			d[i] = dGoal.value[i] - dPos.value[i];
			dMax = max(dMax, abs(d[i]));
		}
		if (dMax == 0) {
			break;
		}
		Quad<StepCoord> pulse;
		for (uint8_t i=0; i<4; i++) {
			if (abs(d[i]) != dMax) {
				continue;
			}
			pulse.value[i] = d[i] < 0 ? -1 : 1;
		}
		dPos += pulse;
		Status status = stepper.step(pulse);
		switch (status) {
			case STATUS_OK:			// operation complete
			case STATUS_PROCESSING:	// work in progress
				break;
			default:
				return status;	// abnormal return
		}
	}
	return STATUS_PROCESSING;
}

<commit_msg>CMAKE<commit_after>#ifdef CMAKE
#include <cstring>
#endif

#include "Stroke.h"

using namespace firestep;

template class Quad<int16_t>;
template class Quad<int32_t>;

Stroke::Stroke()
	: length(0), maxV(16), scale(1), curSeg(0), planMicros(0), tStart(0), dtTotal(0)
{}

SegIndex Stroke::goalSegment(Ticks t) {
	if (t < tStart || length == 0 || dtTotal==0) {
		return 0;
	}
	Ticks dt = t - tStart;
	if (dt >= dtTotal) {
		return length-1;
	}
	Ticks dtl = dt * length;
	return (dtl + length-1) / dtTotal;
}

Ticks Stroke::goalStartTicks(Ticks t) {
	if (t < tStart || length == 0 || dtTotal==0) {
		return 0;
	}
	Ticks dt = t - tStart;
	if (dt >= dtTotal) {
		return (dtTotal*(length-1))/length;
	}
	Ticks dtl = dt * length;
	SegIndex s = (dtl + length-1) / dtTotal;
	Ticks dtEnd = (s*dtTotal)/length;
#ifdef TEST_TRACE
	cout << "dtEnd:" << (long) dtEnd
		<< " s:" << (long) s
		<< " dtl:" << dtl
		<< " dt:" << dt
		<< " dtTotal:" << dtTotal
		<< " length:" << (long) length
		<< endl;
#endif
	return dtEnd;
}

Ticks Stroke::goalEndTicks(Ticks t) {
	if (t < tStart || length == 0 || dtTotal==0) {
		return 0;
	}
	Ticks dt = t - tStart;
	if (dt >= dtTotal) {
		return dtTotal;
	}
	Ticks dtl = dt * length;
	SegIndex s = (dtl + length-1) / dtTotal;
	Ticks dtEnd = ((s+1)*dtTotal)/length;
#ifdef TRACE
	cout << "dtEnd:" << (long) dtEnd
		<< " s:" << (long) s
		<< " dtl:" << dtl
		<< " dt:" << dt
		<< " dtTotal:" << dtTotal
		<< " length:" << (long) length
		<< endl;
#endif
	return dtEnd;
}

Quad<StepCoord> Stroke::goalPos(Ticks t) {
	Quad<StepCoord> v;
	SegIndex sGoal = goalSegment(t);
	Quad<StepCoord> dGoal;
	Ticks dtSegStart = goalStartTicks(t);
	Ticks dtSegEnd = goalEndTicks(t);
	Ticks dtSeg = dtSegEnd - dtSegStart;
	if (t <= tStart || dtTotal <= 0 || length <= 0 || dtSeg <= 0) {
		// do nothing
	} else if (tStart+dtTotal <= t) {
		dGoal = dEndPos;
	} else {
		Quad<StepCoord> posSegStart;
		for (SegIndex s=0; s<sGoal; s++) {
			v += seg[s]*scale;
			posSegStart += v;
		}
		Ticks dt = t - tStart;
		Ticks tNum = (dt>dtSegEnd ? dtSegEnd:dt) - dtSegStart;
		v += seg[sGoal]*scale;
		v *= tNum;
		v /= dtSeg;
		dGoal = posSegStart+v;
	}
	return dGoal;
}

#ifdef CMAKE
template<class T> T abs(T a) { return a < 0 ? -a : a; };
#endif

Status Stroke::start(Ticks tStart) {
	this->tStart = tStart;

	if (dtTotal <= 0) {
		if (planMicros <= TICK_MICROSECONDS) {
			return STATUS_STROKE_PLANMICROS;
		}
		dtTotal = (planMicros + TICK_MICROSECONDS-1) / TICK_MICROSECONDS;
	}

	dPos = 0;
	Quad<StepCoord> end = goalPos(tStart+dtTotal-1);
	for (int i=0; i<4; i++) {
		if (maxV < abs(dEndPos.value[i] - end.value[i])) {
			return STATUS_STROKE_END_ERROR;
		}
	}
	return STATUS_OK;
}

bool Stroke::isDone() {
	return dPos == dEndPos;
}

Status Stroke::traverse(Ticks tCurrent, QuadStepper &stepper) {
	Quad<StepCoord> dGoal = goalPos(tCurrent);
	if (tStart <= 0) {
		return STATUS_STROKE_START;
	}
	if (tCurrent > tStart+dtTotal) {
		return STATUS_OK;
	}
	while (dPos != dGoal) {
		StepCoord d[4];
		StepCoord dMax = 0;
		for (uint8_t i=0; i<4; i++) {
			d[i] = dGoal.value[i] - dPos.value[i];
			dMax = max(dMax, abs(d[i]));
		}
		if (dMax == 0) {
			break;
		}
		Quad<StepCoord> pulse;
		for (uint8_t i=0; i<4; i++) {
			if (abs(d[i]) != dMax) {
				continue;
			}
			pulse.value[i] = d[i] < 0 ? -1 : 1;
		}
		dPos += pulse;
		Status status = stepper.step(pulse);
		switch (status) {
			case STATUS_OK:			// operation complete
			case STATUS_PROCESSING:	// work in progress
				break;
			default:
				return status;	// abnormal return
		}
	}
	return STATUS_PROCESSING;
}

<|endoftext|>


<commit_before>#include    "FTVectoriser.h"
#include    "FTGL.h"

#ifndef CALLBACK
#define CALLBACK
#endif

#if defined(__APPLE_CC__) && !defined(__INTEL_COMPILER)
    typedef GLvoid (*GLUTesselatorFunction)(...);
#elif defined( __mips ) || defined( __linux__ ) || defined( __FreeBSD__ ) || defined( __OpenBSD__ ) || defined( __sun ) || defined (__CYGWIN__) || defined (__APPLE__)
    typedef GLvoid (*GLUTesselatorFunction)();
#elif defined ( WIN32)
    typedef GLvoid (CALLBACK *GLUTesselatorFunction)( );
#else
    #error "Error - need to define type GLUTesselatorFunction for this platform/compiler"
#endif

void CALLBACK ftglError( GLenum errCode, FTMesh* mesh)
{
    mesh->Error( errCode);
}

void CALLBACK ftglVertex( void* data, FTMesh* mesh)
{
    FTGL_DOUBLE* vertex = static_cast<FTGL_DOUBLE*>(data);
    mesh->AddPoint( vertex[0], vertex[1], vertex[2]);
}

void CALLBACK ftglCombine( FTGL_DOUBLE coords[3], void* /*vertex_data[4]*/, GLfloat /*weight[4]*/, void** outData, FTMesh* mesh)
{
    const FTGL_DOUBLE* vertex = static_cast<const FTGL_DOUBLE*>(coords);
    *outData = const_cast<FTGL_DOUBLE*>(mesh->Combine( vertex[0], vertex[1], vertex[2]));
}

void CALLBACK ftglBegin( GLenum type, FTMesh* mesh)
{
    mesh->Begin( type);
}

void CALLBACK ftglEnd( FTMesh* mesh)
{
    mesh->End();
}

FTMesh::FTMesh()
:	currentTesselation(0),
    err(0)
{
    tesselationList.reserve( 16);
}

FTMesh::~FTMesh()
{
    for( size_t t = 0; t < tesselationList.size(); ++t)
    {
        delete tesselationList[t];
    }

    tesselationList.clear();
}

void FTMesh::AddPoint( const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z)
{
    currentTesselation->AddPoint( x, y, z);
}

const FTGL_DOUBLE* FTMesh::Combine( const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z)
{
    tempPointList.push_back( FTPoint( x, y,z));
    return static_cast<const FTGL_DOUBLE*>(tempPointList.back());
}

void FTMesh::Begin( GLenum meshType)
{
    currentTesselation = new FTTesselation( meshType);
}

void FTMesh::End()
{
    tesselationList.push_back( currentTesselation);
}

const FTTesselation* FTMesh::Tesselation( unsigned int index) const
{
    return ( index < tesselationList.size()) ? tesselationList[index] : NULL;
}

FTVectoriser::FTVectoriser( const FT_GlyphSlot glyph)
:   contourList(0),
    mesh(0),
    ftContourCount(0),
    contourFlag(0)
{
    if( glyph)
    {
        outline = glyph->outline;

        ftContourCount = outline.n_contours;
        contourList = 0;
        contourFlag = outline.flags;

        ProcessContours();
    }
}

FTVectoriser::~FTVectoriser()
{
    for( size_t c = 0; c < ContourCount(); ++c)
    {
        delete contourList[c];
    }

    delete [] contourList;
    delete mesh;
}

void FTVectoriser::ProcessContours()
{
    short contourLength = 0;
    short startIndex = 0;
    short endIndex = 0;

    contourList = new FTContour*[ftContourCount];

    for( short contourIndex = 0; contourIndex < ftContourCount; ++contourIndex)
    {
        FT_Vector* pointList = &outline.points[startIndex];
        char* tagList = &outline.tags[startIndex];

        endIndex = outline.contours[contourIndex];
        contourLength =  ( endIndex - startIndex) + 1;

        FTContour* contour = new FTContour( pointList, tagList, contourLength);

        contourList[contourIndex] = contour;

        startIndex = endIndex + 1;
    }
}

size_t FTVectoriser::PointCount()
{
    size_t s = 0;
    for( size_t c = 0; c < ContourCount(); ++c)
    {
        s += contourList[c]->PointCount();
    }

    return s;
}

const FTContour* FTVectoriser::Contour( unsigned int index) const
{
    return ( index < ContourCount()) ? contourList[index] : NULL;
}

void FTVectoriser::MakeMesh( FTGL_DOUBLE zNormal)
{
    if( mesh)
    {
        delete mesh;
    }

    mesh = new FTMesh;

    GLUtesselator* tobj = gluNewTess();

    gluTessCallback( tobj, GLU_TESS_BEGIN_DATA,     (GLUTesselatorFunction)ftglBegin);
    gluTessCallback( tobj, GLU_TESS_VERTEX_DATA,    (GLUTesselatorFunction)ftglVertex);
    gluTessCallback( tobj, GLU_TESS_COMBINE_DATA,   (GLUTesselatorFunction)ftglCombine);
    gluTessCallback( tobj, GLU_TESS_END_DATA,       (GLUTesselatorFunction)ftglEnd);
    gluTessCallback( tobj, GLU_TESS_ERROR_DATA,     (GLUTesselatorFunction)ftglError);

    if( contourFlag & ft_outline_even_odd_fill) // ft_outline_reverse_fill
    {
        gluTessProperty( tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_ODD);
    }
    else
    {
        gluTessProperty( tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_NONZERO);
    }

    gluTessProperty( tobj, GLU_TESS_TOLERANCE, 0);
    gluTessNormal( tobj, 0.0f, 0.0f, zNormal);
    gluTessBeginPolygon( tobj, mesh);

        for( size_t c = 0; c < ContourCount(); ++c)
        {
            const FTContour* contour = contourList[c];

            gluTessBeginContour( tobj);

                for( size_t p = 0; p < contour->PointCount(); ++p)
                {
                    const FTGL_DOUBLE* d = contour->Point(p);
                    gluTessVertex( tobj, (GLdouble*)d, (GLdouble*)d);
                }

            gluTessEndContour( tobj);
        }

    gluTessEndPolygon( tobj);

    gluDeleteTess( tobj);
}

<commit_msg>port to Mac OS X 10.5 preview.<commit_after>#include    "FTVectoriser.h"
#include    "FTGL.h"

#ifndef CALLBACK
#define CALLBACK
#endif

#if defined(__APPLE_CC__) && __APPLE_CC__ < 5450 && !defined(__INTEL_COMPILER)
    typedef GLvoid (*GLUTesselatorFunction)(...);
#elif defined( __mips ) || defined( __linux__ ) || defined( __FreeBSD__ ) || defined( __OpenBSD__ ) || defined( __sun ) || defined (__CYGWIN__) || defined (__APPLE__)
    typedef GLvoid (*GLUTesselatorFunction)();
#elif defined ( WIN32)
    typedef GLvoid (CALLBACK *GLUTesselatorFunction)( );
#else
    #error "Error - need to define type GLUTesselatorFunction for this platform/compiler"
#endif

void CALLBACK ftglError( GLenum errCode, FTMesh* mesh)
{
    mesh->Error( errCode);
}

void CALLBACK ftglVertex( void* data, FTMesh* mesh)
{
    FTGL_DOUBLE* vertex = static_cast<FTGL_DOUBLE*>(data);
    mesh->AddPoint( vertex[0], vertex[1], vertex[2]);
}

void CALLBACK ftglCombine( FTGL_DOUBLE coords[3], void* /*vertex_data[4]*/, GLfloat /*weight[4]*/, void** outData, FTMesh* mesh)
{
    const FTGL_DOUBLE* vertex = static_cast<const FTGL_DOUBLE*>(coords);
    *outData = const_cast<FTGL_DOUBLE*>(mesh->Combine( vertex[0], vertex[1], vertex[2]));
}

void CALLBACK ftglBegin( GLenum type, FTMesh* mesh)
{
    mesh->Begin( type);
}

void CALLBACK ftglEnd( FTMesh* mesh)
{
    mesh->End();
}

FTMesh::FTMesh()
:	currentTesselation(0),
    err(0)
{
    tesselationList.reserve( 16);
}

FTMesh::~FTMesh()
{
    for( size_t t = 0; t < tesselationList.size(); ++t)
    {
        delete tesselationList[t];
    }

    tesselationList.clear();
}

void FTMesh::AddPoint( const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z)
{
    currentTesselation->AddPoint( x, y, z);
}

const FTGL_DOUBLE* FTMesh::Combine( const FTGL_DOUBLE x, const FTGL_DOUBLE y, const FTGL_DOUBLE z)
{
    tempPointList.push_back( FTPoint( x, y,z));
    return static_cast<const FTGL_DOUBLE*>(tempPointList.back());
}

void FTMesh::Begin( GLenum meshType)
{
    currentTesselation = new FTTesselation( meshType);
}

void FTMesh::End()
{
    tesselationList.push_back( currentTesselation);
}

const FTTesselation* FTMesh::Tesselation( unsigned int index) const
{
    return ( index < tesselationList.size()) ? tesselationList[index] : NULL;
}

FTVectoriser::FTVectoriser( const FT_GlyphSlot glyph)
:   contourList(0),
    mesh(0),
    ftContourCount(0),
    contourFlag(0)
{
    if( glyph)
    {
        outline = glyph->outline;

        ftContourCount = outline.n_contours;
        contourList = 0;
        contourFlag = outline.flags;

        ProcessContours();
    }
}

FTVectoriser::~FTVectoriser()
{
    for( size_t c = 0; c < ContourCount(); ++c)
    {
        delete contourList[c];
    }

    delete [] contourList;
    delete mesh;
}

void FTVectoriser::ProcessContours()
{
    short contourLength = 0;
    short startIndex = 0;
    short endIndex = 0;

    contourList = new FTContour*[ftContourCount];

    for( short contourIndex = 0; contourIndex < ftContourCount; ++contourIndex)
    {
        FT_Vector* pointList = &outline.points[startIndex];
        char* tagList = &outline.tags[startIndex];

        endIndex = outline.contours[contourIndex];
        contourLength =  ( endIndex - startIndex) + 1;

        FTContour* contour = new FTContour( pointList, tagList, contourLength);

        contourList[contourIndex] = contour;

        startIndex = endIndex + 1;
    }
}

size_t FTVectoriser::PointCount()
{
    size_t s = 0;
    for( size_t c = 0; c < ContourCount(); ++c)
    {
        s += contourList[c]->PointCount();
    }

    return s;
}

const FTContour* FTVectoriser::Contour( unsigned int index) const
{
    return ( index < ContourCount()) ? contourList[index] : NULL;
}

void FTVectoriser::MakeMesh( FTGL_DOUBLE zNormal)
{
    if( mesh)
    {
        delete mesh;
    }

    mesh = new FTMesh;

    GLUtesselator* tobj = gluNewTess();

    gluTessCallback( tobj, GLU_TESS_BEGIN_DATA,     (GLUTesselatorFunction)ftglBegin);
    gluTessCallback( tobj, GLU_TESS_VERTEX_DATA,    (GLUTesselatorFunction)ftglVertex);
    gluTessCallback( tobj, GLU_TESS_COMBINE_DATA,   (GLUTesselatorFunction)ftglCombine);
    gluTessCallback( tobj, GLU_TESS_END_DATA,       (GLUTesselatorFunction)ftglEnd);
    gluTessCallback( tobj, GLU_TESS_ERROR_DATA,     (GLUTesselatorFunction)ftglError);

    if( contourFlag & ft_outline_even_odd_fill) // ft_outline_reverse_fill
    {
        gluTessProperty( tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_ODD);
    }
    else
    {
        gluTessProperty( tobj, GLU_TESS_WINDING_RULE, GLU_TESS_WINDING_NONZERO);
    }

    gluTessProperty( tobj, GLU_TESS_TOLERANCE, 0);
    gluTessNormal( tobj, 0.0f, 0.0f, zNormal);
    gluTessBeginPolygon( tobj, mesh);

        for( size_t c = 0; c < ContourCount(); ++c)
        {
            const FTContour* contour = contourList[c];

            gluTessBeginContour( tobj);

                for( size_t p = 0; p < contour->PointCount(); ++p)
                {
                    const FTGL_DOUBLE* d = contour->Point(p);
                    gluTessVertex( tobj, (GLdouble*)d, (GLdouble*)d);
                }

            gluTessEndContour( tobj);
        }

    gluTessEndPolygon( tobj);

    gluDeleteTess( tobj);
}

<|endoftext|>


<commit_before>/*

either keep finding the exchange rate between all pairs of previously seen items, or build a graph and for each query search for a path between the items, multiply along the chain and reduce (with gcd)
	shortest path doesn't matter, there's no contradictory assertions. But also links are unweighted in terms of search so if calculating along a link is a problem, use BFS (will minimize gcd/lcm usages too).
		<=60 items (nodes), at most 1 assertion per pair so < 3600 assertions (edges), BFS should be fine
	partner's template included gcd, see submission for lesson 6

*/

#include <iostream>
#include <algorithm>
#include <string>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <utility> // pair
#include <cmath>

using namespace std;

typedef long long ll;
typedef struct {
	ll num;
	ll den;
} ratio;

set<string> items;
map<string,int> nodenum;
int item_n = 0;
vector<vector<pair<int,ratio>>> g;

ll gcd(ll a, ll b, ll &x, ll &y)
{
    if (a == 0)
    {
        x = 0;
        y = 1;
        return b;
    }
    ll x1, y1;
    ll d = gcd(b%a, a, x1, y1);
    x = y1 - (b / a) * x1;
    y = x1;
    return d;
}

inline ll gcd(ll a, ll b) { return gcd(a, b, a, b); }

// reduced multiplied ratio
ratio rmul(ratio r1, ratio r2){
	ll num = r1.num * r2.num;
	ll den = r1.den * r2.den;
	ratio mulled = {num / gcd(num,den), den / gcd(num,den)};
	return mulled;
}

// BFS
// input: an adjacency list describing an undirected/directed graph (g)
// output: the distance of each node from s (dist)
// visible indicates which vertices where already seen
vector<int> visible;
vector<ratio> pathratio;
void bfs(int s, int t)
{
    queue<int> q;
    q.push(s);
    visible[s]=1;
    pathratio[s]={1,1};
    while (!q.empty()) {
        int cur=q.front();
        q.pop();
        for(auto& ver :g[cur])
        {
            if(visible[ver.first]!=0)continue;
            visible[ver.first]=1;
            pathratio[ver.first] = rmul(pathratio[cur], ver.second); // note
			if(ver.first == t){
				break;
			}
            q.push(ver.first);
        }
    }
}

int main() {
	char linetype, chaff;
	string item1, item2;
	int nof1, nof2;
	while(cin >> linetype) {
		if(linetype == '.'){
			break;
		}
		if(linetype == '!'){
			cin >> nof1 >> item1 >> chaff >> nof2 >> item2;
			if(items.find(item1) == items.end()){ // if haven't seen this one before
				items.insert(item1);
				nodenum[item1] = item_n;
				g.push_back(vector<pair<int,ratio>>());
				item_n++;
			}
			if(items.find(item2) == items.end()){ // if haven't seen this one before
				items.insert(item2);
				nodenum[item2] = item_n;
				g.push_back(vector<pair<int,ratio>>());
				item_n++;
			}
			ratio r1 = {nof1, nof2};
			ratio r2 = {nof2, nof1}; // reverse edge
			g[nodenum[item1]].push_back(make_pair(nodenum[item2],r1));
			g[nodenum[item2]].push_back(make_pair(nodenum[item1],r2));
		}
		else{// linetype == '?'
			cin >> item1 >> chaff >> item2;
			// assume both there?
			visible = vector<int>(item_n,0);
			ratio r0 = {0,1};
			pathratio = vector<ratio>(item_n,r0);
			bfs(nodenum[item1], nodenum[item2]);
			if(visible[nodenum[item2]]){
				ratio rres = pathratio[nodenum[item2]];
				cout << rres.num << " " << item1 << " = " << rres.den << " " << item2 << endl;
			}
			else{
				cout << "?" << " " << item1 << " = " << "?" << " " << item2 << endl;
			}
		}
	}
	return 0;
}
<commit_msg>ICPC: 5331 - Exchange Rates<commit_after>/*

either keep finding the exchange rate between all pairs of previously seen items, or build a graph and for each query search for a path between the items, multiply along the chain and reduce (with gcd)
	shortest path doesn't matter, there's no contradictory assertions. But also links are unweighted in terms of search so if calculating along a link is a problem, use BFS (will minimize gcd/lcm usages too).
		<=60 items (nodes), at most 1 assertion per pair so < 3600 assertions (edges), BFS should be fine
	partner's template included gcd, see submission for lesson 6

*/

#include <iostream>
#include <set>
#include <vector>
#include <map>
#include <queue>
#include <utility> // pair

using namespace std;

typedef long long ll;
typedef struct {
	ll num;
	ll den;
} ratio;

set<string> items;
map<string,int> nodenum;
int item_n = 0;
vector<vector<pair<int,ratio>>> g;

ll gcd(ll a, ll b, ll &x, ll &y)
{
    if (a == 0)
    {
        x = 0;
        y = 1;
        return b;
    }
    ll x1, y1;
    ll d = gcd(b%a, a, x1, y1);
    x = y1 - (b / a) * x1;
    y = x1;
    return d;
}

inline ll gcd(ll a, ll b) { return gcd(a, b, a, b); }

// reduced multiplied ratio
ratio rmul(ratio r1, ratio r2){
	ll num = r1.num * r2.num;
	ll den = r1.den * r2.den;
	ll nd_gcd = gcd(num,den);
	ratio mulled = {num / nd_gcd, den / nd_gcd};
	return mulled;
}

// BFS
// input: an adjacency list describing an undirected/directed graph (g)
// output: the distance of each node from s (dist)
// visible indicates which vertices where already seen
vector<int> visible;
vector<ratio> pathratio;
void bfs(int s, int t)
{
    queue<int> q;
    q.push(s);
    visible[s]=1;
    pathratio[s]={1,1};
    while (!q.empty()) {
        int cur=q.front();
        q.pop();
        for(auto& ver :g[cur])
        {
            if(visible[ver.first]!=0)continue;
            visible[ver.first]=1;
            pathratio[ver.first] = rmul(pathratio[cur], ver.second); // note
			if(ver.first == t){
				break;
			}
            q.push(ver.first);
        }
    }
}

int main() {
	char linetype, chaff;
	string item1, item2;
	int nof1, nof2;
	while(cin >> linetype) {
		if(linetype == '.'){
			break;
		}
		if(linetype == '!'){
			cin >> nof1 >> item1 >> chaff >> nof2 >> item2;
			if(items.find(item1) == items.end()){ // if haven't seen this one before
				items.insert(item1);
				nodenum[item1] = item_n;
				g.push_back(vector<pair<int,ratio>>());
				item_n++;
			}
			if(items.find(item2) == items.end()){ // if haven't seen this one before
				items.insert(item2);
				nodenum[item2] = item_n;
				g.push_back(vector<pair<int,ratio>>());
				item_n++;
			}
			ratio r1 = {nof1, nof2};
			ratio r2 = {nof2, nof1}; // reverse edge
			g[nodenum[item1]].push_back(make_pair(nodenum[item2],r1));
			g[nodenum[item2]].push_back(make_pair(nodenum[item1],r2));
		}
		else{// linetype == '?'
			cin >> item1 >> chaff >> item2;
			// assume both there?
			visible = vector<int>(item_n,0);
			ratio r0 = {0,1};
			pathratio = vector<ratio>(item_n,r0);
			bfs(nodenum[item1], nodenum[item2]);
			if(visible[nodenum[item2]]){
				ratio rres = pathratio[nodenum[item2]];
				cout << rres.num << " " << item1 << " = " << rres.den << " " << item2 << endl;
			}
			else{
				cout << "?" << " " << item1 << " = " << "?" << " " << item2 << endl;
			}
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>/*
 * File:   AfUnixCommunicator.cpp
 * Author: cjg
 *
 * Created on 30 settembre 2009, 12.01
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "AfUnixCommunicator.h"

using namespace std;

AfUnixCommunicator::AfUnixCommunicator(string &path) {
    mPath = path;
}

AfUnixCommunicator::AfUnixCommunicator(int fd) {
    mSocketFd = fd;
    InitializeStream();
}

AfUnixCommunicator::AfUnixCommunicator(const char *path) {
    mPath = path;
}

AfUnixCommunicator::~AfUnixCommunicator() {
    // TODO Auto-generated destructor stub
}

void AfUnixCommunicator::Serve() {
    struct sockaddr_un socket_addr;

    unlink(mPath.c_str());

    if ((mSocketFd = socket(AF_UNIX, SOCK_STREAM, 0)) == 0)
        throw "AfUnixCommunicator: Can't create socket.";

    socket_addr.sun_family = AF_UNIX;
    strcpy(socket_addr.sun_path, mPath.c_str());

    if (bind(mSocketFd, (struct sockaddr *) & socket_addr,
            sizeof (struct sockaddr_un)) != 0)
        throw "AfUnixCommunicator: Can't bind socket.";

    if (listen(mSocketFd, 5) != 0)
        throw "AfUnixCommunicator: Can't listen from socket.";
}

const Communicator * const AfUnixCommunicator::Accept() const {
    unsigned client_socket_fd;
    struct sockaddr_un client_socket_addr;
    unsigned client_socket_addr_size;

    client_socket_addr_size = sizeof (struct sockaddr_un);
    if ((client_socket_fd = accept(mSocketFd,
        (sockaddr *) & client_socket_addr,
        &client_socket_addr_size)) == 0)
        throw "AfUnixCommunicator: Error while accepting connection.";

    return new AfUnixCommunicator(client_socket_fd);
}

void AfUnixCommunicator::Connect() {
    int len;
    struct sockaddr_un remote;

    mSocketFd = socket(AF_UNIX, SOCK_STREAM, 0);
    remote.sun_family = AF_UNIX;
    strcpy(remote.sun_path, mPath.c_str());
    len = strlen(remote.sun_path) + sizeof (remote.sun_family);
    if (connect(mSocketFd, (struct sockaddr *) & remote, len) != 0)
        throw "AfUnixCommunicator: Can't connect to socket.";
    InitializeStream();
}

void AfUnixCommunicator::Close() {
}

std::istream & AfUnixCommunicator::GetInputStream() const {
    return *(this->mpInput);
}

std::ostream & AfUnixCommunicator::GetOutputStream() const {
    return *(this->mpOutput);
}

void AfUnixCommunicator::InitializeStream() {
    mpInputBuf = new __gnu_cxx::stdio_filebuf<char>(mSocketFd,
            std::ios_base::in);
    mpOutputBuf = new __gnu_cxx::stdio_filebuf<char>(mSocketFd,
            std::ios_base::out);
    mpInput = new istream(mpInputBuf);
    mpOutput = new ostream(mpOutputBuf);
}
<commit_msg>fixed issue in calculating socket len in AfUnixCommunicator::Connect<commit_after>/*
 * File:   AfUnixCommunicator.cpp
 * Author: cjg
 *
 * Created on 30 settembre 2009, 12.01
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "AfUnixCommunicator.h"

using namespace std;

AfUnixCommunicator::AfUnixCommunicator(string &path) {
    mPath = path;
}

AfUnixCommunicator::AfUnixCommunicator(int fd) {
    mSocketFd = fd;
    InitializeStream();
}

AfUnixCommunicator::AfUnixCommunicator(const char *path) {
    mPath = string(path);
}

AfUnixCommunicator::~AfUnixCommunicator() {
    // TODO Auto-generated destructor stub
}

void AfUnixCommunicator::Serve() {
    struct sockaddr_un socket_addr;

    unlink(mPath.c_str());

    if ((mSocketFd = socket(AF_UNIX, SOCK_STREAM, 0)) == 0)
        throw "AfUnixCommunicator: Can't create socket.";

    socket_addr.sun_family = AF_UNIX;
    strcpy(socket_addr.sun_path, mPath.c_str());

    if (bind(mSocketFd, (struct sockaddr *) & socket_addr,
            sizeof (struct sockaddr_un)) != 0)
        throw "AfUnixCommunicator: Can't bind socket.";

    if (listen(mSocketFd, 5) != 0)
        throw "AfUnixCommunicator: Can't listen from socket.";
}

const Communicator * const AfUnixCommunicator::Accept() const {
    unsigned client_socket_fd;
    struct sockaddr_un client_socket_addr;
    unsigned client_socket_addr_size;

    client_socket_addr_size = sizeof (struct sockaddr_un);
    if ((client_socket_fd = accept(mSocketFd,
        (sockaddr *) & client_socket_addr,
        &client_socket_addr_size)) == 0)
        throw "AfUnixCommunicator: Error while accepting connection.";

    return new AfUnixCommunicator(client_socket_fd);
}

void AfUnixCommunicator::Connect() {
    int len;
    struct sockaddr_un remote;

    if((mSocketFd = socket(AF_UNIX, SOCK_STREAM, 0)) == 0)
        throw "AfUnixCommunicator: Can't create socket.";

    remote.sun_family = AF_UNIX;
    strcpy(remote.sun_path, mPath.c_str());
    len = offsetof(struct sockaddr_un, sun_path) + strlen(remote.sun_path);
    if (connect(mSocketFd, (struct sockaddr *) & remote, len) != 0)
        throw "AfUnixCommunicator: Can't connect to socket.";
    InitializeStream();
}

void AfUnixCommunicator::Close() {
}

std::istream & AfUnixCommunicator::GetInputStream() const {
    return *(this->mpInput);
}

std::ostream & AfUnixCommunicator::GetOutputStream() const {
    return *(this->mpOutput);
}

void AfUnixCommunicator::InitializeStream() {
    mpInputBuf = new __gnu_cxx::stdio_filebuf<char>(mSocketFd,
            std::ios_base::in);
    mpOutputBuf = new __gnu_cxx::stdio_filebuf<char>(mSocketFd,
            std::ios_base::out);
    mpInput = new istream(mpInputBuf);
    mpOutput = new ostream(mpOutputBuf);
}
<|endoftext|>


<commit_before>#pragma once

#include <eosio/chain/types.hpp>
#include <eosio/chain/config.hpp>

namespace eosio { namespace chain {

/**
 * @brief Producer-voted blockchain configuration parameters
 *
 * This object stores the blockchain configuration, which is set by the block producers. Block producers each vote for
 * their preference for each of the parameters in this object, and the blockchain runs according to the median of the
 * values specified by the producers.
 */
struct chain_config {
   uint64_t   max_block_net_usage;                  ///< the maxiumum net usage in instructions for a block
   uint32_t   target_block_net_usage_pct;           ///< the target percent (1% == 100, 100%= 10,000) of maximum net usage; exceeding this triggers congestion handling
   uint32_t   max_transaction_net_usage;            ///< the maximum objectively measured net usage that the chain will allow regardless of account limits
   uint32_t   base_per_transaction_net_usage;       ///< the base amount of net usage billed for a transaction to cover incidentals
   uint32_t   net_usage_leeway;
   uint32_t   context_free_discount_net_usage_num;  ///< the numerator for the discount on net usage of context-free data
   uint32_t   context_free_discount_net_usage_den;  ///< the denominator for the discount on net usage of context-free data

   uint32_t   max_block_cpu_usage;                  ///< the maxiumum billable cpu usage (in microseconds) for a block
   uint32_t   target_block_cpu_usage_pct;           ///< the target percent (1% == 100, 100%= 10,000) of maximum cpu usage; exceeding this triggers congestion handling
   uint32_t   max_transaction_cpu_usage;            ///< the maximum billable cpu usage (in microseconds) that the chain will allow regardless of account limits
   uint32_t   min_transaction_cpu_usage;            ///< the minimum billable cpu usage (in microseconds) that the chain requires

   uint32_t   max_transaction_lifetime;             ///< the maximum number of seconds that an input transaction's expiration can be ahead of the time of the block in which it is first included
   uint32_t   deferred_trx_expiration_window;       ///< the number of seconds after the time a deferred transaction can first execute until it expires
   uint32_t   max_transaction_delay;                ///< the maximum number of seconds that can be imposed as a delay requirement by authorization checks
   uint32_t   max_inline_action_size;               ///< maximum allowed size (in bytes) of an inline action
   uint16_t   max_inline_action_depth;              ///< recursion depth limit on sending inline actions
   uint16_t   max_authority_depth;                  ///< recursion depth limit for checking if an authority is satisfied

   void validate()const;

   template<typename Stream>
   friend Stream& operator << ( Stream& out, const chain_config& c ) {
      return out << "Max Block Net Usage: " << c.max_block_net_usage << ", "
                 << "Target Block Net Usage Percent: " << ((double)c.target_block_net_usage_pct / (double)config::percent_1) << "%, "
                 << "Max Transaction Net Usage: " << c.max_transaction_net_usage << ", "
                 << "Base Per-Transaction Net Usage: " << c.base_per_transaction_net_usage << ", "
                 << "Net Usage Leeway: " << c.net_usage_leeway << ", "
                 << "Context-Free Data Net Usage Discount: " << (double)c.context_free_discount_net_usage_num * 100.0 / (double)c.context_free_discount_net_usage_den << "% , "

                 << "Max Block CPU Usage: " << c.max_block_cpu_usage << ", "
                 << "Target Block CPU Usage Percent: " << ((double)c.target_block_cpu_usage_pct / (double)config::percent_1) << "%, "
                 << "Max Transaction CPU Usage: " << c.max_transaction_cpu_usage << ", "
                 << "Min Transaction CPU Usage: " << c.min_transaction_cpu_usage << ", "

                 << "Max Transaction Lifetime: " << c.max_transaction_lifetime << ", "
                 << "Deferred Transaction Expiration Window: " << c.deferred_trx_expiration_window << ", "
                 << "Max Transaction Delay: " << c.max_transaction_delay << ", "
                 << "Max Inline Action Size: " << c.max_inline_action_size << ", "
                 << "Max Inline Action Depth: " << c.max_inline_action_depth << ", "
                 << "Max Authority Depth: " << c.max_authority_depth << "\n";
   }

   friend inline bool operator ==( const chain_config& lhs, const chain_config& rhs ) {
      return   std::tie(   lhs.max_block_net_usage,
                           lhs.target_block_net_usage_pct,
                           lhs.max_transaction_net_usage,
                           lhs.base_per_transaction_net_usage,
                           lhs.net_usage_leeway,
                           lhs.context_free_discount_net_usage_num,
                           lhs.context_free_discount_net_usage_den,
                           lhs.max_block_cpu_usage,
                           lhs.target_block_cpu_usage_pct,
                           lhs.max_transaction_cpu_usage,
                           lhs.max_transaction_cpu_usage,
                           lhs.max_transaction_lifetime,
                           lhs.deferred_trx_expiration_window,
                           lhs.max_transaction_delay,
                           lhs.max_inline_action_size,
                           lhs.max_inline_action_depth,
                           lhs.max_authority_depth
                        )
               ==
               std::tie(   rhs.max_block_net_usage,
                           rhs.target_block_net_usage_pct,
                           rhs.max_transaction_net_usage,
                           rhs.base_per_transaction_net_usage,
                           rhs.net_usage_leeway,
                           rhs.context_free_discount_net_usage_num,
                           rhs.context_free_discount_net_usage_den,
                           rhs.max_block_cpu_usage,
                           rhs.target_block_cpu_usage_pct,
                           rhs.max_transaction_cpu_usage,
                           rhs.max_transaction_cpu_usage,
                           rhs.max_transaction_lifetime,
                           rhs.deferred_trx_expiration_window,
                           rhs.max_transaction_delay,
                           rhs.max_inline_action_size,
                           rhs.max_inline_action_depth,
                           rhs.max_authority_depth
                        );
   };

   friend inline bool operator !=( const chain_config& lhs, const chain_config& rhs ) { return !(lhs == rhs); }

};

} } // namespace eosio::chain

FC_REFLECT(eosio::chain::chain_config,
           (max_block_net_usage)(target_block_net_usage_pct)
           (max_transaction_net_usage)(base_per_transaction_net_usage)(net_usage_leeway)
           (context_free_discount_net_usage_num)(context_free_discount_net_usage_den)

           (max_block_cpu_usage)(target_block_cpu_usage_pct)
           (max_transaction_cpu_usage)(min_transaction_cpu_usage)

           (max_transaction_lifetime)(deferred_trx_expiration_window)(max_transaction_delay)
           (max_inline_action_size)(max_inline_action_depth)(max_authority_depth)
)
<commit_msg>Revert eventually spurious whitespace changes to chain_config.hpp<commit_after>#pragma once

#include <eosio/chain/types.hpp>
#include <eosio/chain/config.hpp>

namespace eosio { namespace chain {

/**
 * @brief Producer-voted blockchain configuration parameters
 *
 * This object stores the blockchain configuration, which is set by the block producers. Block producers each vote for
 * their preference for each of the parameters in this object, and the blockchain runs according to the median of the
 * values specified by the producers.
 */
struct chain_config {
   uint64_t   max_block_net_usage;                 ///< the maxiumum net usage in instructions for a block
   uint32_t   target_block_net_usage_pct;          ///< the target percent (1% == 100, 100%= 10,000) of maximum net usage; exceeding this triggers congestion handling
   uint32_t   max_transaction_net_usage;           ///< the maximum objectively measured net usage that the chain will allow regardless of account limits
   uint32_t   base_per_transaction_net_usage;      ///< the base amount of net usage billed for a transaction to cover incidentals
   uint32_t   net_usage_leeway;
   uint32_t   context_free_discount_net_usage_num; ///< the numerator for the discount on net usage of context-free data
   uint32_t   context_free_discount_net_usage_den; ///< the denominator for the discount on net usage of context-free data

   uint32_t   max_block_cpu_usage;                 ///< the maxiumum billable cpu usage (in microseconds) for a block
   uint32_t   target_block_cpu_usage_pct;          ///< the target percent (1% == 100, 100%= 10,000) of maximum cpu usage; exceeding this triggers congestion handling
   uint32_t   max_transaction_cpu_usage;           ///< the maximum billable cpu usage (in microseconds) that the chain will allow regardless of account limits
   uint32_t   min_transaction_cpu_usage;           ///< the minimum billable cpu usage (in microseconds) that the chain requires

   uint32_t   max_transaction_lifetime;            ///< the maximum number of seconds that an input transaction's expiration can be ahead of the time of the block in which it is first included
   uint32_t   deferred_trx_expiration_window;      ///< the number of seconds after the time a deferred transaction can first execute until it expires
   uint32_t   max_transaction_delay;               ///< the maximum number of seconds that can be imposed as a delay requirement by authorization checks
   uint32_t   max_inline_action_size;              ///< maximum allowed size (in bytes) of an inline action
   uint16_t   max_inline_action_depth;             ///< recursion depth limit on sending inline actions
   uint16_t   max_authority_depth;                 ///< recursion depth limit for checking if an authority is satisfied

   void validate()const;

   template<typename Stream>
   friend Stream& operator << ( Stream& out, const chain_config& c ) {
      return out << "Max Block Net Usage: " << c.max_block_net_usage << ", "
                 << "Target Block Net Usage Percent: " << ((double)c.target_block_net_usage_pct / (double)config::percent_1) << "%, "
                 << "Max Transaction Net Usage: " << c.max_transaction_net_usage << ", "
                 << "Base Per-Transaction Net Usage: " << c.base_per_transaction_net_usage << ", "
                 << "Net Usage Leeway: " << c.net_usage_leeway << ", "
                 << "Context-Free Data Net Usage Discount: " << (double)c.context_free_discount_net_usage_num * 100.0 / (double)c.context_free_discount_net_usage_den << "% , "

                 << "Max Block CPU Usage: " << c.max_block_cpu_usage << ", "
                 << "Target Block CPU Usage Percent: " << ((double)c.target_block_cpu_usage_pct / (double)config::percent_1) << "%, "
                 << "Max Transaction CPU Usage: " << c.max_transaction_cpu_usage << ", "
                 << "Min Transaction CPU Usage: " << c.min_transaction_cpu_usage << ", "

                 << "Max Transaction Lifetime: " << c.max_transaction_lifetime << ", "
                 << "Deferred Transaction Expiration Window: " << c.deferred_trx_expiration_window << ", "
                 << "Max Transaction Delay: " << c.max_transaction_delay << ", "
                 << "Max Inline Action Size: " << c.max_inline_action_size << ", "
                 << "Max Inline Action Depth: " << c.max_inline_action_depth << ", "
                 << "Max Authority Depth: " << c.max_authority_depth << "\n";
   }

   friend inline bool operator ==( const chain_config& lhs, const chain_config& rhs ) {
      return   std::tie(   lhs.max_block_net_usage,
                           lhs.target_block_net_usage_pct,
                           lhs.max_transaction_net_usage,
                           lhs.base_per_transaction_net_usage,
                           lhs.net_usage_leeway,
                           lhs.context_free_discount_net_usage_num,
                           lhs.context_free_discount_net_usage_den,
                           lhs.max_block_cpu_usage,
                           lhs.target_block_cpu_usage_pct,
                           lhs.max_transaction_cpu_usage,
                           lhs.max_transaction_cpu_usage,
                           lhs.max_transaction_lifetime,
                           lhs.deferred_trx_expiration_window,
                           lhs.max_transaction_delay,
                           lhs.max_inline_action_size,
                           lhs.max_inline_action_depth,
                           lhs.max_authority_depth
                        )
               ==
               std::tie(   rhs.max_block_net_usage,
                           rhs.target_block_net_usage_pct,
                           rhs.max_transaction_net_usage,
                           rhs.base_per_transaction_net_usage,
                           rhs.net_usage_leeway,
                           rhs.context_free_discount_net_usage_num,
                           rhs.context_free_discount_net_usage_den,
                           rhs.max_block_cpu_usage,
                           rhs.target_block_cpu_usage_pct,
                           rhs.max_transaction_cpu_usage,
                           rhs.max_transaction_cpu_usage,
                           rhs.max_transaction_lifetime,
                           rhs.deferred_trx_expiration_window,
                           rhs.max_transaction_delay,
                           rhs.max_inline_action_size,
                           rhs.max_inline_action_depth,
                           rhs.max_authority_depth
                        );
   };

   friend inline bool operator !=( const chain_config& lhs, const chain_config& rhs ) { return !(lhs == rhs); }

};

} } // namespace eosio::chain

FC_REFLECT(eosio::chain::chain_config,
           (max_block_net_usage)(target_block_net_usage_pct)
           (max_transaction_net_usage)(base_per_transaction_net_usage)(net_usage_leeway)
           (context_free_discount_net_usage_num)(context_free_discount_net_usage_den)

           (max_block_cpu_usage)(target_block_cpu_usage_pct)
           (max_transaction_cpu_usage)(min_transaction_cpu_usage)

           (max_transaction_lifetime)(deferred_trx_expiration_window)(max_transaction_delay)
           (max_inline_action_size)(max_inline_action_depth)(max_authority_depth)

)
<|endoftext|>


<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include <vector>
#include "DecartaSearchService.h"
#include "ISearchResultParser.h"
#include "Types.h"
#include "IWebLoadRequest.h"
#include "LatLongAltitude.h"
#include "SearchResultModel.h"
#include "IWebLoadRequestFactory.h"
#include "WebLoadRequestCompletionCallback.h"
#include "SearchQuery.h"
#include "Logger.h"

namespace ExampleApp
{
    namespace Search
    {
        namespace Decarta
        {
            DecartaSearchService::DecartaSearchService(const std::string& decartaApiKey,
                    SdkModel::ISearchResultParser& parser,
                    Eegeo::Helpers::UrlHelpers::IUrlEncoder& urlEncoder,
                    Eegeo::Web::IWebLoadRequestFactory& webRequestFactory)
                : m_decartaApiKey(decartaApiKey)
                , m_parser(parser)
                , m_webRequestFactory(webRequestFactory)
                , m_urlEncoder(urlEncoder)
                , m_pPoiSearchCallback(Eegeo_NEW(Eegeo::Web::TWebLoadRequestCompletionCallback<DecartaSearchService>)(this, &DecartaSearchService::HandleSearchResponse))
                , m_pCurrentRequest(NULL)
            {
            }

            DecartaSearchService::~DecartaSearchService()
            {
                CancelInFlightQueries();
                Eegeo_DELETE m_pPoiSearchCallback;
            }

            void DecartaSearchService::CancelInFlightQueries()
            {
                if(m_pCurrentRequest != NULL)
                {
                    std::vector<SdkModel::SearchResultModel> results;
                    SdkModel::SearchQuery* pRequestBoundQuery = static_cast<SdkModel::SearchQuery*>(m_pCurrentRequest->GetUserData());
                    ExecutQueryResponseReceivedCallbacks(*pRequestBoundQuery, results);
                    Eegeo_DELETE pRequestBoundQuery;
                    m_pCurrentRequest->Cancel();
                    m_pCurrentRequest = NULL;
                }
            }

            void DecartaSearchService::PerformLocationQuerySearch(const SdkModel::SearchQuery& searchQuery)
            {
                CancelInFlightQueries();

                const std::string baseUrl =  "http://api.decarta.com/v1/";

                std::stringstream ss;
                ss << baseUrl;
                ss << m_decartaApiKey;

                if(searchQuery.IsCategory())
                {
                    // Some decarta categories from http://developer.decarta.com/Docs/REST/Search#category
                    EncodeApiQueryIntoStringStream(searchQuery.Query(), "/search/category/", ss);
                }
                else
                {
                    if(searchQuery.Query().empty())
                    {
                        // Ideally we could use the search API to perform a 'wildcard' search here to get all
                        // the POI results nearby, but deCarta does not support this feature. We could fake it
                        // by performing multiple searches for various categories from the deCarta category
                        // list, aggregating the results, but seems overly complex for this example.
                        return;
                    }
                    else
                    {
                        EncodeApiQueryIntoStringStream(searchQuery.Query(), "/search/", ss);
                    }
                }

                ss << "?lat=" << searchQuery.Location().GetLatitudeInDegrees();
                ss << "&lon=" << searchQuery.Location().GetLongitudeInDegrees();
                ss << "&radius=" << searchQuery.Radius();
                ss << "&limit=100";

                std::string url = ss.str();
                EXAMPLE_LOG("Search Request: %s\n", url.c_str());

                IssueRequest(url, searchQuery);

                ExecuteQueryPerformedCallbacks(searchQuery);
            }

            void DecartaSearchService::IssueRequest(const std::string queryUrl, const SdkModel::SearchQuery& query)
            {
                // Dynamically allocate a copy of the search query for association with the web request, as we do not know
                // the lifetime of the parameter, and we do not really want to store state when the lifetime is bound to the
                // request anyway.

                SdkModel::SearchQuery* pRequestBoundQuery = Eegeo_NEW(SdkModel::SearchQuery)(query.Query(),
                        query.IsCategory(),
                        query.Location(),
                        query.Radius());

                m_pCurrentRequest = m_webRequestFactory.CreateGet(queryUrl, *m_pPoiSearchCallback, pRequestBoundQuery);
                m_pCurrentRequest->SetTimeoutSeconds(10);
                m_pCurrentRequest->Load();
            }

            void DecartaSearchService::HandleSearchResponse(Eegeo::Web::IWebLoadRequest& webLoadRequest)
            {
                if(m_pCurrentRequest != NULL)
                {
                    std::vector<SdkModel::SearchResultModel> results;
                    SdkModel::SearchQuery* pRequestBoundQuery = static_cast<SdkModel::SearchQuery*>(webLoadRequest.GetUserData());

                    EXAMPLE_LOG("Search Response Code: %d\n", webLoadRequest.HttpStatusCode());

                    if(webLoadRequest.IsSucceeded())
                    {
                        size_t resultSize = webLoadRequest.GetResourceData().size();
                        std::string serialized(reinterpret_cast<char const*>(&(webLoadRequest.GetResourceData().front())), resultSize);

                        EXAMPLE_LOG("Search Response Body: %s\n", serialized.c_str());

                        m_parser.ParseSearchResults(serialized, results);
                    }

                    ExecutQueryResponseReceivedCallbacks(*pRequestBoundQuery, results);

                    // Must delete this query as we dynamically allocated it in DecartaSearchService::IssueRequest.
                    Eegeo_DELETE pRequestBoundQuery;
                    m_pCurrentRequest = NULL;
                }
            }

            void DecartaSearchService::EncodeApiQueryIntoStringStream(const std::string& query,
                    const std::string& apiPoint,
                    std::stringstream& out_stream)
            {
                out_stream << apiPoint;
                std::string encodedQuery;
                m_urlEncoder.UrlEncode(query, encodedQuery);
                out_stream << encodedQuery << ".json";
            }
        }
    }
}

<commit_msg>Re-order issue of callbacks when search query performed to occur immediately prior to request dispatch. There was a race here in that other parts of the code require the QueryPerformedCallbacks to have been executed prior to the execution of the response callback for the search query. This was generally always the case when performing real network IO, which masked the race. Now that a web request stub/proxy has been added that can immediately respond to requests in the request Load() call if criteria not met (e.g., stream only Wifi), the race is now exposed. It should be safe to execute the query performed callbacks immediately prior to the dispatch of the query.<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include <vector>
#include "DecartaSearchService.h"
#include "ISearchResultParser.h"
#include "Types.h"
#include "IWebLoadRequest.h"
#include "LatLongAltitude.h"
#include "SearchResultModel.h"
#include "IWebLoadRequestFactory.h"
#include "WebLoadRequestCompletionCallback.h"
#include "SearchQuery.h"
#include "Logger.h"

namespace ExampleApp
{
    namespace Search
    {
        namespace Decarta
        {
            DecartaSearchService::DecartaSearchService(const std::string& decartaApiKey,
                    SdkModel::ISearchResultParser& parser,
                    Eegeo::Helpers::UrlHelpers::IUrlEncoder& urlEncoder,
                    Eegeo::Web::IWebLoadRequestFactory& webRequestFactory)
                : m_decartaApiKey(decartaApiKey)
                , m_parser(parser)
                , m_webRequestFactory(webRequestFactory)
                , m_urlEncoder(urlEncoder)
                , m_pPoiSearchCallback(Eegeo_NEW(Eegeo::Web::TWebLoadRequestCompletionCallback<DecartaSearchService>)(this, &DecartaSearchService::HandleSearchResponse))
                , m_pCurrentRequest(NULL)
            {
            }

            DecartaSearchService::~DecartaSearchService()
            {
                CancelInFlightQueries();
                Eegeo_DELETE m_pPoiSearchCallback;
            }

            void DecartaSearchService::CancelInFlightQueries()
            {
                if(m_pCurrentRequest != NULL)
                {
                    std::vector<SdkModel::SearchResultModel> results;
                    SdkModel::SearchQuery* pRequestBoundQuery = static_cast<SdkModel::SearchQuery*>(m_pCurrentRequest->GetUserData());
                    ExecutQueryResponseReceivedCallbacks(*pRequestBoundQuery, results);
                    Eegeo_DELETE pRequestBoundQuery;
                    m_pCurrentRequest->Cancel();
                    m_pCurrentRequest = NULL;
                }
            }

            void DecartaSearchService::PerformLocationQuerySearch(const SdkModel::SearchQuery& searchQuery)
            {
                CancelInFlightQueries();

                const std::string baseUrl =  "http://api.decarta.com/v1/";

                std::stringstream ss;
                ss << baseUrl;
                ss << m_decartaApiKey;

                if(searchQuery.IsCategory())
                {
                    // Some decarta categories from http://developer.decarta.com/Docs/REST/Search#category
                    EncodeApiQueryIntoStringStream(searchQuery.Query(), "/search/category/", ss);
                }
                else
                {
                    if(searchQuery.Query().empty())
                    {
                        // Ideally we could use the search API to perform a 'wildcard' search here to get all
                        // the POI results nearby, but deCarta does not support this feature. We could fake it
                        // by performing multiple searches for various categories from the deCarta category
                        // list, aggregating the results, but seems overly complex for this example.
                        return;
                    }
                    else
                    {
                        EncodeApiQueryIntoStringStream(searchQuery.Query(), "/search/", ss);
                    }
                }

                ss << "?lat=" << searchQuery.Location().GetLatitudeInDegrees();
                ss << "&lon=" << searchQuery.Location().GetLongitudeInDegrees();
                ss << "&radius=" << searchQuery.Radius();
                ss << "&limit=100";

                std::string url = ss.str();
                EXAMPLE_LOG("Search Request: %s\n", url.c_str());

                ExecuteQueryPerformedCallbacks(searchQuery);

                IssueRequest(url, searchQuery);
            }

            void DecartaSearchService::IssueRequest(const std::string queryUrl, const SdkModel::SearchQuery& query)
            {
                // Dynamically allocate a copy of the search query for association with the web request, as we do not know
                // the lifetime of the parameter, and we do not really want to store state when the lifetime is bound to the
                // request anyway.

                SdkModel::SearchQuery* pRequestBoundQuery = Eegeo_NEW(SdkModel::SearchQuery)(query.Query(),
                        query.IsCategory(),
                        query.Location(),
                        query.Radius());

                m_pCurrentRequest = m_webRequestFactory.CreateGet(queryUrl, *m_pPoiSearchCallback, pRequestBoundQuery);
                m_pCurrentRequest->SetTimeoutSeconds(10);
                m_pCurrentRequest->Load();
            }

            void DecartaSearchService::HandleSearchResponse(Eegeo::Web::IWebLoadRequest& webLoadRequest)
            {
                if(m_pCurrentRequest != NULL)
                {
                    std::vector<SdkModel::SearchResultModel> results;
                    SdkModel::SearchQuery* pRequestBoundQuery = static_cast<SdkModel::SearchQuery*>(webLoadRequest.GetUserData());

                    EXAMPLE_LOG("Search Response Code: %d\n", webLoadRequest.HttpStatusCode());

                    if(webLoadRequest.IsSucceeded())
                    {
                        size_t resultSize = webLoadRequest.GetResourceData().size();
                        std::string serialized(reinterpret_cast<char const*>(&(webLoadRequest.GetResourceData().front())), resultSize);

                        EXAMPLE_LOG("Search Response Body: %s\n", serialized.c_str());

                        m_parser.ParseSearchResults(serialized, results);
                    }

                    ExecutQueryResponseReceivedCallbacks(*pRequestBoundQuery, results);

                    // Must delete this query as we dynamically allocated it in DecartaSearchService::IssueRequest.
                    Eegeo_DELETE pRequestBoundQuery;
                    m_pCurrentRequest = NULL;
                }
            }

            void DecartaSearchService::EncodeApiQueryIntoStringStream(const std::string& query,
                    const std::string& apiPoint,
                    std::stringstream& out_stream)
            {
                out_stream << apiPoint;
                std::string encodedQuery;
                m_urlEncoder.UrlEncode(query, encodedQuery);
                out_stream << encodedQuery << ".json";
            }
        }
    }
}

<|endoftext|>


<commit_before>/** @file */
#include "clientmanager.h"

/**
 * Raises a client to the layer above it.
 * @param window The client to raise
 */
void LayerManager::raise_layer(Window window)
{
    if (!m_clients->is_client(window))
        return;

    Layer current = m_layers[window];
    if (current < MAX_LAYER)
    {
        m_layers[window] += 10;
        m_clients->relayer();
    }
}

/**
 * Lowers a client to the layer below it.
 * @param window The client to lower
 */
void LayerManager::lower_layer(Window window)
{
    if (!m_clients->is_client(window))
        return;

    Layer current = m_layers[window];
    if (current > MIN_LAYER)
    {
        m_layers[window] -= 10;
        m_clients->relayer();
    }
}

/**
 * Shifts the layer of a window up/down by a certain value.
 * @param window The window of a client
 * @param offset The z-layer to shift by.
 */
void LayerManager::adjust_layer(Window window, LayerDiff layer)
{
    Layer new_layer = m_layers[window] + layer;
    if (new_layer >= MIN_LAYER && new_layer <= MAX_LAYER)
    {
        m_layers[window] = new_layer;
        m_clients->relayer();
    }
}

/**
 * Sets the layer of a client.
 * @param window The window of a client
 * @param layer The layer to set the client to
 */
void LayerManager::set_layer(Window window, Layer layer)
{
    if (!m_clients->is_client(window))
        return;

    m_layers[window] = layer;
    m_clients->relayer();
}

/**
 * Removes a client from the layer list.
 * @param window The client window to remove.
 */
void LayerManager::delete_layer(Window window)
{
    m_layers.erase(window);
}

/**
 * Relayers all clients which are currently CS_VISIBLE or CS_ACTIVE. Puts all
 * CS_ICON clients, or the placeholder windows for any CS_MOVING or CS_RESIZING
 * clients on the very top.
 */
void LayerManager::relayer_clients()
{
    // First, only layer the 'normal' windows which are not icons or placeholders.
    std::vector<Window> clients;
    for (LayerManager::iterator client_iter = m_layers.begin();
            client_iter != m_layers.end();
            client_iter++)
    {
        ClientState state = m_clients->get_state(client_iter->first);
        if (state == CS_VISIBLE || state == CS_ACTIVE)
            clients.push_back(client_iter->first);
    }

    MappedVectorSorter<Window,Layer> sorter(m_layers, true);
    std::sort(clients.begin(), clients.end(), sorter);
    XRestackWindows(m_shared.display, &clients[0], clients.size());
}
<commit_msg>Added layer correction for focused windows.<commit_after>/** @file */
#include "clientmanager.h"

/**
 * Gets the current 'offset', which is 0 when the window is unfocused and 5 when it is.
 */
int get_layer_offset(Layer layer)
{
    return layer % 10;
}

/**
 * Raises a client to the layer above it.
 * @param window The client to raise
 */
void LayerManager::raise_layer(Window window)
{
    if (!m_clients->is_client(window))
        return;

    Layer current = m_layers[window];
    if (current < MAX_LAYER)
    {
        m_layers[window] += 10;
        m_clients->relayer();
    }
}

/**
 * Lowers a client to the layer below it.
 * @param window The client to lower
 */
void LayerManager::lower_layer(Window window)
{
    if (!m_clients->is_client(window))
        return;

    Layer current = m_layers[window];
    if (current > MIN_LAYER)
    {
        m_layers[window] -= 10;
        m_clients->relayer();
    }
}

/**
 * Shifts the layer of a window up/down by a certain value.
 * @param window The window of a client
 * @param offset The z-layer to shift by.
 */
void LayerManager::adjust_layer(Window window, LayerDiff layer)
{
    Layer new_layer = m_layers[window] + layer;
    if (new_layer >= MIN_LAYER && new_layer <= MAX_LAYER)
    {
        m_layers[window] = new_layer;
        m_clients->relayer();
    }
}

/**
 * Sets the layer of a client.
 * @param window The window of a client
 * @param layer The layer to set the client to
 */
void LayerManager::set_layer(Window window, Layer layer)
{
    if (!m_clients->is_client(window))
        return;

    // If the window is focused, then be sure to keep the focus offset when
    // changing to a new layer
    Layer old_layer = m_layers[window];
    Layer offset = get_layer_offset(old_layer);

    m_layers[window] = layer + offset;
    m_clients->relayer();
}

/**
 * Removes a client from the layer list.
 * @param window The client window to remove.
 */
void LayerManager::delete_layer(Window window)
{
    m_layers.erase(window);
}

/**
 * Relayers all clients which are currently CS_VISIBLE or CS_ACTIVE. Puts all
 * CS_ICON clients, or the placeholder windows for any CS_MOVING or CS_RESIZING
 * clients on the very top.
 */
void LayerManager::relayer_clients()
{
    // First, only layer the 'normal' windows which are not icons or placeholders.
    std::vector<Window> clients;
    for (LayerManager::iterator client_iter = m_layers.begin();
            client_iter != m_layers.end();
            client_iter++)
    {
        ClientState state = m_clients->get_state(client_iter->first);
        if (state == CS_VISIBLE || state == CS_ACTIVE)
            clients.push_back(client_iter->first);
    }

    MappedVectorSorter<Window,Layer> sorter(m_layers, true);
    std::sort(clients.begin(), clients.end(), sorter);
    XRestackWindows(m_shared.display, &clients[0], clients.size());
}
<|endoftext|>