<commit_before>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/7/2 21:50:01
 * 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/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
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>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- 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 -----

class Solve
{

public:
  Solve()
  {
  }

  void flush()
  {
  }

private:
};

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

/*
int main()
{
  Solve solve;
  solve.flush();
}
*/

int main()
{
  int n, m, x;
  cin >> n >> m >> x;
  vector<int> c(n);
  vector<vector<int>> a(n, vector<int>(m));
  for (auto i{0}; i < n; ++i)
  {
    cin >> c[i];
    for (auto j{0}; j < m; ++j)
    {
      cin >> a[i][j];
    }
  }
  int ans{Infty<int>()};
  for (auto i{0}; i < (1 << n); ++i)
  {
    int cost{0};
    vector<int> b(m, 0);
    for (auto j{0}; j < n; ++j)
    {
      if (i >> n & 1)
      {
        cost += c[i];
      }
      for (auto k{0}; k < m; ++k)
      {
        b[k] += a[j][k];
      }
    }
    if (all_of(b.begin(), b.end(), [&](auto t) { return t >= x; }))
    {
      ch_min(ans, cost);
    }
  }
  if (ans == Infty<int>())
  {
    ans = -1;
  }
  cout << ans << endl;
}
<commit_msg>tried C.cpp to 'C'<commit_after>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/7/2 21:50:01
 * 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/integer/common_factor_rt.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::integer::gcd; // for C++14 or for cpp_int
using boost::integer::lcm; // for C++14 or for cpp_int
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>;
// ----- for C++17 -----
template <typename T, typename enable_if<is_integral<T>::value>::type * = nullptr>
size_t popcount(T x) { return bitset<64>(x).count(); }
size_t popcount(string const &S) { return bitset<200010>{S}.count(); }
// ----- 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 -----

class Solve
{

public:
  Solve()
  {
  }

  void flush()
  {
  }

private:
};

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

/*
int main()
{
  Solve solve;
  solve.flush();
}
*/

int main()
{
  int n, m, x;
  cin >> n >> m >> x;
  vector<int> c(n);
  vector<vector<int>> a(n, vector<int>(m));
  for (auto i{0}; i < n; ++i)
  {
    cin >> c[i];
    for (auto j{0}; j < m; ++j)
    {
      cin >> a[i][j];
    }
  }
  int ans{Infty<int>()};
  for (auto i{0}; i < (1 << n); ++i)
  {
    int cost{0};
    vector<int> b(m, 0);
    for (auto j{0}; j < n; ++j)
    {
      if (i >> n & 1)
      {
        cost += c[i];
      }
      for (auto k{0}; k < m; ++k)
      {
        b[k] += a[j][k];
      }
    }
    if (all_of(b.begin(), b.end(), [&](auto t) { return t >= x; }))
    {
#if DEBUG == 1
      cerr << "i = " << i << endl;
      cerr << "cost = " << cost << endl;
#endif
      ch_min(ans, cost);
    }
  }
  if (ans == Infty<int>())
  {
    ans = -1;
  }
  cout << ans << endl;
}
<|endoftext|>


<commit_before>// Copyright 2014 Google Inc.  All Rights Reserved
// Author: Wojtek Żółtak (wojciech.zoltak@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "supersonic/contrib/storage/core/page_sink.h"

#include <vector>

#include "supersonic/base/infrastructure/types.h"
#include "supersonic/base/exception/exception.h"
#include "supersonic/base/exception/exception_macros.h"
#include "supersonic/base/exception/result.h"
#include "supersonic/contrib/storage/base/serializer.h"
#include "supersonic/contrib/storage/base/column_writer.h"
#include "supersonic/contrib/storage/core/data_type_serializer.h"
#include "supersonic/contrib/storage/base/storage_metadata.h"
#include "supersonic/contrib/storage/core/page_builder.h"
#include "supersonic/utils/exception/failureor.h"

#include "supersonic/proto/supersonic.pb.h"

namespace supersonic {
namespace {

const uint64_t kPageSizeLimit = 100 * 1024;  // 100KB

class PageSinkImplementation : public PageSink {
 public:
  explicit PageSinkImplementation(
      std::unique_ptr<const BoundSingleSourceProjector> projector,
      std::shared_ptr<PageStreamWriter> page_stream_writer,
      std::unique_ptr<
          std::vector<std::unique_ptr<ColumnWriter>>> column_writers,
      std::shared_ptr<PageBuilder> page_builder,
      std::shared_ptr<MetadataWriter> metadata_writer,
      uint32_t page_family)
      : finalized_(false),
        builder_dirty_(false),
        projector_(std::move(projector)),
        page_stream_writer_(page_stream_writer),
        column_writers_(std::move(column_writers)),
        page_builder_(page_builder),
        metadata_writer_(metadata_writer),
        page_family_(page_family),
        rows_in_page_(0) {}

  virtual ~PageSinkImplementation() {
    if (!finalized_) {
      LOG(DFATAL)<< "Destroying not finalized PageSink.";
      Finalize();
    }
  }

  FailureOr<rowcount_t> Write(const View& data) {
    if (finalized_) {
      THROW(new Exception(ERROR_INVALID_STATE,
              "Writing to finalized page sink."));
    }

    View projected_data(projector_->result_schema());
    projected_data.set_row_count(data.row_count());
    projector_->Project(data, &projected_data);

    // TODO(wzoltak): Check if schema matches in debug mode?
    for (int column_index = 0; column_index < projected_data.column_count();
        column_index++) {
      FailureOrVoid write_result = (*column_writers_)[column_index]
          ->WriteColumn(projected_data.column(column_index),
                        projected_data.row_count());
      PROPAGATE_ON_FAILURE(write_result);
    }
    builder_dirty_ = builder_dirty_ || projected_data.row_count() > 0;
    rows_in_page_ += data.row_count();

    if (page_builder_->PageSize() > kPageSizeLimit) {
      FailureOrVoid written_page = WritePage();
      PROPAGATE_ON_FAILURE(written_page);
    }
    return Success(projected_data.row_count());
  }

  FailureOrVoid Finalize() {
    if (!finalized_) {
      if (builder_dirty_) {
        PROPAGATE_ON_FAILURE(WritePage());
      }
      finalized_ = true;
    }
    return Success();
  }

  size_t BytesInPage() {
    return page_builder_->PageSize();
  }

 private:
  FailureOrVoid WritePage() {
    FailureOrOwned<Page> page_result = page_builder_->CreatePage();
    PROPAGATE_ON_FAILURE(page_result);
    std::unique_ptr<Page> page(page_result.release());

    auto page_number = page_stream_writer_->AppendPage(page_family_, *page);
    PROPAGATE_ON_FAILURE(page_number);

    PageMetadata page_metadata;
    page_metadata.set_page_number(page_number.get());
    page_metadata.set_row_count(rows_in_page_);

    PROPAGATE_ON_FAILURE(
        metadata_writer_->AppendPage(page_family_, page_metadata));

    page_builder_->Reset();
    builder_dirty_ = false;
    rows_in_page_ = 0;

    return Success();
  }

  bool finalized_;
  bool builder_dirty_;
  std::unique_ptr<const BoundSingleSourceProjector> projector_;
  std::shared_ptr<PageStreamWriter> page_stream_writer_;
  std::unique_ptr<std::vector<std::unique_ptr<ColumnWriter> > > column_writers_;
  std::shared_ptr<PageBuilder> page_builder_;
  std::shared_ptr<MetadataWriter> metadata_writer_;
  uint32_t page_family_;
  uint64 rows_in_page_;
  DISALLOW_COPY_AND_ASSIGN(PageSinkImplementation);
};

}  // namespace

FailureOrOwned<PageSink> CreatePageSink(
    std::unique_ptr<const BoundSingleSourceProjector> projector,
    std::shared_ptr<PageStreamWriter> page_stream_writer,
    std::shared_ptr<MetadataWriter> metadata_writer,
    uint32_t page_family,
    BufferAllocator* buffer_allocator) {
  std::unique_ptr<std::vector<std::unique_ptr<ColumnWriter> > > serializers(
      new std::vector<std::unique_ptr<ColumnWriter> >());
  std::shared_ptr<PageBuilder> page_builder(
      new PageBuilder(0, buffer_allocator));

  const TupleSchema& schema = projector->result_schema();
  int streams_count = 0;
  for (int i = 0; i < schema.attribute_count(); i++) {
    const Attribute& attribute = schema.attribute(i);
    FailureOrOwned<ColumnWriter> column_writer_result = CreateColumnWriter(
        attribute, page_builder, streams_count);
    PROPAGATE_ON_FAILURE(column_writer_result);
    streams_count += column_writer_result->uses_streams();
    serializers->emplace_back(column_writer_result.release());
  }

  page_builder->Reset(streams_count);

  std::unique_ptr<PageSinkImplementation> sink(
      new PageSinkImplementation(std::move(projector),
                                 page_stream_writer,
                                 std::move(serializers),
                                 page_builder,
                                 metadata_writer,
                                 page_family));
  return Success(sink.release());
}

// Factory function for testing purposes.
FailureOrOwned<PageSink> CreatePageSink(
    std::unique_ptr<const BoundSingleSourceProjector> projector,
    std::shared_ptr<PageStreamWriter> page_stream_writer,
    std::unique_ptr<
        std::vector<std::unique_ptr<ColumnWriter> > > column_writers,
    std::shared_ptr<PageBuilder> page_builder,
    std::shared_ptr<MetadataWriter> metadata_writer,
    uint32_t page_family) {
  std::unique_ptr<PageSinkImplementation> page_sink(
      new PageSinkImplementation(std::move(projector),
                                 page_stream_writer,
                                 std::move(column_writers),
                                 page_builder,
                                 metadata_writer,
                                 page_family));
  return Success(page_sink.release());
}

}  // namespace supersonic
<commit_msg>512 page size limit.<commit_after>// Copyright 2014 Google Inc.  All Rights Reserved
// Author: Wojtek Żółtak (wojciech.zoltak@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "supersonic/contrib/storage/core/page_sink.h"

#include <vector>

#include "supersonic/base/infrastructure/types.h"
#include "supersonic/base/exception/exception.h"
#include "supersonic/base/exception/exception_macros.h"
#include "supersonic/base/exception/result.h"
#include "supersonic/contrib/storage/base/serializer.h"
#include "supersonic/contrib/storage/base/column_writer.h"
#include "supersonic/contrib/storage/core/data_type_serializer.h"
#include "supersonic/contrib/storage/base/storage_metadata.h"
#include "supersonic/contrib/storage/core/page_builder.h"
#include "supersonic/utils/exception/failureor.h"

#include "supersonic/proto/supersonic.pb.h"

namespace supersonic {
namespace {

const uint64_t kPageSizeLimit = 512 * 1024;  // 512KB

class PageSinkImplementation : public PageSink {
 public:
  explicit PageSinkImplementation(
      std::unique_ptr<const BoundSingleSourceProjector> projector,
      std::shared_ptr<PageStreamWriter> page_stream_writer,
      std::unique_ptr<
          std::vector<std::unique_ptr<ColumnWriter>>> column_writers,
      std::shared_ptr<PageBuilder> page_builder,
      std::shared_ptr<MetadataWriter> metadata_writer,
      uint32_t page_family)
      : finalized_(false),
        builder_dirty_(false),
        projector_(std::move(projector)),
        page_stream_writer_(page_stream_writer),
        column_writers_(std::move(column_writers)),
        page_builder_(page_builder),
        metadata_writer_(metadata_writer),
        page_family_(page_family),
        rows_in_page_(0) {}

  virtual ~PageSinkImplementation() {
    if (!finalized_) {
      LOG(DFATAL)<< "Destroying not finalized PageSink.";
      Finalize();
    }
  }

  FailureOr<rowcount_t> Write(const View& data) {
    if (finalized_) {
      THROW(new Exception(ERROR_INVALID_STATE,
              "Writing to finalized page sink."));
    }

    View projected_data(projector_->result_schema());
    projected_data.set_row_count(data.row_count());
    projector_->Project(data, &projected_data);

    // TODO(wzoltak): Check if schema matches in debug mode?
    for (int column_index = 0; column_index < projected_data.column_count();
        column_index++) {
      FailureOrVoid write_result = (*column_writers_)[column_index]
          ->WriteColumn(projected_data.column(column_index),
                        projected_data.row_count());
      PROPAGATE_ON_FAILURE(write_result);
    }
    builder_dirty_ = builder_dirty_ || projected_data.row_count() > 0;
    rows_in_page_ += data.row_count();

    if (page_builder_->PageSize() > kPageSizeLimit) {
      FailureOrVoid written_page = WritePage();
      PROPAGATE_ON_FAILURE(written_page);
    }
    return Success(projected_data.row_count());
  }

  FailureOrVoid Finalize() {
    if (!finalized_) {
      if (builder_dirty_) {
        PROPAGATE_ON_FAILURE(WritePage());
      }
      finalized_ = true;
    }
    return Success();
  }

  size_t BytesInPage() {
    return page_builder_->PageSize();
  }

 private:
  FailureOrVoid WritePage() {
    FailureOrOwned<Page> page_result = page_builder_->CreatePage();
    PROPAGATE_ON_FAILURE(page_result);
    std::unique_ptr<Page> page(page_result.release());

    auto page_number = page_stream_writer_->AppendPage(page_family_, *page);
    PROPAGATE_ON_FAILURE(page_number);

    PageMetadata page_metadata;
    page_metadata.set_page_number(page_number.get());
    page_metadata.set_row_count(rows_in_page_);

    PROPAGATE_ON_FAILURE(
        metadata_writer_->AppendPage(page_family_, page_metadata));

    page_builder_->Reset();
    builder_dirty_ = false;
    rows_in_page_ = 0;

    return Success();
  }

  bool finalized_;
  bool builder_dirty_;
  std::unique_ptr<const BoundSingleSourceProjector> projector_;
  std::shared_ptr<PageStreamWriter> page_stream_writer_;
  std::unique_ptr<std::vector<std::unique_ptr<ColumnWriter> > > column_writers_;
  std::shared_ptr<PageBuilder> page_builder_;
  std::shared_ptr<MetadataWriter> metadata_writer_;
  uint32_t page_family_;
  uint64 rows_in_page_;
  DISALLOW_COPY_AND_ASSIGN(PageSinkImplementation);
};

}  // namespace

FailureOrOwned<PageSink> CreatePageSink(
    std::unique_ptr<const BoundSingleSourceProjector> projector,
    std::shared_ptr<PageStreamWriter> page_stream_writer,
    std::shared_ptr<MetadataWriter> metadata_writer,
    uint32_t page_family,
    BufferAllocator* buffer_allocator) {
  std::unique_ptr<std::vector<std::unique_ptr<ColumnWriter> > > serializers(
      new std::vector<std::unique_ptr<ColumnWriter> >());
  std::shared_ptr<PageBuilder> page_builder(
      new PageBuilder(0, buffer_allocator));

  const TupleSchema& schema = projector->result_schema();
  int streams_count = 0;
  for (int i = 0; i < schema.attribute_count(); i++) {
    const Attribute& attribute = schema.attribute(i);
    FailureOrOwned<ColumnWriter> column_writer_result = CreateColumnWriter(
        attribute, page_builder, streams_count);
    PROPAGATE_ON_FAILURE(column_writer_result);
    streams_count += column_writer_result->uses_streams();
    serializers->emplace_back(column_writer_result.release());
  }

  page_builder->Reset(streams_count);

  std::unique_ptr<PageSinkImplementation> sink(
      new PageSinkImplementation(std::move(projector),
                                 page_stream_writer,
                                 std::move(serializers),
                                 page_builder,
                                 metadata_writer,
                                 page_family));
  return Success(sink.release());
}

// Factory function for testing purposes.
FailureOrOwned<PageSink> CreatePageSink(
    std::unique_ptr<const BoundSingleSourceProjector> projector,
    std::shared_ptr<PageStreamWriter> page_stream_writer,
    std::unique_ptr<
        std::vector<std::unique_ptr<ColumnWriter> > > column_writers,
    std::shared_ptr<PageBuilder> page_builder,
    std::shared_ptr<MetadataWriter> metadata_writer,
    uint32_t page_family) {
  std::unique_ptr<PageSinkImplementation> page_sink(
      new PageSinkImplementation(std::move(projector),
                                 page_stream_writer,
                                 std::move(column_writers),
                                 page_builder,
                                 metadata_writer,
                                 page_family));
  return Success(page_sink.release());
}

}  // namespace supersonic
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef AST_PROGRAM_H
#define AST_PROGRAM_H

#include <vector>

#include <boost/variant/variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

#include <boost/spirit/home/support/attributes.hpp>

#include "ast/FunctionDeclaration.hpp"
#include "ast/GlobalVariableDeclaration.hpp"

namespace eddic {

typedef boost::variant<FunctionDeclaration, GlobalVariableDeclaration> FirstLevelBlock;
typedef std::vector<FirstLevelBlock> ProgramEquivalence;

//A source EDDI program
struct Program {
    std::vector<FirstLevelBlock> blocks;
};

} //end of eddic

//Adapt the struct for the AST
BOOST_FUSION_ADAPT_STRUCT(
    eddic::Program,
    (std::vector<eddic::FirstLevelBlock>, blocks)
)

//Enable the use as one-attribute
namespace boost { namespace spirit { namespace traits {
    /*
    template <>
    struct assign_to_attribute_from_value <eddic::Program, eddic::ProgramEquivalence, qi::domain> {
        static void call(const eddic::ProgramEquivalence& val, eddic::Program& attr){
            attr.blocks = val;
        }
    };
    */

    /*
    template<>
    struct transform_attribute<eddic::Program, std::vector<eddic::FirstLevelBlock>, qi::domain> {
        typedef std::vector<eddic::FirstLevelBlock>& type;

        static type pre(eddic::Program& program) { return program.blocks; }
        static void post(eddic::Program&, const type) {}
        static void fail(eddic::Program&) {}
    };*/
}}}

#endif
<commit_msg>Remove old stuff<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef AST_PROGRAM_H
#define AST_PROGRAM_H

#include <vector>

#include <boost/variant/variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>

#include <boost/spirit/home/support/attributes.hpp>

#include "ast/FunctionDeclaration.hpp"
#include "ast/GlobalVariableDeclaration.hpp"

namespace eddic {

typedef boost::variant<FunctionDeclaration, GlobalVariableDeclaration> FirstLevelBlock;
typedef std::vector<FirstLevelBlock> ProgramEquivalence;

//A source EDDI program
struct Program {
    std::vector<FirstLevelBlock> blocks;
};

} //end of eddic

//Adapt the struct for the AST
BOOST_FUSION_ADAPT_STRUCT(
    eddic::Program,
    (std::vector<eddic::FirstLevelBlock>, blocks)
)

#endif
<|endoftext|>


<commit_before>/*
 * File:   cubicspline.cpp
 * Author: ruehle
 *
 * Created on August 22, 2008, 4:44 PM
 */

#include <cubicspline.h>

void CubicSpline::Fit(ub::vector<double> x, ub::vector<double> y)
{
    ub::matrix<double> A;
    A.resize(_r.size*4, x.size());
}

<commit_msg>compiles now again<commit_after>/*
 * File:   cubicspline.cpp
 * Author: ruehle
 *
 * Created on August 22, 2008, 4:44 PM
 */

#include <cubicspline.h>

void CubicSpline::Fit(ub::vector<double> x, ub::vector<double> y)
{
//    ub::matrix<double> A;
//    A.resize(_r.size*4, x.size());
}

<|endoftext|>


<commit_before>#include <sys/time.h>
#include <glib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ostream>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <pthread.h>

using namespace std;

struct timeval startTV;
struct timeval nextReportTV;
struct timeval intervalTV;
long int count =0;
pthread_t thread1;
int port;
char* hostname = "192.168.1.2";
char *stringString = "local.garden.water.counter";

void error(char *msg)
{
    perror(msg);
    exit(0);
}

int send(int portno, struct hostent* server, char *msg)
{
    int sockfd, n;

    struct sockaddr_in serv_addr;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) {
        perror("ERROR connecting");
    } else {
       n = write(sockfd,msg,strlen(msg));
       if (n < 0)
           perror("ERROR writing to socket");
       close(sockfd);
    }
    return 0;
}

int timeval_subtract (struct timeval *result,struct timeval *x,struct timeval *y )
{
  // Perform the carry for the later subtraction by updating y.
  if (x->tv_usec < y->tv_usec) {
    int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
    y->tv_usec -= 1000000 * nsec;
    y->tv_sec += nsec;
  }
  if (x->tv_usec - y->tv_usec > 1000000) {
    int nsec = (x->tv_usec - y->tv_usec) / 1000000;
    y->tv_usec += 1000000 * nsec;
    y->tv_sec -= nsec;
  }

  // Compute the time remaining to wait.  tv_usec is certainly positive.
  result->tv_sec = x->tv_sec - y->tv_sec;
  result->tv_usec = x->tv_usec - y->tv_usec;

  // Return 1 if result is negative.
  return x->tv_sec < y->tv_sec;
}

void timeval_add(struct timeval *result,struct timeval *x,struct timeval *y )
{
  long int sec =0;
  long int usec_sum = x->tv_usec + y->tv_usec;

  while(usec_sum > 1000000 ) {
     usec_sum = usec_sum - 1000000;
     sec = sec + 1;
  }

  sec = y->tv_sec + x->tv_sec + sec;

  // Compute the time remaining to wait.  tv_usec is certainly positive.
  result->tv_sec = sec;
  result->tv_usec = usec_sum;;

}

void report(long int cnt, struct timeval *now, struct timeval *interval) {
   char buf[255];
   long ts = time(NULL);
   sprintf(buf,"%s  %d %u\n",stringString, cnt,ts);
   struct hostent *server = gethostbyname(hostname);
   send(port, server, buf);
}

void* reportThreadRun(void *ptr) {

    while(true) {
       struct timeval nowTV;
       gettimeofday(&nowTV,NULL);
       if(nextReportTV.tv_sec ==0) {
          // first time out
          timeval_add(&nextReportTV, &nowTV, &intervalTV);
          cerr << "first time" << endl;
       } else {
          // ok now we have something real.
          struct timeval deltaTV;
          int neg = timeval_subtract (&deltaTV,&nextReportTV,&nowTV );
          cerr << "other times,  neg:" << neg << " deltaTV " << deltaTV.tv_sec << " count: "<< count << endl;
          if(neg ) {
             // the future
             timeval_add(&nextReportTV, &nowTV, &intervalTV);
             // add the delta which is now negative to get next point
             if(deltaTV.tv_sec > -60 ) {
                timeval_add(&nextReportTV, &nextReportTV, &deltaTV);
             } else {
                // this means either we really lamed out on response time, or the time actually changed.
                // either way we don't want to add in that negative this
             }
             cerr << "-- report " << endl;
             report(count,&intervalTV,&nowTV);
          }
       }
       sleep(1);
       //cerr << " and loop" << endl;
    }

}
static gboolean onTransitionEvent( GIOChannel *channel,
               GIOCondition condition,
               gpointer user_data )
{
    GError *error = 0;
    gsize bytes_read = 0;
    int buf_sz = 255;
    char buf[buf_sz];

    g_io_channel_seek_position( channel, 0, G_SEEK_SET, 0 );
    GIOStatus rc = g_io_channel_read_chars( channel,
                                            buf, buf_sz - 1,
                                            &bytes_read,
                                            &error );
    count++;

    if(rc == G_IO_STATUS_NORMAL) {
        //cerr << "  data:" << buf << endl;
    } else {
        cerr << "something was wrong, rc = " << rc << endl;
    }
    // thank you, call again!
    return 1;
}

int main( int argc, char** argv )
{
    int  iret1;
    GMainLoop* loop = g_main_loop_new( 0, 0 );

    intervalTV.tv_sec=60;
    intervalTV.tv_usec =0;

    char *portString = "2003";
    char *intervalString = "60";
    int opt;

    while ((opt = getopt(argc, argv, "p:h:s:i:")) != -1) {
        switch (opt) {
        case 'p':
            portString = optarg;
            break;
        case 'h':
            hostname = optarg;
            break;
        case 's':
            stringString = optarg;
            break;
        case 'i':
            intervalString = optarg;
            break;
        default:
            fprintf(stderr, "Usage: %s \n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }
    port = atoi(portString);
    intervalTV.tv_sec = atoi(intervalString);

    cout << " will send data to " << hostname << ":" << port << " to key " << stringString << " at interval " << intervalTV.tv_sec << " seconds " << endl;

    gettimeofday(&startTV,NULL);
    nextReportTV.tv_sec =0;;
    int fd = open( "/sys/class/gpio/gpio30/value", O_RDONLY | O_NONBLOCK );
    if(fd < 0) {
       cerr << "unable to open the GPIO 'file'. Did you set that stuff up proerly ?.  Will now exit ";
       exit(-1);
    }
    GIOChannel* channel = g_io_channel_unix_new( fd );
    GIOCondition cond = GIOCondition( G_IO_PRI );
    guint id = g_io_add_watch( channel, cond, onTransitionEvent, 0 );

    cerr << "creating thread";
    iret1 = pthread_create( &thread1, NULL, reportThreadRun, NULL);
    cerr << "thread created";
    g_main_loop_run( loop );
    pthread_join( thread1, NULL);
}
<commit_msg>more changes for more stuff monitored<commit_after>#include <sys/time.h>
#include <glib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ostream>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>

using namespace std;

#define MAX_BUF 64     //This is plenty large

int port;
char* hostname = "192.168.1.2";
char *stringString = "local.garden.water.counter";

struct CountUp {
    string gpio;
    long int count;
    string reportingString;
    guint id;
};

void error(char *msg)
{
    perror(msg);
    exit(0);
}

int send(int portno, struct hostent* server, char *msg)
{
    int sockfd, n;

    struct sockaddr_in serv_addr;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
         (char *)&serv_addr.sin_addr.s_addr,
         server->h_length);
    serv_addr.sin_port = htons(portno);
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");
    n = write(sockfd,msg,strlen(msg));
    if (n < 0)
         error("ERROR writing to socket");
    return 0;
}
//Function definitions
int readADC(unsigned int pin)
{
    int fd;          //file pointer
    char buf[MAX_BUF];     //file buffer
    char val[4];     //holds up to 4 digits for ADC value

    //Create the file path by concatenating the ADC pin number to the end of the string
    //Stores the file path name string into "buf"
    snprintf(buf, sizeof(buf), "/sys/devices/ocp.2/helper.14/AIN%d", pin);     //Concatenate ADC file name

    fd = open(buf, O_RDONLY);     //open ADC as read only

    //Will trigger if the ADC is not enabled
    if (fd < 0) {
        perror("ADC - problem opening ADC");
    }//end if

    read(fd, &val, 4);     //read ADC ing val (up to 4 digits 0-1799)
    close(fd);     //close file and stop reading

    return atoi(val);     //returns an integer value (rather than ascii)
}//end read ADC()

static gboolean sendTimerCallback (gpointer user_data) {
    CountUp* countups = (CountUp*)user_data;
    int lenArr = sizeof(countups)/sizeof(countups[0]);
    for(int i=0; i < lenArr; i++) {
        long int cnt = countups[i].count;
        string reportString = countups[i].reportingString;

        char buf[255];
        long ts = time(NULL);
        sprintf(buf,"%s %d  %u\n",reportString.c_str(),cnt,ts);
        struct hostent *server = gethostbyname("192.168.1.2");
        send(2003, server, buf);
    }

    return 1;
}

static gboolean onTransitionEvent( GIOChannel *channel,
               GIOCondition condition,
               gpointer user_data )
{
    GError *error = 0;
    gsize bytes_read = 0;
    int buf_sz = 255;
    char buf[buf_sz];
    CountUp* pCountUpStruct = (CountUp*) user_data;

    g_io_channel_seek_position( channel, 0, G_SEEK_SET, 0 );
    GIOStatus rc = g_io_channel_read_chars( channel,
                                            buf, buf_sz - 1,
                                            &bytes_read,
                                            &error );
    if(rc == G_IO_STATUS_NORMAL) {
        cerr << "  data:" << buf << endl;
    } else {
        cerr << "something was wrong, rc = " << rc << endl;
    }
    pCountUpStruct->count++;

    // thank you, call again!
    return 1;
}

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

    char *portString = "2003";
    char *intervalString = "60";
    char *hostname = "192.168.1.2";
    char *intervalString = "120";

    int opt;
    while ((opt = getopt(argc, argv, "p:h:s:i:")) != -1) {
        switch (opt) {
            case 'p':
                portString = optarg;
                break;
            case 'h':
                hostname = optarg;
                break;
            case 's':
                stringString = optarg;
                break;
            case 'i':
                intervalString = optarg;
                break;
            default:
                fprintf(stderr, "Usage: %s \n", argv[0]);
                exit(EXIT_FAILURE);
        }
    }
    port = atoi(portString);
    interval = atoi(intervalString);

    CountUp countups[]={
            {  "gpio30", 0, "waterCount" },
            {  "James", 0, "waterCount"  },
            { "John", 0, "waterCount"  },
            { "Mike", 0, "waterCount"  }
    };

    GMainLoop* loop = g_main_loop_new( 0, 0 );

    int lenArr = sizeof(countups)/sizeof(countups[0]);
    for(int i=0; i < lenArr; i++) {
        string gpioDesc = "/sys/class/gpio/"+countups[i].gpio+"/value";
        int fd = open( gpioDesc.c_str(), O_RDONLY | O_NONBLOCK );
        GIOChannel* channel = g_io_channel_unix_new( fd );
        GIOCondition cond = GIOCondition( G_IO_PRI );
        guint id = g_io_add_watch( channel, cond, onTransitionEvent, &(countups[i]) );
    }

    guint sendIntervalSecs = 60 *2;
    g_timeout_add_seconds(sendIntervalSecs,sendTimerCallback,countups);
    g_main_loop_run( loop );
}
<|endoftext|>


<commit_before>#include "Search.hpp"
#include "MoveIterator.hpp"
#include <limits>

using namespace std;

ThreadPool<maskedArguments> myThreadPool(NUM_OF_THREADS,&negaScoutWrapper);

search_result allResults[64][16*2-2];

atomic<int32_t> galpha_pl;
atomic<int32_t> gbeta__pl;

template<player pl, bool mainThread>
int32_t negaScout(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst){
#ifndef NDEBUG
    ++totalNodes;
#endif

    //An ftasame sta katw katw fyla tote gyrname thn katastash
    if(depth == 0){
#ifndef NDEBUG
        ++horizonNodes;
#endif
        int32_t temp = veryVeryGreedyAndStupidEvaluationFunction(board);
        temp = (pl == NORMAL) ? temp : -temp;
        return temp;
    }

    uint64 hash = board.getHash();

    int32_t alph = alpha, bet = beta;
    //alpha beta are passed by reference!!!
    int kiMove = tt.retrieveTTEntry(hash, depth, alph, bet, pl == PLACER);
    if (alph >= bet) {
        return alph;
    }

    int bmove = -1;

    bool firstChild = true;

    MoveIterator_t<BitBoard_t, pl, mainThread> mIt(board);

    if (mainThread){
        // if (pl == NORMAL){
            galpha_pl = +alph;
            gbeta__pl = (int) pl;
        // } else {
        //     galpha_pl = +MIN_TT_SCORE ;
        //     gbeta__pl = -alph;
        // }
    }

    int iter = 0;
    while(true) {
        tlocal_search_result tmp_r = mIt.searchNextChild(board, kiMove,
            depth-1, alph, bet, firstChild, &(allResults[depth][iter].score));
        kiMove = -1;
        if (tmp_r.move == -1) break;                //and rt.score is invalid

        firstChild = false; //set this here
        if(mainThread){//Template if
            if(tmp_r.move < 0) {
                allResults[depth][iter].move  = -(2+tmp_r.move);
                ++iter;
                continue;
            }
        }
        //tmp_r.move is always non-negative if a valid move was played

        //Setting firstChild here permits skipping the rest of current iteration
        //if score must be ignored for now

        //possible set a continue here such that if a new thread is used for
        //subtree search, to skip score checking ?
        //if (tmp_r.move < -1) continue;

        //move played!

        if (tmp_r.score >= bet){
            tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
            return bet;                                 //fail-hard beta cut-off
        }
        if ((!mainThread) && ((int) pl) != gbeta__pl && tmp_r.score >= -galpha_pl){
        // if ((!mainThread) && tmp_r.score >= ((pl == NORMAL) ? (int32_t) gbeta__pl : -galpha_pl)){
            return -galpha_pl;//((pl == NORMAL) ? (int32_t) gbeta__pl : -galpha_pl);//MAX_TT_SCORE;
        }

        if (tmp_r.score > alph){                        //better move found
            if (mainThread){
                // if (pl == NORMAL){
                    galpha_pl = +tmp_r.score;
                // } else {
                //     gbeta__pl = -tmp_r.score;
                // }
            }
            alph  = tmp_r.score;
            bmove = tmp_r.move;
            assert(bmove >= 0);
        }
    }

    //Wait for threads to finish and merge scores here
    if(mainThread){
        bool unfinished = false;
        do {
            unfinished = false;
            for (int i = 0 ; i < iter ; ++i){
                if (allResults[depth][i].score == 0) {
                    unfinished = true;
                    continue;
                } else if (allResults[depth][i].move >= 0){
                    tlocal_search_result tmp_r;

                    tmp_r.score = allResults[depth][i].score;
                    tmp_r.move  = allResults[depth][i].move;
                    allResults[depth][i].move = -5;

                    if (tmp_r.score >= bet){
                        for (int j = 0 ; j < iter ; ++j){
                            while(allResults[depth][j].score == 0 && allResults[depth][j].move >= 0){
                                this_thread::yield();
                            }
                        }
                        tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
                        return bet;                             //fail-hard beta cut-off
                    }

                    if (tmp_r.score > alph){                    //better move found
                        // if (pl == NORMAL){
                            galpha_pl = +tmp_r.score;
                        // } else {
                        //     gbeta__pl = -tmp_r.score;
                        // }
                        alph  = tmp_r.score;
                        bmove = tmp_r.move;
                        assert(bmove >= 0);
                    }
                }
            }
        } while (unfinished);
    }

    if (firstChild){ //no move was available, this is a leaf node, return score
        board.assert_state();
        assert(pl == NORMAL);
#ifndef NDEBUG
        ++horizonNodes;
#endif
        bool a;
        return board.getHigherTile(&a) << 2;
    }

    NodeType nt = PV__Node;
    if (bmove < 0){                                     //All-Node
        nt    = All_Node;
        bmove = 0;
    }
    tt.addTTEntry(hash, depth, bmove, alph, pl == PLACER, nt);
    return alph;
}

template<player other, bool mainThread>
int32_t search_deeper(BitBoard_t &board, int32_t depth, int32_t alpha,
                                                int32_t beta, bool firstChild){
    int32_t score;
    if(firstChild == true){
        score = -negaScout<other, mainThread>(board, depth, -beta, -alpha, firstChild);
    } else {
        // score = -negaScout<other, mainThread>(board, depth, -alpha-1, -alpha, firstChild);
        // if(alpha < score){
            score = -negaScout<other, mainThread>(board, depth, -beta, -alpha, firstChild);
        // }
    }
    return score;
}

void negaScoutWrapper(maskedArguments args){
    int32_t data;
    if (args.pl == player::PLACER){
        data = search_deeper<player::PLACER,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
    } else {
        data = search_deeper<player::NORMAL,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
    }
    assert(data!=0);
    *(args.writeResult) = data;
}

template<player other>
void spawnThread(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild, atomic<int32_t> *score){
    maskedArguments args;
    args.pl = other;
    args.alpha = alpha;
    args.beta = beta;
    args.depth = depth;
    args.board = board;
    args.firstChild = firstChild;
    args.writeResult = score;

    myThreadPool.useNewThread(args);
}

int32_t veryVeryGreedyAndStupidEvaluationFunction(BitBoard_t boardForEv){
    bool inCorner = false;
    int32_t v2 = boardForEv.getHigherTile(&inCorner);
    int32_t score = (v2 << 6) + 1;
    if(inCorner){
        score += boardForEv.getMaxCornerChain() << 5;
        score <<= 2;
    }
    score += boardForEv.getMaxChain() << 4;
    int tmp = boardForEv.countFreeTiles() - 7;
    tmp = (tmp < 0) ? -tmp : tmp;
    score += (7-tmp) << 2;
    score += boardForEv.countTileTypes() << 2;
    assert(score >= 0);
    return score;
}

template int32_t negaScout<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t search_deeper<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
<commit_msg>Fixed busy wait of mainThread<commit_after>#include "Search.hpp"
#include "MoveIterator.hpp"
#include <limits>

using namespace std;

ThreadPool<maskedArguments> myThreadPool(NUM_OF_THREADS,&negaScoutWrapper);

search_result allResults[64][16*2-2];

atomic<int32_t> galpha_pl;
atomic<int32_t> gbeta__pl;

template<player pl, bool mainThread>
int32_t negaScout(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst){
#ifndef NDEBUG
    ++totalNodes;
#endif

    //An ftasame sta katw katw fyla tote gyrname thn katastash
    if(depth == 0){
#ifndef NDEBUG
        ++horizonNodes;
#endif
        int32_t temp = veryVeryGreedyAndStupidEvaluationFunction(board);
        temp = (pl == NORMAL) ? temp : -temp;
        return temp;
    }

    uint64 hash = board.getHash();

    int32_t alph = alpha, bet = beta;
    //alpha beta are passed by reference!!!
    int kiMove = tt.retrieveTTEntry(hash, depth, alph, bet, pl == PLACER);
    if (alph >= bet) {
        return alph;
    }

    int bmove = -1;

    bool firstChild = true;

    MoveIterator_t<BitBoard_t, pl, mainThread> mIt(board);

    if (mainThread){
        // if (pl == NORMAL){
            galpha_pl = +alph;
            gbeta__pl = (int) pl;
        // } else {
        //     galpha_pl = +MIN_TT_SCORE ;
        //     gbeta__pl = -alph;
        // }
    }

    int iter = 0;
    while(true) {
        tlocal_search_result tmp_r = mIt.searchNextChild(board, kiMove,
            depth-1, alph, bet, firstChild, &(allResults[depth][iter].score));
        kiMove = -1;
        if (tmp_r.move == -1) break;                //and rt.score is invalid

        firstChild = false; //set this here
        if(mainThread){//Template if
            if(tmp_r.move < 0) {
                allResults[depth][iter].move  = -(2+tmp_r.move);
                ++iter;
                continue;
            }
        }
        //tmp_r.move is always non-negative if a valid move was played

        //Setting firstChild here permits skipping the rest of current iteration
        //if score must be ignored for now

        //possible set a continue here such that if a new thread is used for
        //subtree search, to skip score checking ?
        //if (tmp_r.move < -1) continue;

        //move played!

        if (tmp_r.score >= bet){
            tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
            return bet;                                 //fail-hard beta cut-off
        }
        if ((!mainThread) && ((int) pl) != gbeta__pl && tmp_r.score >= -galpha_pl){
        // if ((!mainThread) && tmp_r.score >= ((pl == NORMAL) ? (int32_t) gbeta__pl : -galpha_pl)){
            return -galpha_pl;//((pl == NORMAL) ? (int32_t) gbeta__pl : -galpha_pl);//MAX_TT_SCORE;
        }

        if (tmp_r.score > alph){                        //better move found
            if (mainThread){
                // if (pl == NORMAL){
                    galpha_pl = +tmp_r.score;
                // } else {
                //     gbeta__pl = -tmp_r.score;
                // }
            }
            alph  = tmp_r.score;
            bmove = tmp_r.move;
            assert(bmove >= 0);
        }
    }

    //Wait for threads to finish and merge scores here
    if(mainThread){
        bool unfinished = false;
        do {
            unfinished = false;
            for (int i = 0 ; i < iter ; ++i){
                if (allResults[depth][i].score == 0) {
                    unfinished = true;
                } else if (allResults[depth][i].move >= 0){
                    tlocal_search_result tmp_r;

                    tmp_r.score = allResults[depth][i].score;
                    tmp_r.move  = allResults[depth][i].move;
                    allResults[depth][i].move = -5;

                    if (tmp_r.score >= bet){
                        for (int j = 0 ; j < iter ; ++j){
                            while(allResults[depth][j].score == 0 && allResults[depth][j].move >= 0){
                                this_thread::yield();
                            }
                        }
                        tt.addTTEntry(hash, depth, tmp_r.move, tmp_r.score, pl==PLACER, Cut_Node);
                        return bet;                             //fail-hard beta cut-off
                    }

                    if (tmp_r.score > alph){                    //better move found
                        // if (pl == NORMAL){
                            galpha_pl = +tmp_r.score;
                        // } else {
                        //     gbeta__pl = -tmp_r.score;
                        // }
                        alph  = tmp_r.score;
                        bmove = tmp_r.move;
                        assert(bmove >= 0);
                    }
                }
            }
            if (unfinished){
                this_thread::yield();
            }
        } while (unfinished);
    }

    if (firstChild){ //no move was available, this is a leaf node, return score
        board.assert_state();
        assert(pl == NORMAL);
#ifndef NDEBUG
        ++horizonNodes;
#endif
        bool a;
        return board.getHigherTile(&a) << 2;
    }

    NodeType nt = PV__Node;
    if (bmove < 0){                                     //All-Node
        nt    = All_Node;
        bmove = 0;
    }
    tt.addTTEntry(hash, depth, bmove, alph, pl == PLACER, nt);
    return alph;
}

template<player other, bool mainThread>
int32_t search_deeper(BitBoard_t &board, int32_t depth, int32_t alpha,
                                                int32_t beta, bool firstChild){
    int32_t score;
    if(firstChild == true){
        score = -negaScout<other, mainThread>(board, depth, -beta, -alpha, firstChild);
    } else {
        // score = -negaScout<other, mainThread>(board, depth, -alpha-1, -alpha, firstChild);
        // if(alpha < score){
            score = -negaScout<other, mainThread>(board, depth, -beta, -alpha, firstChild);
        // }
    }
    return score;
}

void negaScoutWrapper(maskedArguments args){
    int32_t data;
    if (args.pl == player::PLACER){
        data = search_deeper<player::PLACER,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
    } else {
        data = search_deeper<player::NORMAL,false>(args.board, args.depth, args.alpha, args.beta, args.firstChild);
    }
    assert(data!=0);
    *(args.writeResult) = data;
}

template<player other>
void spawnThread(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild, atomic<int32_t> *score){
    maskedArguments args;
    args.pl = other;
    args.alpha = alpha;
    args.beta = beta;
    args.depth = depth;
    args.board = board;
    args.firstChild = firstChild;
    args.writeResult = score;

    myThreadPool.useNewThread(args);
}

int32_t veryVeryGreedyAndStupidEvaluationFunction(BitBoard_t boardForEv){
    bool inCorner = false;
    int32_t v2 = boardForEv.getHigherTile(&inCorner);
    int32_t score = (v2 << 6) + 1;
    if(inCorner){
        score += boardForEv.getMaxCornerChain() << 5;
        score <<= 2;
    }
    score += boardForEv.getMaxChain() << 4;
    int tmp = boardForEv.countFreeTiles() - 7;
    tmp = (tmp < 0) ? -tmp : tmp;
    score += (7-tmp) << 2;
    score += boardForEv.countTileTypes() << 2;
    assert(score >= 0);
    return score;
}

template int32_t negaScout<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t negaScout<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool amIfirst);
template int32_t search_deeper<player::PLACER, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, true>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::PLACER, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
template int32_t search_deeper<player::NORMAL, false>(BitBoard_t &board, int32_t depth, int32_t alpha, int32_t beta, bool firstChild);
<|endoftext|>


<commit_before>#define _USE_MATH_DEFINES
#include <math.h>
#include "bandlimited_sawtooth_oscillator.h"
#include "bandlimited_sawtooth_oscillator_note.h"

//----------------
// コンストラクタ
//----------------
bandlimited_sawtooth_oscillator::bandlimited_sawtooth_oscillator()
{
	// サイン波テーブル作成
	int ii = 0;
	for(; ii< _sinTable.size()-1; ii++)
	{
		_sinTable[ii] = sin( 2.0*M_PI * ii/(_sinTable.size()-1));
	}

	_sinTable[ii] = 0.0;

	_srate = 44100;
}

//
void bandlimited_sawtooth_oscillator::setFeedback(double value)
{
	_feedback = value;
}

//-------------
//
//-------------
double bandlimited_sawtooth_oscillator::LinearInterpolatedSin( double x )
{
#ifdef _DEBUG
	if( x < 0.0 ) throw;
	if( 1.0 <= x ) throw;
#endif

	// スケーリング
	double pos = (_sinTable.size()-1) * x;

#ifdef _DEBUG
	if( pos >= _sinTable.size()-1 ) throw;
#endif

	// 位置を計算
	unsigned int idx_A = static_cast<int>(pos);

	// 距離を算出
	double s = pos - idx_A;

	// 線形補間
	return (1.0-s) * _sinTable[idx_A] + s*_sinTable[idx_A+1];
}

//-------------
// BLIT
//-------------
double bandlimited_sawtooth_oscillator::BLIT( double t, int N )
{
	if( t < 1.0e-12 )// TODO: 要チューニング
	{
		// ゼロ割防止。ロピタルの定理を適用
		return (2.0 * N) * 2.0;
	}

	// 分子
	double x_numerator = LinearInterpolatedSin(::fmod((2.0*N+1.0)/2.0*t, 1.0));

	// 分母
	double x_denominator = LinearInterpolatedSin( t/2.0 );

	return (x_numerator/x_denominator-1.0) * 2.0;
}

//-------------
//
//-------------
void bandlimited_sawtooth_oscillator::updateOscillater(bandlimited_sawtooth_oscillator_note& note)
{
	note.t += note.dt;
	if ( 1.0 <= note.t )note.t -= 1.0;

	note.saw = note.saw*_feedback + BLIT(note.t, note.n)*note.dt;
}

//
void bandlimited_sawtooth_oscillator::updateEnvelope(bandlimited_sawtooth_oscillator_note &note)
{
	if( note.adsr == bandlimited_sawtooth_oscillator_note::Attack )
	{
		// Attack
		if( note.envelope + _attack_decrement < 1.0 )
		{
			note.envelope += _attack_decrement;
		}
		else
		{
			// Attack→定数
			note.envelope = 1.0;
			note.adsr = bandlimited_sawtooth_oscillator_note::Const;
		}
	}
	else if( note.adsr == bandlimited_sawtooth_oscillator_note::Release )
	{
		// Release
		if( 0.0 < note.envelope - _release_decrement )
		{
			note.envelope -= _release_decrement;
		}
		else
		{
			// リリース終了
			note.envelope = 0.0;
			note.adsr = bandlimited_sawtooth_oscillator_note::Silent;

			// 破棄
			note.kill();
		}
	}
}

//
void bandlimited_sawtooth_oscillator::setAttackTime(double attackTime)
{
	if( attackTime > 1.0e-12)
	{
		_attack_decrement = 1.0 / (attackTime * _srate);
	}
	else
	{
		_attack_decrement = 1.0;
	}
}

//
void bandlimited_sawtooth_oscillator::setReleaseTime(double releaseTime)
{
	if( releaseTime > 1.0e-12)
	{
		_release_decrement = 1.0 / (releaseTime * _srate);
	}
	else
	{
		_release_decrement = 1.0;
	}
}

//
void bandlimited_sawtooth_oscillator::setSampleRate(int srate)
{
	_srate = srate;
}<commit_msg>ゼロ割判定を修正。戻り値に-2するのを止めた。<commit_after>#define _USE_MATH_DEFINES
#include <math.h>
#include "bandlimited_sawtooth_oscillator.h"
#include "bandlimited_sawtooth_oscillator_note.h"

//----------------
// コンストラクタ
//----------------
bandlimited_sawtooth_oscillator::bandlimited_sawtooth_oscillator()
{
	// サイン波テーブル作成
	int ii = 0;
	for(; ii< _sinTable.size()-1; ii++)
	{
		_sinTable[ii] = sin( 2.0*M_PI * ii/(_sinTable.size()-1));
	}

	_sinTable[ii] = 0.0;

	_srate = 44100;
}

//
void bandlimited_sawtooth_oscillator::setFeedback(double value)
{
	_feedback = value;
}

//-------------
//
//-------------
double bandlimited_sawtooth_oscillator::LinearInterpolatedSin( double x )
{
#ifdef _DEBUG
	if( x < 0.0 ) throw;
	if( 1.0 <= x ) throw;
#endif

	// スケーリング
	double pos = (_sinTable.size()-1) * x;

#ifdef _DEBUG
	if( pos >= _sinTable.size()-1 ) throw;
#endif

	// 位置を計算
	unsigned int idx_A = static_cast<int>(pos);

	// 距離を算出
	double s = pos - idx_A;

	// 線形補間
	return (1.0-s) * _sinTable[idx_A] + s*_sinTable[idx_A+1];
}

//-------------
// BLIT
//-------------
double bandlimited_sawtooth_oscillator::BLIT( double t, int N )
{
	// 分母
	double x_denominator = LinearInterpolatedSin( 0.5*t );

	if( x_denominator < 1.0e-12 )// TODO: 要チューニング
	{
		// ゼロ割防止。ロピタルの定理を適用
		return 2.0*(2*N+1);
	}

	// 分子
	double x_numerator = LinearInterpolatedSin(::fmod((N+0.5)*t, 1.0));

	return 2.0*x_numerator/x_denominator;
}

//-------------
//
//-------------
void bandlimited_sawtooth_oscillator::updateOscillater(bandlimited_sawtooth_oscillator_note& note)
{
	note.t += note.dt;
	if ( 1.0 <= note.t )note.t -= 1.0;

	note.saw = note.saw*_feedback + (BLIT(note.t, note.n)-2.0)*note.dt;
}

//
void bandlimited_sawtooth_oscillator::updateEnvelope(bandlimited_sawtooth_oscillator_note &note)
{
	if( note.adsr == bandlimited_sawtooth_oscillator_note::Attack )
	{
		// Attack
		if( note.envelope + _attack_decrement < 1.0 )
		{
			note.envelope += _attack_decrement;
		}
		else
		{
			// Attack→定数
			note.envelope = 1.0;
			note.adsr = bandlimited_sawtooth_oscillator_note::Const;
		}
	}
	else if( note.adsr == bandlimited_sawtooth_oscillator_note::Release )
	{
		// Release
		if( 0.0 < note.envelope - _release_decrement )
		{
			note.envelope -= _release_decrement;
		}
		else
		{
			// リリース終了
			note.envelope = 0.0;
			note.adsr = bandlimited_sawtooth_oscillator_note::Silent;

			// 破棄
			note.kill();
		}
	}
}

//
void bandlimited_sawtooth_oscillator::setAttackTime(double attackTime)
{
	if( attackTime > 1.0e-12)
	{
		_attack_decrement = 1.0 / (attackTime * _srate);
	}
	else
	{
		_attack_decrement = 1.0;
	}
}

//
void bandlimited_sawtooth_oscillator::setReleaseTime(double releaseTime)
{
	if( releaseTime > 1.0e-12)
	{
		_release_decrement = 1.0 / (releaseTime * _srate);
	}
	else
	{
		_release_decrement = 1.0;
	}
}

//
void bandlimited_sawtooth_oscillator::setSampleRate(int srate)
{
	_srate = srate;
}<|endoftext|>


<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/kernels/reduction_ops_common.h"

namespace tensorflow {

#define REGISTER_CPU_KERNELS(type)                                             \
  REGISTER_KERNEL_BUILDER(                                                     \
      Name("Sum")                                                              \
          .Device(DEVICE_CPU)                                                  \
          .TypeConstraint<type>("T")                                           \
          .TypeConstraint<int32>("Tidx"),                                      \
      ReductionOp<CPUDevice, type, int32, Eigen::internal::SumReducer<type>>); \
  REGISTER_KERNEL_BUILDER(                                                     \
      Name("Sum")                                                              \
          .Device(DEVICE_CPU)                                                  \
          .TypeConstraint<type>("T")                                           \
          .TypeConstraint<int64>("Tidx"),                                      \
      ReductionOp<CPUDevice, type, int64, Eigen::internal::SumReducer<type>>);
TF_CALL_NUMBER_TYPES(REGISTER_CPU_KERNELS);
#undef REGISTER_CPU_KERNELS

#if GOOGLE_CUDA

#define REGISTER_GPU_KERNELS(type)                                             \
  REGISTER_KERNEL_BUILDER(                                                     \
      Name("Sum")                                                              \
          .Device(DEVICE_GPU)                                                  \
          .TypeConstraint<type>("T")                                           \
          .TypeConstraint<int32>("Tidx")                                       \
          .HostMemory("reduction_indices"),                                    \
      ReductionOp<GPUDevice, type, int32, Eigen::internal::SumReducer<type>>); \
  REGISTER_KERNEL_BUILDER(                                                     \
      Name("Sum")                                                              \
          .Device(DEVICE_GPU)                                                  \
          .TypeConstraint<type>("T")                                           \
          .TypeConstraint<int64>("Tidx")                                       \
          .HostMemory("reduction_indices"),                                    \
      ReductionOp<GPUDevice, type, int64, Eigen::internal::SumReducer<type>>);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS);
TF_CALL_complex64(REGISTER_GPU_KERNELS);
TF_CALL_complex128(REGISTER_GPU_KERNELS);
#undef REGISTER_GPU_KERNELS

// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(
    Name("Sum")
        .Device(DEVICE_GPU)
        .TypeConstraint<int32>("T")
        .TypeConstraint<int32>("Tidx")
        .HostMemory("input")
        .HostMemory("output")
        .HostMemory("reduction_indices"),
    ReductionOp<CPUDevice, int32, int32, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
    Name("Sum")
        .Device(DEVICE_GPU)
        .TypeConstraint<int32>("T")
        .TypeConstraint<int64>("Tidx")
        .HostMemory("input")
        .HostMemory("output")
        .HostMemory("reduction_indices"),
    ReductionOp<CPUDevice, int32, int64, Eigen::internal::SumReducer<int32>>);

#endif

#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNELS(type)                                        \
  REGISTER_KERNEL_BUILDER(Name("Sum")                                      \
                              .Device(DEVICE_SYCL)                         \
                              .TypeConstraint<type>("T")                   \
                              .TypeConstraint<int32>("Tidx")               \
                              .HostMemory("reduction_indices"),            \
                          ReductionOp<SYCLDevice, type, int32,             \
                                      Eigen::internal::SumReducer<type>>); \
  REGISTER_KERNEL_BUILDER(Name("Sum")                                      \
                              .Device(DEVICE_SYCL)                         \
                              .TypeConstraint<type>("T")                   \
                              .TypeConstraint<int64>("Tidx")               \
                              .HostMemory("reduction_indices"),            \
                          ReductionOp<SYCLDevice, type, int64,             \
                                      Eigen::internal::SumReducer<type>>);
REGISTER_SYCL_KERNELS(float);
REGISTER_SYCL_KERNELS(double);

REGISTER_KERNEL_BUILDER(
    Name("Sum")
        .Device(DEVICE_SYCL)
        .TypeConstraint<int32>("T")
        .TypeConstraint<int32>("Tidx")
        .HostMemory("input")
        .HostMemory("output")
        .HostMemory("reduction_indices"),
    ReductionOp<CPUDevice, int32, int32, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
    Name("Sum")
        .Device(DEVICE_SYCL)
        .TypeConstraint<int32>("T")
        .TypeConstraint<int64>("Tidx")
        .HostMemory("input")
        .HostMemory("output")
        .HostMemory("reduction_indices"),
    ReductionOp<CPUDevice, int32, int64, Eigen::internal::SumReducer<int32>>);
#undef REGISTER_SYCL_KERNELS
#endif  // TENSORFLOW_USE_SYCL

}  // namespace tensorflow
<commit_msg>Register a new Sum op for T:int64 and Tidx:int32<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/kernels/reduction_ops_common.h"

namespace tensorflow {

#define REGISTER_CPU_KERNELS(type)                                             \
  REGISTER_KERNEL_BUILDER(                                                     \
      Name("Sum")                                                              \
          .Device(DEVICE_CPU)                                                  \
          .TypeConstraint<type>("T")                                           \
          .TypeConstraint<int32>("Tidx"),                                      \
      ReductionOp<CPUDevice, type, int32, Eigen::internal::SumReducer<type>>); \
  REGISTER_KERNEL_BUILDER(                                                     \
      Name("Sum")                                                              \
          .Device(DEVICE_CPU)                                                  \
          .TypeConstraint<type>("T")                                           \
          .TypeConstraint<int64>("Tidx"),                                      \
      ReductionOp<CPUDevice, type, int64, Eigen::internal::SumReducer<type>>);
TF_CALL_NUMBER_TYPES(REGISTER_CPU_KERNELS);
#undef REGISTER_CPU_KERNELS

#if GOOGLE_CUDA

#define REGISTER_GPU_KERNELS(type)                                             \
  REGISTER_KERNEL_BUILDER(                                                     \
      Name("Sum")                                                              \
          .Device(DEVICE_GPU)                                                  \
          .TypeConstraint<type>("T")                                           \
          .TypeConstraint<int32>("Tidx")                                       \
          .HostMemory("reduction_indices"),                                    \
      ReductionOp<GPUDevice, type, int32, Eigen::internal::SumReducer<type>>); \
  REGISTER_KERNEL_BUILDER(                                                     \
      Name("Sum")                                                              \
          .Device(DEVICE_GPU)                                                  \
          .TypeConstraint<type>("T")                                           \
          .TypeConstraint<int64>("Tidx")                                       \
          .HostMemory("reduction_indices"),                                    \
      ReductionOp<GPUDevice, type, int64, Eigen::internal::SumReducer<type>>);
TF_CALL_GPU_NUMBER_TYPES(REGISTER_GPU_KERNELS);
TF_CALL_complex64(REGISTER_GPU_KERNELS);
TF_CALL_complex128(REGISTER_GPU_KERNELS);
#undef REGISTER_GPU_KERNELS

// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(
    Name("Sum")
        .Device(DEVICE_GPU)
        .TypeConstraint<int32>("T")
        .TypeConstraint<int32>("Tidx")
        .HostMemory("input")
        .HostMemory("output")
        .HostMemory("reduction_indices"),
    ReductionOp<CPUDevice, int32, int32, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
    Name("Sum")
        .Device(DEVICE_GPU)
        .TypeConstraint<int32>("T")
        .TypeConstraint<int64>("Tidx")
        .HostMemory("input")
        .HostMemory("output")
        .HostMemory("reduction_indices"),
    ReductionOp<CPUDevice, int32, int64, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
    Name("Sum")
        .Device(DEVICE_GPU)
        .TypeConstraint<int64>("T")
        .TypeConstraint<int32>("Tidx")
        .HostMemory("input")
        .HostMemory("output")
        .HostMemory("reduction_indices"),
    ReductionOp<CPUDevice, int64, int32, Eigen::internal::SumReducer<int64>>);
#endif

#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNELS(type)                                        \
  REGISTER_KERNEL_BUILDER(Name("Sum")                                      \
                              .Device(DEVICE_SYCL)                         \
                              .TypeConstraint<type>("T")                   \
                              .TypeConstraint<int32>("Tidx")               \
                              .HostMemory("reduction_indices"),            \
                          ReductionOp<SYCLDevice, type, int32,             \
                                      Eigen::internal::SumReducer<type>>); \
  REGISTER_KERNEL_BUILDER(Name("Sum")                                      \
                              .Device(DEVICE_SYCL)                         \
                              .TypeConstraint<type>("T")                   \
                              .TypeConstraint<int64>("Tidx")               \
                              .HostMemory("reduction_indices"),            \
                          ReductionOp<SYCLDevice, type, int64,             \
                                      Eigen::internal::SumReducer<type>>);
REGISTER_SYCL_KERNELS(float);
REGISTER_SYCL_KERNELS(double);

REGISTER_KERNEL_BUILDER(
    Name("Sum")
        .Device(DEVICE_SYCL)
        .TypeConstraint<int32>("T")
        .TypeConstraint<int32>("Tidx")
        .HostMemory("input")
        .HostMemory("output")
        .HostMemory("reduction_indices"),
    ReductionOp<CPUDevice, int32, int32, Eigen::internal::SumReducer<int32>>);
REGISTER_KERNEL_BUILDER(
    Name("Sum")
        .Device(DEVICE_SYCL)
        .TypeConstraint<int32>("T")
        .TypeConstraint<int64>("Tidx")
        .HostMemory("input")
        .HostMemory("output")
        .HostMemory("reduction_indices"),
    ReductionOp<CPUDevice, int32, int64, Eigen::internal::SumReducer<int32>>);
#undef REGISTER_SYCL_KERNELS
#endif  // TENSORFLOW_USE_SYCL

}  // namespace tensorflow
<|endoftext|>


<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/platform/test.h"

namespace tensorflow {

TEST(StringPiece, Ctor) {
  {
    // const char* without size.
    const char* hello = "hello";
    StringPiece s20(hello);
    EXPECT_TRUE(s20.data() == hello);
    EXPECT_EQ(5, s20.size());

    // const char* with size.
    StringPiece s21(hello, 4);
    EXPECT_TRUE(s21.data() == hello);
    EXPECT_EQ(4, s21.size());

    // Not recommended, but valid C++
    StringPiece s22(hello, 6);
    EXPECT_TRUE(s22.data() == hello);
    EXPECT_EQ(6, s22.size());
  }

  {
    string hola = "hola";
    StringPiece s30(hola);
    EXPECT_TRUE(s30.data() == hola.data());
    EXPECT_EQ(4, s30.size());

    // std::string with embedded '\0'.
    hola.push_back('\0');
    hola.append("h2");
    hola.push_back('\0');
    StringPiece s31(hola);
    EXPECT_TRUE(s31.data() == hola.data());
    EXPECT_EQ(8, s31.size());
  }
}

TEST(StringPiece, Contains) {
  StringPiece a("abcdefg");
  StringPiece b("abcd");
  StringPiece c("efg");
  StringPiece d("gh");
  EXPECT_TRUE(a.contains(b));
  EXPECT_TRUE(a.contains(c));
  EXPECT_TRUE(!a.contains(d));
}

}  // namespace tensorflow
<commit_msg>Added tests for tensorflow::StringPiece::Hasher.<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/lib/core/stringpiece.h"

#include <unordered_map>
#include "tensorflow/core/platform/test.h"

namespace tensorflow {

TEST(StringPiece, Ctor) {
  {
    // const char* without size.
    const char* hello = "hello";
    StringPiece s20(hello);
    EXPECT_TRUE(s20.data() == hello);
    EXPECT_EQ(5, s20.size());

    // const char* with size.
    StringPiece s21(hello, 4);
    EXPECT_TRUE(s21.data() == hello);
    EXPECT_EQ(4, s21.size());

    // Not recommended, but valid C++
    StringPiece s22(hello, 6);
    EXPECT_TRUE(s22.data() == hello);
    EXPECT_EQ(6, s22.size());
  }

  {
    string hola = "hola";
    StringPiece s30(hola);
    EXPECT_TRUE(s30.data() == hola.data());
    EXPECT_EQ(4, s30.size());

    // std::string with embedded '\0'.
    hola.push_back('\0');
    hola.append("h2");
    hola.push_back('\0');
    StringPiece s31(hola);
    EXPECT_TRUE(s31.data() == hola.data());
    EXPECT_EQ(8, s31.size());
  }
}

TEST(StringPiece, Contains) {
  StringPiece a("abcdefg");
  StringPiece b("abcd");
  StringPiece c("efg");
  StringPiece d("gh");
  EXPECT_TRUE(a.contains(b));
  EXPECT_TRUE(a.contains(c));
  EXPECT_TRUE(!a.contains(d));
}

TEST(StringPieceHasher, Equality) {
  StringPiece::Hasher hasher;

  StringPiece s1("foo");
  StringPiece s2("bar");
  StringPiece s3("baz");
  StringPiece s4("zot");

  EXPECT_TRUE(hasher(s1) != hasher(s2));
  EXPECT_TRUE(hasher(s1) != hasher(s3));
  EXPECT_TRUE(hasher(s1) != hasher(s4));
  EXPECT_TRUE(hasher(s2) != hasher(s3));
  EXPECT_TRUE(hasher(s2) != hasher(s4));
  EXPECT_TRUE(hasher(s3) != hasher(s4));

  EXPECT_TRUE(hasher(s1) == hasher(s1));
  EXPECT_TRUE(hasher(s2) == hasher(s2));
  EXPECT_TRUE(hasher(s3) == hasher(s3));
  EXPECT_TRUE(hasher(s4) == hasher(s4));
}

TEST(StringPieceHasher, HashMap) {
  string s1("foo");
  string s2("bar");
  string s3("baz");

  StringPiece p1(s1);
  StringPiece p2(s2);
  StringPiece p3(s3);

  std::unordered_map<StringPiece, int, StringPiece::Hasher> map;

  map.insert(std::make_pair(p1, 0));
  map.insert(std::make_pair(p2, 1));
  map.insert(std::make_pair(p3, 2));
  EXPECT_EQ(map.size(), 3);

  bool found[3] = {false, false, false};
  for (auto const& val : map) {
    int x = val.second;
    EXPECT_TRUE(x >= 0 && x < 3);
    EXPECT_TRUE(!found[x]);
    found[x] = true;
  }
  EXPECT_EQ(found[0], true);
  EXPECT_EQ(found[1], true);
  EXPECT_EQ(found[2], true);

  auto new_iter = map.find("zot");
  EXPECT_TRUE(new_iter == map.end());

  new_iter = map.find("bar");
  EXPECT_TRUE(new_iter != map.end());

  map.erase(new_iter);
  EXPECT_EQ(map.size(), 2);

  found[0] = false;
  found[1] = false;
  found[2] = false;
  for (const auto& iter : map) {
    int x = iter.second;
    EXPECT_TRUE(x >= 0 && x < 3);
    EXPECT_TRUE(!found[x]);
    found[x] = true;
  }
  EXPECT_EQ(found[0], true);
  EXPECT_EQ(found[1], false);
  EXPECT_EQ(found[2], true);
}
}  // namespace tensorflow
<|endoftext|>