text:
/*
    Copyright 2005-2007 Adobe Systems Incorporated
    Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt
    or a copy at http://stlab.adobe.com/licenses.html)
*/

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

#ifndef ADOBE_LEX_SHARED_HPP
#define ADOBE_LEX_SHARED_HPP

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

#include <adobe/config.hpp>

#include <adobe/implementation/lex_shared_fwd.hpp>
#include <adobe/string.hpp>
#include <adobe/name.hpp>
#include <adobe/istream.hpp>
#include <adobe/circular_queue.hpp>
#include <adobe/implementation/parser_shared.hpp>

#include <iostream>
#include <cstdio>

#include <boost/function.hpp>
#include <boost/array.hpp>

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

#ifdef BOOST_MSVC
namespace std
{
    using ::isspace;
    using ::isdigit;
    using ::isalnum;
    using ::isalpha;
}
#endif

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

namespace adobe {

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

template <  std::size_t S,
            typename    E>  // E models Enumeration
struct lex_base_t
{
 public:
    typedef std::istream::pos_type      pos_type;
    typedef boost::function<void ()>    parse_token_proc_t;
    typedef lex_token_t<E>              token_type;

    lex_base_t(uchar_ptr_t first, uchar_ptr_t last, const line_position_t& position);

    virtual ~lex_base_t();

    const token_type&       get_token();
    void                    putback_token();
    void                    put_token(const token_type& token);

    void                    init_token(token_type& token)
        { token.range_m.first = first_m; }
    void                    finalize_token(token_type& token, E enumeration)
        { token.range_m.second = first_m; token.enum_m = enumeration; }
    void                    reset_lex(const token_type& token)
        { first_m = token.range_m.first; }

    void                    advance_lex()
        { ++first_m; }
    bool                    peek_char(char& c)
        { if (first_m == last_m) return false; c = *first_m; return true; }
    bool                    get_char(char& c)
        { bool result(peek_char(c)); if (result) advance_lex(); return result; }

    void                    set_lex_position(uchar_ptr_t p) { first_m = p; }

    void                    throw_exception(E expected, E found);
    void                    throw_parser_exception(const char* error_string);

    void                    set_skip_white_space(bool skip);

    void                    skip_white_space();

    const line_position_t&  next_position();

    bool                    is_eof();
    bool                    is_line_end();

    void                    set_parse_token_proc(parse_token_proc_t proc);

private:
    struct lex_fragment_t
    {
        lex_fragment_t( const token_type&       token = token_type(),
                        const line_position_t&  line_position = line_position_t()) :
            token_value_m(token), line_position_m(line_position)
        { }

        token_type      token_value_m;
        line_position_t line_position_m;
    };

    uchar_ptr_t                         first_m;
    uchar_ptr_t                         last_m;
    std::streampos                      streampos_m;
    line_position_t                     line_position_m;
    parse_token_proc_t                  parse_proc_m;
    bool                                skip_white_m;
    boost::array<char, 8>               putback_m; // stack-based is faster
    std::size_t                         index_m; // for putback_m

#if !defined(ADOBE_NO_DOCUMENTATION)
    circular_queue<lex_fragment_t>  last_token_m; // N token lookahead
#endif // !defined(ADOBE_NO_DOCUMENTATION)
};

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

template <std::size_t S, typename E>
lex_base_t<S, E>::lex_base_t(uchar_ptr_t first, uchar_ptr_t last, const line_position_t& position) :
    first_m(first),
    last_m(last),
    streampos_m(0),
    line_position_m(position),
    skip_white_m(true),
    index_m(0),
    last_token_m(S)
{ }

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

template <std::size_t S, typename E>
lex_base_t<S, E>::~lex_base_t()
{ }

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

template <std::size_t S, typename E>
const typename lex_base_t<S, E>::token_type& lex_base_t<S, E>::get_token()
{
    assert(parse_proc_m);

    if (last_token_m.empty())
    {
        if (skip_white_m)
            skip_white_space();

        line_position_m.position_m = streampos_m; // remember the start of the token position

        if (!is_eof())
            parse_proc_m();
    }

    token_type& result(last_token_m.front().token_value_m);

    last_token_m.pop_front();

    return result;
}

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

template <std::size_t S, typename E>
void lex_base_t<S, E>::put_token(const token_type& token)
{
    last_token_m.push_back(lex_fragment_t(token, line_position_m));
}

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

template <std::size_t S, typename E>
void lex_base_t<S, E>::putback_token()
{
    last_token_m.putback(); // REVISIT (sparent) : Check for overflow
}

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

template <std::size_t S, typename E>
const line_position_t& lex_base_t<S, E>::next_position()
{
/*
    REVISIT (sparent) : Clean this up - this primes the ring buffer so we can get the next position
*/
    get_token(); putback_token();

    return last_token_m.front().line_position_m;
}

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

template <std::size_t S, typename E>
bool lex_base_t<S, E>::is_line_end()
{
    using adobe::is_line_end;

    uchar_ptr_t old_first(first_m);

    bool result(is_line_end(first_m, last_m));

    if (result)
    {
        ++line_position_m.line_number_m;

        streampos_m += static_cast<std::streamoff>(std::distance(old_first, first_m));

        line_position_m.line_start_m = streampos_m;
    }

    return result;
}

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

template <std::size_t S, typename E>
bool lex_base_t<S, E>::is_eof()
{
    if (first_m != last_m) return false;

    put_token(token_type(eof_token<E>(), last_m, last_m));

    return true;
}

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

template <std::size_t S, typename E>
void lex_base_t<S, E>::throw_parser_exception(const char* error_string)
{
    using adobe::throw_parser_exception;

    throw_parser_exception(error_string, line_position_m);
}

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

template <std::size_t S, typename E>
void lex_base_t<S, E>::set_parse_token_proc(parse_token_proc_t proc)
{
    parse_proc_m = proc;
}

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

template <std::size_t S, typename E>
void lex_base_t<S, E>::set_skip_white_space(bool skip)
{
    skip_white_m = skip;
}

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

template <std::size_t S, typename E>
void lex_base_t<S, E>::skip_white_space()
{
    while (true)
    {
        (void)is_line_end();

        if (first_m == last_m) break;

        char c;

        if (peek_char(c) && std::isspace(static_cast<unsigned char>(c)))
            advance_lex();
        else
            break;
    }
}

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

#if 0
#pragma mark -
#endif

/*************************************************************************************************/
namespace implementation {

struct lex_fragment_t
{
    lex_fragment_t( stream_lex_token_t      token = stream_lex_token_t(),
                    const line_position_t&  line_position = line_position_t()) :
        token_value_m(adobe::move(token)), line_position_m(line_position)
    { }

    lex_fragment_t(move_from<lex_fragment_t> x) :
        token_value_m(adobe::move(x.source.token_value_m)), line_position_m(adobe::move(x.source.line_position_m))
    { }

    lex_fragment_t& operator=(lex_fragment_t x)
    {
        token_value_m = adobe::move(x.token_value_m);
        line_position_m = adobe::move(x.line_position_m);
        return *this;
    }

    stream_lex_token_t  token_value_m;
    line_position_t     line_position_m;
};

} // namespace implementation

template <  std::size_t S,
            typename    I>  // I models InputIterator
struct stream_lex_base_t
{
 public:
    typedef std::istream::pos_type                          pos_type;
    typedef boost::function<void (char)>                    parse_token_proc_t;

    stream_lex_base_t(I first, I last, const line_position_t& position);

    virtual ~stream_lex_base_t();

    const stream_lex_token_t&   get_token();
    void                        putback_token();
    void                        put_token(stream_lex_token_t token);

    bool                    get_char(char& c);
    void                    putback_char(char c);
    int                     peek_char();
    void                    ignore_char();

    void                    throw_exception(const name_t& expected, const name_t& found);
    void                    throw_parser_exception(const char* error_string);

    void                    set_skip_white_space(bool skip);

    void                    skip_white_space();

    const line_position_t&  next_position();

    bool                    is_line_end(char c);

    void                    set_parse_token_proc(parse_token_proc_t proc);

    std::vector<char>       identifier_buffer_m;

private:
    I                                   first_m;
    I                                   last_m;
    std::streampos                      streampos_m;
    line_position_t                     line_position_m;
    parse_token_proc_t                  parse_proc_m;
    bool                                skip_white_m;
    boost::array<char, 8>               putback_m; // stack-based is faster
    std::size_t                         index_m; // for putback_m

#if !defined(ADOBE_NO_DOCUMENTATION)
    circular_queue<implementation::lex_fragment_t>  last_token_m; // N token lookahead
#endif // !defined(ADOBE_NO_DOCUMENTATION)
};

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

template <std::size_t S, typename I>
stream_lex_base_t<S, I>::stream_lex_base_t(I first, I last, const line_position_t& position) :
    identifier_buffer_m(128),
    first_m(first),
    last_m(last),
    streampos_m(1),
    line_position_m(position),
    skip_white_m(true),
    index_m(0),
    last_token_m(S)
{ }

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

template <std::size_t S, typename I>
stream_lex_base_t<S, I>::~stream_lex_base_t()
{ }

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

template <std::size_t S, typename I>
bool stream_lex_base_t<S, I>::get_char(char& c)
{
    if (index_m)
    {
        c = static_cast<char>(putback_m[index_m]);

        --index_m;

        streampos_m += 1;

        return true;
    }

    if (first_m == last_m) return false;

    c = static_cast<char>(*first_m);

    ++first_m;

    streampos_m += 1;

    return true;
}

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

template <std::size_t S, typename I>
void stream_lex_base_t<S, I>::putback_char(char c)
{
    putback_m[++index_m] = c;

    streampos_m -= 1;
}

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

template <std::size_t S, typename I>
int stream_lex_base_t<S, I>::peek_char()
{
    if (index_m)
        return putback_m[index_m];
    else if (first_m == last_m)
        return EOF;
    else
        return *first_m;
}

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

template <std::size_t S, typename I>
void stream_lex_base_t<S, I>::ignore_char()
{
    if (index_m)
        --index_m;
    else if (first_m == last_m)
        return;
    else
        ++first_m;

    streampos_m += 1;
}

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

template <std::size_t S, typename I>
const stream_lex_token_t& stream_lex_base_t<S, I>::get_token()
{
    assert(parse_proc_m);

    if (last_token_m.empty())
    {
        char c;

    /*
        REVISIT (sparent) : You can't get(c), tellg(), and then putback(c) on a stream - the
        tellg() in the middle will cause the putback(c) to move the stream to an invalid state.
        So instead of calling skip_space(c) we break up the call with the tellg() in the middle,
        prior to the callback.
    */

        if (skip_white_m)
            skip_white_space();

        line_position_m.position_m = streampos_m; // remember the start of the token position

    /*
        REVISIT (sparent) : I don't like that eof is not handled as the other tokens are handled
        there should be a way to make this logic consistant.
    */

        if (!get_char(c)) // eof
            put_token(stream_lex_token_t(eof_k, any_regular_t()));
        else
            parse_proc_m(c);
    }

    stream_lex_token_t& result(last_token_m.front().token_value_m);

    last_token_m.pop_front();

    return result;
}

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

template <std::size_t S, typename I>
void stream_lex_base_t<S, I>::put_token(stream_lex_token_t token)
{
    last_token_m.push_back(implementation::lex_fragment_t(adobe::move(token), line_position_m));
}

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

template <std::size_t S, typename I>
void stream_lex_base_t<S, I>::putback_token()
{
    last_token_m.putback(); // REVISIT (sparent) : Check for overflow
}

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

template <std::size_t S, typename I>
const line_position_t& stream_lex_base_t<S, I>::next_position()
{
/*
    REVISIT (sparent) : Clean this up - this primes the ring buffer so we can get the next position
*/
    get_token(); putback_token();

    return last_token_m.front().line_position_m;
}

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

template <std::size_t S, typename I>
bool stream_lex_base_t<S, I>::is_line_end(char c)
{
    using adobe::is_line_end;

    std::size_t num_chars_eaten(is_line_end(first_m, last_m, c));

    if (num_chars_eaten != 0)
    {
        ++line_position_m.line_number_m;

        if (num_chars_eaten == 2)
            streampos_m += 1;

        line_position_m.line_start_m = streampos_m;
    }

    return num_chars_eaten != 0;
}

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

template <std::size_t S, typename I>
void stream_lex_base_t<S, I>::throw_parser_exception(const char* error_string)
{
    using adobe::throw_parser_exception;

    throw_parser_exception(error_string, line_position_m);
}

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

template <std::size_t S, typename I>
void stream_lex_base_t<S, I>::set_parse_token_proc(parse_token_proc_t proc)
{
    parse_proc_m = proc;
}

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

template <std::size_t S, typename I>
void stream_lex_base_t<S, I>::set_skip_white_space(bool skip)
{
    skip_white_m = skip;
}

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

template <std::size_t S, typename I>
void stream_lex_base_t<S, I>::skip_white_space()
{
    char c;

    while (get_char(c))
    {
        // Handle any type of line ending.
        if (!is_line_end(c) && !std::isspace(c))
        {
            putback_char(c);

            break;
        }
    }
}

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

} // namespace adobe

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

#endif

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

ext: hpp

max_stars_repo_name: andyprowl/virtual-concepts

max_issues_repo_name: brycelelbach/asl

max_forks_repo_name: brycelelbach/asl


text:
//
// Copyright (c) 2018-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/vinniefalco/BeastLounge
//

// Test that header file is self-contained.
#include <boost/beast/_experimental/json/parser.hpp>

#include <boost/beast/_experimental/unit_test/suite.hpp>
#include <boost/beast/_experimental/json/parser.hpp>
#include <sstream>

namespace boost {
namespace beast {
namespace json {

class parser_test : public unit_test::suite
{
public:
    void
    testParser()
    {
        string_view in =
R"xx({
    "glossary": {
        "title": "example glossary",
		"GlossDiv": {
            "title": "S",
			"GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML"]
                    },
					"GlossSee": "markup"
                }
            }
        }
    }
})xx"
        ;
        parser p;
        error_code ec;
        p.write({in.data(), in.size()}, ec);
        if(BEAST_EXPECTS(! ec, ec.message()))
        {
            std::stringstream ss;
            ss << p.get();
            BEAST_EXPECT(ss.str() ==
                "{\"glossary\":{\"title\":\"example glossary\",\"GlossDiv\":"
                "{\"title\":\"S\",\"GlossList\":{\"GlossEntry\":{\"ID\":\"SGML\","
                "\"SortAs\":\"SGML\",\"GlossTerm\":\"Standard Generalized Markup "
                "Language\",\"Acronym\":\"SGML\",\"Abbrev\":\"ISO 8879:1986\","
                "\"GlossDef\":{\"para\":\"A meta-markup language, used to create "
                "markup languages such as DocBook.\",\"GlossSeeAlso\":[\"GML\",\"XML\"]},"
                "\"GlossSee\":\"markup\"}}}}}"
            );
        }
    }

    void
    run()
    {
        log <<
            "sizeof(parser) == " <<
            sizeof(parser) << "\n";
        testParser();
    }
};

BEAST_DEFINE_TESTSUITE(beast,json,parser);

} // json
} // beast
} // boost

ext: cpp

max_stars_repo_name: djarek/BeastLounge

max_issues_repo_name: djarek/BeastLounge

max_forks_repo_name: djarek/BeastLounge


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

#include "service/impala-internal-service.h"

#include <boost/lexical_cast.hpp>

#include "common/status.h"
#include "gutil/strings/substitute.h"
#include "service/impala-server.h"
#include "runtime/query-exec-mgr.h"
#include "runtime/query-state.h"
#include "runtime/fragment-instance-state.h"
#include "runtime/exec-env.h"
#include "testutil/fault-injection-util.h"

#include "common/names.h"

using namespace impala;

ImpalaInternalService::ImpalaInternalService() {
  impala_server_ = ExecEnv::GetInstance()->impala_server();
  DCHECK(impala_server_ != nullptr);
  query_exec_mgr_ = ExecEnv::GetInstance()->query_exec_mgr();
  DCHECK(query_exec_mgr_ != nullptr);
}

void ImpalaInternalService::ExecPlanFragment(TExecPlanFragmentResult& return_val,
    const TExecPlanFragmentParams& params) {
  VLOG_QUERY << "ExecPlanFragment():"
            << " instance_id=" << params.fragment_instance_ctx.fragment_instance_id;
  FAULT_INJECTION_RPC_DELAY(RPC_EXECPLANFRAGMENT);
  query_exec_mgr_->StartFInstance(params).SetTStatus(&return_val);
}

template <typename T> void SetUnknownIdError(
    const string& id_type, const TUniqueId& id, T* status_container) {
  Status status(ErrorMsg(TErrorCode::INTERNAL_ERROR,
      Substitute("Unknown $0 id: $1", id_type, lexical_cast<string>(id))));
  status.SetTStatus(status_container);
}

void ImpalaInternalService::CancelPlanFragment(TCancelPlanFragmentResult& return_val,
    const TCancelPlanFragmentParams& params) {
  VLOG_QUERY << "CancelPlanFragment(): instance_id=" << params.fragment_instance_id;
  FAULT_INJECTION_RPC_DELAY(RPC_CANCELPLANFRAGMENT);
  QueryState::ScopedRef qs(GetQueryId(params.fragment_instance_id));
  if (qs.get() == nullptr) {
    SetUnknownIdError("query", GetQueryId(params.fragment_instance_id), &return_val);
    return;
  }
  FragmentInstanceState* fis = qs->GetFInstanceState(params.fragment_instance_id);
  if (fis == nullptr) {
    SetUnknownIdError("instance", params.fragment_instance_id, &return_val);
    return;
  }
  Status status = fis->Cancel();
  status.SetTStatus(&return_val);
}

void ImpalaInternalService::ReportExecStatus(TReportExecStatusResult& return_val,
    const TReportExecStatusParams& params) {
  VLOG_QUERY << "ReportExecStatus(): instance_id=" << params.fragment_instance_id;
  FAULT_INJECTION_RPC_DELAY(RPC_REPORTEXECSTATUS);
  impala_server_->ReportExecStatus(return_val, params);
}

void ImpalaInternalService::TransmitData(TTransmitDataResult& return_val,
    const TTransmitDataParams& params) {
  FAULT_INJECTION_RPC_DELAY(RPC_TRANSMITDATA);
  impala_server_->TransmitData(return_val, params);
}

void ImpalaInternalService::UpdateFilter(TUpdateFilterResult& return_val,
    const TUpdateFilterParams& params) {
  VLOG_QUERY << "UpdateFilter(): filter=" << params.filter_id
            << " query_id=" << PrintId(params.query_id);
  FAULT_INJECTION_RPC_DELAY(RPC_UPDATEFILTER);
  impala_server_->UpdateFilter(return_val, params);
}

void ImpalaInternalService::PublishFilter(TPublishFilterResult& return_val,
    const TPublishFilterParams& params) {
  VLOG_QUERY << "PublishFilter(): filter=" << params.filter_id
            << " instance_id=" << PrintId(params.dst_instance_id);
  FAULT_INJECTION_RPC_DELAY(RPC_PUBLISHFILTER);
  QueryState::ScopedRef qs(GetQueryId(params.dst_instance_id));
  if (qs.get() == nullptr) return;
  FragmentInstanceState* fis = qs->GetFInstanceState(params.dst_instance_id);
  if (fis == nullptr) return;
  fis->PublishFilter(params.filter_id, params.bloom_filter);
}

ext: cc

max_stars_repo_name: michaelhkw/impala

max_issues_repo_name: michaelhkw/impala

max_forks_repo_name: michaelhkw/impala


text:
//=======================================================================
// Copyright 2007 Aaron Windsor
//
// 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)
//=======================================================================
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>
#include <vector>

#include <boost/graph/connected_components.hpp>
#include <boost/graph/make_connected.hpp>

using namespace boost;

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

  typedef adjacency_list
    < vecS,
      vecS,
      undirectedS,
      property<vertex_index_t, int>
    >
    graph;

  graph g(11);
  add_edge(0,1,g);
  add_edge(2,3,g);
  add_edge(3,4,g);
  add_edge(5,6,g);
  add_edge(6,7,g);
  add_edge(8,9,g);
  add_edge(9,10,g);
  add_edge(10,8,g);

  std::vector< graph_traits<graph>::vertices_size_type >
    component(num_vertices(g));

  std::cout << "Before calling make_connected, the graph has "
            << connected_components(g, &component[0])
            << " connected components" << std::endl;

  make_connected(g);

  std::cout << "After calling make_connected, the graph has "
            << connected_components(g, &component[0])
            << " connected components" << std::endl;

  return 0;
}


text:
// Copyright (c) 2022 hs293go
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT

#include <pybind11/attr.h>
#include <pybind11/embed.h>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>

#include <Eigen/Dense>
#include <cmath>

namespace py = pybind11;
int main() {
  // Prepare the data...
  const Eigen::VectorXd xv_data = Eigen::VectorXd::LinSpaced(10000, -4, 4);
  const Eigen::VectorXd yv_data =
      xv_data.unaryExpr([](double it) { return tgamma(it); });

  // Embed the interpreter in the current scope
  py::scoped_interpreter interp{};

  // Import the module, similar to `import matplotlib.pyplot as plt`
  auto plt = py::module::import("matplotlib.pyplot");

  // Pybind11 does namespace/member resolution by `().attr("name")`.
  // Bring in `plot` etc. like `from matplotlib.pyplot import plot`
  auto plot = plt.attr("plot");
  auto show = plt.attr("show");
  auto ylim = plt.attr("ylim");
  auto savefig = plt.attr("savefig");

  // Use the following py::array ctor to map an existing buffer
  // https://pybind11.readthedocs.io/en/stable/advanced/pycpp/numpy.html
  py::array xv(xv_data.size(), xv_data.data());
  py::array yv(yv_data.size(), yv_data.data());

  // plot and show!
  plot(xv, yv, "r--");
  ylim(-10, 10);
  savefig("res/readme.png");
  show();
}


text:
// Copyright (c) Benjamin Kietzman (github.com/bkietz)
//
// 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 DBUS_FUNCTIONAL_HPP
#define DBUS_FUNCTIONAL_HPP

/*
#ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL
#include <functional>
namespace dbus {
using std::function;
}
#else
#include <boost/tr1/functional.hpp>
namespace dbus {
using std::tr1::function;
}
#endif
*/

// The above was not working because of
// reference_wrapper being declared in std::tr1.
// I suspect this is a bug in BOOST_HAS_TR1_REFERENCE_WRAPPER
#include <boost/function.hpp>
namespace dbus {
using boost::function;
}

#endif // DBUS_FUNCTIONAL_HPP

max_stars_repo_name: bkietz/boost-dbus

max_issues_repo_name: bkietz/boost-dbus

max_forks_repo_name: bkietz/boost-dbus


text:
/* Copyright (c) 2016 - 2020, the adamantine authors.
 *
 * This file is subject to the Modified BSD License and may not be distributed
 * without copyright and license information. Please refer to the file LICENSE
 * for the text and further information on this license.
 */

#ifndef GEOMETRY_TEMPLATES_HH
#define GEOMETRY_TEMPLATES_HH

#include <Geometry.hh>
#include <instantiation.hh>
#include <types.hh>
#include <utils.hh>

#include <deal.II/grid/filtered_iterator.h>
#include <deal.II/grid/grid_generator.h>

namespace adamantine
{

template <int dim>
Geometry<dim>::Geometry(MPI_Comm const &communicator,
                        boost::property_tree::ptree const &database)
    : _triangulation(communicator)
{
  std::vector<unsigned int> repetitions(dim);
  repetitions[0] = database.get("length_divisions", 10);
  repetitions[1] = database.get("height_divisions", 10);
  if (dim == 3)
    repetitions[2] = database.get("width_divisions", 10);

  dealii::Point<dim> p1;
  dealii::Point<dim> p2;
  p2[0] = database.get<double>("length");
  p2[1] = database.get<double>("height");
  _max_height = p2[1];
  if (dim == 3)
    p2[2] = database.get<double>("width");

  // For now we assume that the geometry is very simple.
  dealii::GridGenerator::subdivided_hyper_rectangle(_triangulation, repetitions,
                                                    p1, p2, true);

  // Assign the MaterialID and the MaterialState.
  dealii::types::boundary_id const top_boundary = 3;
  for (auto cell : _triangulation.active_cell_iterators())
  {
    cell->set_material_id(0);
    if (cell->at_boundary())
    {
      bool is_powder = false;
      for (unsigned int i = 0; i < dealii::GeometryInfo<dim>::faces_per_cell;
           ++i)
      {
        if ((cell->face(i)->at_boundary()) &&
            (cell->face(i)->boundary_id() == top_boundary))
        {
          cell->set_user_index(static_cast<int>(MaterialState::powder));
          is_powder = true;
          break;
        }
      }
      if (is_powder == false)
        cell->set_user_index(static_cast<int>(MaterialState::solid));
    }
    else
      cell->set_user_index(static_cast<int>(MaterialState::solid));
  }
}
} // namespace adamantine

INSTANTIATE_DIM(Geometry)

#endif

max_stars_repo_name: stvdwtt/adamantine

max_issues_repo_name: stvdwtt/adamantine

max_forks_repo_name: stvdwtt/adamantine


text:
/*
Part of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)
Copyright 2017-2019 University of Huddersfield.
Licensed under the BSD-3 License.
See license.md file in the project root for full license information.
This project has received funding from the European Research Council (ERC)
under the European Union’s Horizon 2020 research and innovation programme
(grant agreement No 725899).
*/

#pragma once

#include "Envelope.hpp"
#include "../util/ButterworthHPFilter.hpp"
#include "../util/FluidEigenMappings.hpp"
#include "../util/SlideUDFilter.hpp"
#include "../../data/FluidIndex.hpp"
#include "../../data/TensorTypes.hpp"
#include <Eigen/Core>
#include <cmath>

namespace fluid {
namespace algorithm {

class EnvelopeSegmentation
{

  using ArrayXd = Eigen::ArrayXd;

public:
  void init(double floor, double hiPassFreq)
  {
    // mFastSlide.init(floor);
    // mSlowSlide.init(floor);
    mEnvelope.init(floor,hiPassFreq);
    mDebounceCount = 1;
    // initFilters(hiPassFreq);
    // mHiPassFreq = hiPassFreq;
    mPrevValue = 0;
    mState = false;
    // mInitialized = true;
  }

  double processSample(const double in, double onThreshold, double offThreshold,
                       double floor, index fastRampUpTime, index slowRampUpTime,
                       index fastRampDownTime, index slowRampDownTime,
                       double hiPassFreq, index debounce)
  {
    // using namespace std;
    // assert(mInitialized);
    // mFastSlide.updateCoeffs(fastRampUpTime, fastRampDownTime);
    // mSlowSlide.updateCoeffs(slowRampUpTime, slowRampDownTime);
    // double filtered = in;
    // if (hiPassFreq != mHiPassFreq)
    // {
    //   initFilters(hiPassFreq);
    //   mHiPassFreq = hiPassFreq;
    // }
    // if (mHiPassFreq > 0){
    //   filtered = mHiPass2.processSample(mHiPass1.processSample(in));
    // }
    // double rectified = abs(filtered);
    // double dB = 20 * log10(rectified);
    // double clipped = max(dB, floor);
    // double fast = mFastSlide.processSample(clipped);
    // double slow = mSlowSlide.processSample(clipped);
    // double value = fast - slow;

    double value =
        mEnvelope.processSample(in, floor, fastRampUpTime, slowRampUpTime,
                                fastRampDownTime, slowRampDownTime, hiPassFreq);
    double detected = 0;

    if (!mState && value > onThreshold && mPrevValue < onThreshold &&
        mDebounceCount == 0)
    {
      detected = 1.0;
      mDebounceCount = debounce;
      mState = true;
    }
    else
    {
      if (mDebounceCount > 0) mDebounceCount--;
    }
    if (mState && value < offThreshold) { mState = false; }
    mPrevValue = value;
    return detected;
  }

  bool initialized() { return mEnvelope.initialized(); }

private:
//  void initFilters(double cutoff)
//  {
//    mHiPass1.init(cutoff);
//    mHiPass2.init(cutoff);
//  }

  Envelope mEnvelope;
  // double mHiPassFreq{0};
  index  mDebounceCount{1};
  double mPrevValue{0};
  // bool   mInitialized{false};
  bool   mState{false};

  // ButterworthHPFilter mHiPass1;
  // ButterworthHPFilter mHiPass2;
  // SlideUDFilter       mFastSlide;
  // SlideUDFilter       mSlowSlide;
};
} // namespace algorithm
} // namespace fluid


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// 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
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//

#define BOOST_TEST_MODULE TestLocalBuffer
#include <boost/test/unit_test.hpp>

#include <boost/compute/core.hpp>
#include <boost/compute/memory/local_buffer.hpp>
#include <boost/compute/utility/source.hpp>

#include "context_setup.hpp"

namespace compute = boost::compute;

BOOST_AUTO_TEST_CASE(local_buffer_arg)
{
    if(device.get_info<CL_DEVICE_LOCAL_MEM_TYPE>() != CL_LOCAL){
        std::cerr << "skipping local buffer arg test: "
                  << "device does not support local memory" << std::endl;
        return;
    }

    const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
        __kernel void foo(__local float *local_buffer,
                          __global float *global_buffer)
        {
            const uint gid = get_global_id(0);
            const uint lid = get_local_id(0);

            local_buffer[lid] = gid;

            global_buffer[gid] = local_buffer[lid];
        }
    );

    // create and build program
    compute::program program =
        compute::program::build_with_source(source, context);

    // create kernel
    compute::kernel kernel = program.create_kernel("foo");

    // setup kernel arguments
    compute::buffer global_buf(context, 128 * sizeof(float));
    kernel.set_arg(0, compute::local_buffer<float>(32));
    kernel.set_arg(1, global_buf);

    // some implementations don't correctly report dynamically-set local buffer sizes
    if(kernel.get_work_group_info<cl_ulong>(device, CL_KERNEL_LOCAL_MEM_SIZE) == 0){
        std::cerr << "skipping checks for local memory size, device reports "
                  << "zero after setting dynamically-sized local buffer size"
                  << std::endl;
        return;
    }

    // check actual memory size
    BOOST_CHECK_GE(
        kernel.get_work_group_info<cl_ulong>(device, CL_KERNEL_LOCAL_MEM_SIZE),
        32 * sizeof(float)
    );

    // increase local buffer size and check new actual local memory size
    kernel.set_arg(0, compute::local_buffer<float>(64));

    BOOST_CHECK_GE(
        kernel.get_work_group_info<cl_ulong>(device, CL_KERNEL_LOCAL_MEM_SIZE),
        64 * sizeof(float)
    );
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: skozilla/compute

max_issues_repo_name: skozilla/compute

max_forks_repo_name: skozilla/compute


text:
/*
 * Copyright Nick Thompson, 2017
 * Use, modification and distribution are subject to 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)
 *
 * Use the adaptive trapezoidal rule to estimate the integral of periodic functions over a period,
 * or to integrate a function whose derivative vanishes at the endpoints.
 *
 * If your function does not satisfy these conditions, and instead is simply continuous and bounded
 * over the whole interval, then this routine will still converge, albeit slowly. However, there
 * are much more efficient methods in this case, including Romberg, Simpson, and double exponential quadrature.
 */

#ifndef BOOST_MATH_QUADRATURE_TRAPEZOIDAL_HPP
#define BOOST_MATH_QUADRATURE_TRAPEZOIDAL_HPP

#include <cmath>
#include <limits>
#include <stdexcept>
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <boost/math/policies/error_handling.hpp>

namespace boost{ namespace math{ namespace quadrature {

template<class F, class Real, class Policy>
auto trapezoidal(F f, Real a, Real b, Real tol, std::size_t max_refinements, Real* error_estimate, Real* L1, const Policy& pol)->decltype(std::declval<F>()(std::declval<Real>()))
{
    static const char* function = "boost::math::quadrature::trapezoidal<%1%>(F, %1%, %1%, %1%)";
    using std::abs;
    using boost::math::constants::half;
    // In many math texts, K represents the field of real or complex numbers.
    // Too bad we can't put blackboard bold into C++ source!
    typedef decltype(f(a)) K;
    if(a >= b)
    {
       return static_cast<K>(boost::math::policies::raise_domain_error(function, "a < b for integration over the region [a, b] is required, but got a = %1%.\n", a, pol));
    }
    if (!(boost::math::isfinite)(a))
    {
       return static_cast<K>(boost::math::policies::raise_domain_error(function, "Left endpoint of integration must be finite for adaptive trapezoidal integration but got a = %1%.\n", a, pol));
    }
    if (!(boost::math::isfinite)(b))
    {
       return static_cast<K>(boost::math::policies::raise_domain_error(function, "Right endpoint of integration must be finite for adaptive trapedzoidal integration but got b = %1%.\n", b, pol));
    }

    K ya = f(a);
    K yb = f(b);
    Real h = (b - a)*half<Real>();
    K I0 = (ya + yb)*h;
    Real IL0 = (abs(ya) + abs(yb))*h;

    K yh = f(a + h);
    K I1;
    I1 = I0*half<Real>() + yh*h;
    Real IL1 = IL0*half<Real>() + abs(yh)*h;

    // The recursion is:
    // I_k = 1/2 I_{k-1} + 1/2^k \sum_{j=1; j odd, j < 2^k} f(a + j(b-a)/2^k)
    std::size_t k = 2;
    // We want to go through at least 4 levels so we have sampled the function at least 10 times.
    // Otherwise, we could terminate prematurely and miss essential features.
    // This is of course possible anyway, but 10 samples seems to be a reasonable compromise.
    Real error = abs(I0 - I1);
    while (k < 4 || (k < max_refinements && error > tol*IL1) )
    {
        I0 = I1;
        IL0 = IL1;

        I1 = I0*half<Real>();
        IL1 = IL0*half<Real>();
        std::size_t p = static_cast<std::size_t>(1u) << k;
        h *= half<Real>();
        K sum = 0;
        Real absum = 0;

        for(std::size_t j = 1; j < p; j += 2)
        {
            K y = f(a + j*h);
            sum += y;
            absum += abs(y);
        }

        I1 += sum*h;
        IL1 += absum*h;
        ++k;
        error = abs(I0 - I1);
    }

    if (error_estimate)
    {
        *error_estimate = error;
    }

    if (L1)
    {
        *L1 = IL1;
    }

    return static_cast<K>(I1);
}
#if BOOST_WORKAROUND(BOOST_MSVC, < 1800)
// Template argument dedcution failure otherwise:
template<class F, class Real>
auto trapezoidal(F f, Real a, Real b, Real tol = 0, std::size_t max_refinements = 12, Real* error_estimate = 0, Real* L1 = 0)->decltype(std::declval<F>()(std::declval<Real>()))
#elif !defined(BOOST_NO_CXX11_NULLPTR)
template<class F, class Real>
auto trapezoidal(F f, Real a, Real b, Real tol = boost::math::tools::root_epsilon<Real>(), std::size_t max_refinements = 12, Real* error_estimate = nullptr, Real* L1 = nullptr)->decltype(std::declval<F>()(std::declval<Real>()))
#else
template<class F, class Real>
auto trapezoidal(F f, Real a, Real b, Real tol = boost::math::tools::root_epsilon<Real>(), std::size_t max_refinements = 12, Real* error_estimate = 0, Real* L1 = 0)->decltype(std::declval<F>()(std::declval<Real>()))
#endif
{
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1600)
   if (tol == 0)
      tol = boost::math::tools::root_epsilon<Real>();
#endif
   return trapezoidal(f, a, b, tol, max_refinements, error_estimate, L1, boost::math::policies::policy<>());
}

}}}
#endif


text:
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED
#define LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED

#include <luabind/config.hpp>
#include <luabind/detail/policy.hpp>
#include <boost/mpl/apply_wrap.hpp>

namespace luabind { namespace detail
{
	template<int N>
	struct char_array
	{
		char storage[N];
	};

#if defined(__GNUC__) && ( __GNUC__ == 3 && __GNUC_MINOR__ == 1 )

	template<class U>
	char_array<sizeof(U)> indirect_sizeof_test(by_reference<U>);

	template<class U>
	char_array<sizeof(U)> indirect_sizeof_test(by_const_reference<U>);

	template<class U>
	char_array<sizeof(U)> indirect_sizeof_test(by_pointer<U>);

	template<class U>
	char_array<sizeof(U)> indirect_sizeof_test(by_const_pointer<U>);

	template<class U>
	char_array<sizeof(U)> indirect_sizeof_test(by_value<U>);

#else

	template<class U>
	char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_reference<U>);

	template<class U>
	char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_const_reference<U>);

	template<class U>
	char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_pointer<U>);

	template<class U>
	char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_const_pointer<U>);

	template<class U>
	char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_value<U>);

#endif

	template<class T>
	struct indirect_sizeof
	{
		BOOST_STATIC_CONSTANT(int, value = sizeof(indirect_sizeof_test(LUABIND_DECORATE_TYPE(T))));
	};

	namespace mpl = boost::mpl;

	template<int Size, class Policies = detail::null_type>
	struct out_value_converter
	{
		template<class T>
		T& apply(lua_State* L, by_reference<T>, int index)
		{
			typedef typename find_conversion_policy<1, Policies>::type converter_policy;
			typename mpl::apply_wrap2<converter_policy,T,lua_to_cpp>::type converter;
			new (m_storage) T(converter.apply(L, LUABIND_DECORATE_TYPE(T), index));
			return *reinterpret_cast<T*>(m_storage);
		}

		template<class T>
		static int match(lua_State* L, by_reference<T>, int index)
		{
			typedef typename find_conversion_policy<1, Policies>::type converter_policy;
			typedef typename mpl::apply_wrap2<converter_policy,T,lua_to_cpp>::type converter;
			return converter::match(L, LUABIND_DECORATE_TYPE(T), index);
		}

		template<class T>
		void converter_postcall(lua_State* L, by_reference<T>, int)
		{
			typedef typename find_conversion_policy<2, Policies>::type converter_policy;
			typename mpl::apply_wrap2<converter_policy,T,cpp_to_lua>::type converter;
			converter.apply(L, *reinterpret_cast<T*>(m_storage));
			reinterpret_cast<T*>(m_storage)->~T();
		}

		template<class T>
		T* apply(lua_State* L, by_pointer<T>, int index)
		{
			typedef typename find_conversion_policy<1, Policies>::type converter_policy;
			typename mpl::apply_wrap2<converter_policy,T,lua_to_cpp>::type converter;
			new (m_storage) T(converter.apply(L, LUABIND_DECORATE_TYPE(T), index));
			return reinterpret_cast<T*>(m_storage);
		}

		template<class T>
		static int match(lua_State* L, by_pointer<T>, int index)
		{
			typedef typename find_conversion_policy<1, Policies>::type converter_policy;
			typedef typename mpl::apply_wrap2<converter_policy,T,lua_to_cpp>::type converter;
			return converter::match(L, LUABIND_DECORATE_TYPE(T), index);
		}

		template<class T>
		void converter_postcall(lua_State* L, by_pointer<T>, int)
		{
			typedef typename find_conversion_policy<2, Policies>::type converter_policy;
			typename mpl::apply_wrap2<converter_policy,T,cpp_to_lua>::type converter;
			converter.apply(L, *reinterpret_cast<T*>(m_storage));
			reinterpret_cast<T*>(m_storage)->~T();
		}

		char m_storage[Size];
	};

	template<int N, class Policies = detail::null_type>
	struct out_value_policy : conversion_policy<N>
	{
		static void precall(lua_State*, const index_map&) {}
		static void postcall(lua_State*, const index_map&) {}

		struct only_accepts_nonconst_references_or_pointers {};
		struct can_only_convert_from_lua_to_cpp {};

		template<class T, class Direction>
		struct apply
		{
			typedef typename boost::mpl::if_<boost::is_same<lua_to_cpp, Direction>
				, typename boost::mpl::if_<boost::mpl::or_<is_nonconst_reference<T>, is_nonconst_pointer<T> >
					, out_value_converter<indirect_sizeof<T>::value, Policies>
					, only_accepts_nonconst_references_or_pointers
					>::type
				, can_only_convert_from_lua_to_cpp
			>::type type;
		};
	};

	template<int Size, class Policies = detail::null_type>
	struct pure_out_value_converter
	{
		template<class T>
		T& apply(lua_State* L, by_reference<T>, int index)
		{
			new (m_storage) T();
			return *reinterpret_cast<T*>(m_storage);
		}

		template<class T>
		static int match(lua_State* L, by_reference<T>, int index)
		{
			return 0;
		}

		template<class T>
		void converter_postcall(lua_State* L, by_reference<T>, int)
		{
			typedef typename find_conversion_policy<1, Policies>::type converter_policy;
			typename mpl::apply_wrap2<converter_policy,T,cpp_to_lua>::type converter;
			converter.apply(L, *reinterpret_cast<T*>(m_storage));
			reinterpret_cast<T*>(m_storage)->~T();
		}

		template<class T>
		T* apply(lua_State* L, by_pointer<T>, int index)
		{
			new (m_storage) T();
			return reinterpret_cast<T*>(m_storage);
		}

		template<class T>
		static int match(lua_State* L, by_pointer<T>, int index)
		{
			return 0;
		}

		template<class T>
		void converter_postcall(lua_State* L, by_pointer<T>, int)
		{
			typedef typename find_conversion_policy<1, Policies>::type converter_policy;
			typename mpl::apply_wrap2<converter_policy,T,cpp_to_lua>::type converter;
			converter.apply(L, *reinterpret_cast<T*>(m_storage));
			reinterpret_cast<T*>(m_storage)->~T();
		}

		char m_storage[Size];
	};

	template<int N, class Policies = detail::null_type>
	struct pure_out_value_policy : conversion_policy<N, false>
	{
		static void precall(lua_State*, const index_map&) {}
		static void postcall(lua_State*, const index_map&) {}

		struct only_accepts_nonconst_references_or_pointers {};
		struct can_only_convert_from_lua_to_cpp {};

		template<class T, class Direction>
		struct apply
		{
			typedef typename boost::mpl::if_<boost::is_same<lua_to_cpp, Direction>
				, typename boost::mpl::if_<boost::mpl::or_<is_nonconst_reference<T>, is_nonconst_pointer<T> >
					, pure_out_value_converter<indirect_sizeof<T>::value, Policies>
					, only_accepts_nonconst_references_or_pointers
					>::type
				, can_only_convert_from_lua_to_cpp
			>::type type;
		};
	};

}}

namespace luabind
{
	template<int N>
	detail::policy_cons<detail::out_value_policy<N>, detail::null_type>
	out_value(LUABIND_PLACEHOLDER_ARG(N))
	{
		return detail::policy_cons<detail::out_value_policy<N>, detail::null_type>();
	}

	template<int N, class Policies>
	detail::policy_cons<detail::out_value_policy<N, Policies>, detail::null_type>
	out_value(LUABIND_PLACEHOLDER_ARG(N), const Policies&)
	{
		return detail::policy_cons<detail::out_value_policy<N, Policies>, detail::null_type>();
	}

	template<int N>
	detail::policy_cons<detail::pure_out_value_policy<N>, detail::null_type>
	pure_out_value(LUABIND_PLACEHOLDER_ARG(N))
	{
		return detail::policy_cons<detail::pure_out_value_policy<N>, detail::null_type>();
	}

	template<int N, class Policies>
	detail::policy_cons<detail::pure_out_value_policy<N, Policies>, detail::null_type>
	pure_out_value(LUABIND_PLACEHOLDER_ARG(N), const Policies&)
	{
		return detail::policy_cons<detail::pure_out_value_policy<N, Policies>, detail::null_type>();
	}
}

#endif // LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED

max_stars_repo_name: martinkro/gamedevelop-ai

max_issues_repo_name: martinkro/gamedevelop-ai

max_forks_repo_name: martinkro/gamedevelop-ai


text:
// Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#ifndef BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_COMPARABLE_HPP
#define BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_COMPARABLE_HPP

#include "matrix.hpp"

#include <boost/hana/all.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/eval_if.hpp>
#include <boost/hana/zip_with.hpp>

namespace boost { namespace hana {
    template <unsigned R1, unsigned C1, unsigned R2, unsigned C2>
    struct equal_impl<cppcon::Matrix<R1, C1>, cppcon::Matrix<R2, C2>> {
        template <typename M1, typename M2>
        static constexpr auto apply(M1 const& m1, M2 const& m2) {
            return eval_if(bool_c<R1 == R2 && C1 == C2>,
                [&](auto _) {
                    return all(zip_with(_(equal), cppcon::rows(m1),
                                                  cppcon::rows(m2)));
                },
                [] { return false_c; }
            );
        }
    };
}}

#endif // !BOOST_HANA_EXAMPLE_CPPCON_2014_MATRIX_COMPARABLE_HPP


text:
#include <Master.h>
#include <boost/test/auto_unit_test.hpp>
#include "ut_phases.hpp"
#include <iostream>

#if TEST_DECK_CONSTRUCTOR
BOOST_AUTO_TEST_CASE(constructor)
{
	Deck deck;
	BOOST_CHECK(deck.getCards().size() == 52);

	std::shared_ptr<card> testcard = std::make_shared<card>(ace, clubs);

	BOOST_CHECK(deck.getCards()[12] == *testcard);

	std::shared_ptr<card> testcard2 = std::make_shared<card>(ace, hearts);

	BOOST_CHECK(deck.getCards()[51] == *testcard2);
}
#endif
#if TEST_DECK_REMOVE
BOOST_AUTO_TEST_CASE(remove_card)
{
	Deck deck;
	BOOST_CHECK(deck.getCards().size() == 52);

	BOOST_CHECK(deck.removeCard(card(ace, spades)) == true);
	BOOST_CHECK(deck.removeCard(card(ace, hearts)) == true);
	BOOST_CHECK(deck.removeCard(card(ace, spades)) == false);
	BOOST_CHECK(deck.removeCard(card(ace, hearts)) == false);
	BOOST_CHECK(deck.getCards().size() == 50);
}
#endif
#if TEST_DECK_DRAW
BOOST_AUTO_TEST_CASE(draw_card)
{
	Deck deck;
	deck.shuffle();
	card x = deck.getCards()[0];
	card c = deck.draw();
	BOOST_CHECK(deck.getCards().size() == 51);
	BOOST_CHECK(x == c);
	BOOST_CHECK(x != deck.draw());
	BOOST_CHECK(deck.getCards().size() == 50);
}
#endif

max_stars_repo_name: brodiequinlan/MasterPoker

max_issues_repo_name: brodiequinlan/MasterPoker

max_forks_repo_name: brodiequinlan/MasterPoker


text:
// created by Mark O. Brown

#include "stdafx.h"
#include "PictureSettingsControl.h"

#include "Andor/AndorCameraCore.h"
#include "Andor/AndorCameraSettingsControl.h"
#include "PrimaryWindows/QtAndorWindow.h"
#include "ConfigurationSystems/ConfigSystem.h"

#include "Commctrl.h"
#include <boost/lexical_cast.hpp>

PictureSettingsControl::PictureSettingsControl()
{
}

void PictureSettingsControl::initialize( IChimeraQtWindow* parent ){
	// introducing things row by row
	/// Set Picture Options
	QVBoxLayout* layout = new QVBoxLayout(this);
	layout->setContentsMargins(0, 0, 0, 0);

	auto handleChange = [this, parent]() {
		try {
			if (parent->andorWin) {
				parent->andorWin->handlePictureSettings ();
			}
		}
		catch (ChimeraError& err){
			parent->reportErr (err.qtrace());
		}
	};

	QHBoxLayout* layout1 = new QHBoxLayout(this);
	layout1->setContentsMargins(0, 0, 0, 0);
	picScaleFactorLabel = new QLabel("Pic. Scale Factor:", parent);
	picScaleFactorEdit = new QLineEdit("50", parent);
	parent->connect(picScaleFactorEdit, &QLineEdit::textChanged, handleChange);

	transfModeLabel = new QLabel ("Qt Image Transformation Mode:", parent);
	transformationModeCombo = new CQComboBox (parent);
	transformationModeCombo->addItems ({ "Fast", "Smooth" });
	parent->connect (transformationModeCombo, qOverload<int> (&QComboBox::currentIndexChanged),
		parent->andorWin, &QtAndorWindow::handleTransformationModeChange);
	layout1->addWidget(picScaleFactorLabel, 0);
	layout1->addWidget(picScaleFactorEdit, 0);
	layout1->addWidget(transfModeLabel, 0);
	layout1->addWidget(transformationModeCombo, 1);

	QGridLayout* layout2 = new QGridLayout(this);
	layout2->setContentsMargins(0, 0, 0, 0);
	/// Picture Numbers
	pictureLabel = new QLabel ("Picture #:", parent);
	layout2->addWidget(pictureLabel, 0, 0);
	for ( auto picInc : range(4) ) {
		pictureNumbers[picInc] = new QLabel (cstr (picInc + 1), parent);
		layout2->addWidget(pictureNumbers[picInc], 0, picInc + 1);
	}
	/// Total picture number
	totalPicNumberLabel = new QLabel ("Total Picture #", parent);
	layout2->addWidget(pictureLabel, 1, 0);
	for (auto picInc : range (4)) {
		totalNumberChoice[picInc] = new CQRadioButton ("", parent);
		totalNumberChoice[picInc]->setChecked (picInc == 0);
		parent->connect (totalNumberChoice[picInc], &QRadioButton::toggled, handleChange);
		layout2->addWidget(totalNumberChoice[picInc], 1, picInc + 1);
	}
	/// Exposure Times
	exposureLabel = new QLabel ("Exposure (ms):", parent);
	layout2->addWidget(exposureLabel, 2, 0);
	for ( auto picInc : range(4) ) {
		exposureEdits[picInc] = new CQLineEdit (parent);
		parent->connect (exposureEdits[picInc], &QLineEdit::textChanged, handleChange);
		layout2->addWidget(exposureEdits[picInc], 2, picInc + 1);
	}
	setUnofficialExposures(std::vector<float>(4, 10 / 1000.0f));

	/// Thresholds
	thresholdLabel = new QLabel ("Threshold (cts)", parent);
	layout2->addWidget(thresholdLabel, 3, 0);
	for ( auto picInc : range(4) ) {
		thresholdEdits[picInc] = new CQLineEdit ("100", parent);
		parent->connect (thresholdEdits[picInc], &QLineEdit::textChanged, handleChange);
		currentPicSettings.thresholds[ picInc ] = { 100 };
		layout2->addWidget(thresholdEdits[picInc], 3, picInc + 1);
	}

	/// colormaps
	colormapLabel = new QLabel ("Colormap", parent);
	layout2->addWidget(colormapLabel, 4, 0);
	for ( auto picInc : range(4) ){
		colormapCombos[picInc] = new CQComboBox (parent);
		colormapCombos[picInc]->addItems ({ "Dark Viridis","Inferno","Black & White", "Red-Black-Blue" });
		parent->connect (colormapCombos[picInc], qOverload<int>(&QComboBox::activated), handleChange);
		colormapCombos[picInc]->setCurrentIndex( 0 );
		currentPicSettings.colors[picInc] = 0;
		layout2->addWidget(colormapCombos[picInc], 4, picInc + 1);
	}
	/// display types
	displayTypeLabel = new QLabel ("Display-Type:", parent);
	layout2->addWidget(displayTypeLabel, 5, 0);
	for ( auto picInc : range ( 4 ) ) {
		displayTypeCombos[picInc] = new CQComboBox (parent);
		displayTypeCombos[picInc]->addItems ({"Normal","Dif: 1", "Dif: 2", "Dif: 3", "Dif: 4"});
		parent->connect (displayTypeCombos[picInc], qOverload<int> (&QComboBox::activated), handleChange);
		displayTypeCombos[ picInc ]->setCurrentIndex ( 0 );
		currentPicSettings.colors[ picInc ] = 0;
		layout2->addWidget(displayTypeCombos[picInc], 5, picInc + 1);
	}
	/// software accumulation mode
	softwareAccumulationLabel = new QLabel ("Software Accum:", parent);
	layout2->addWidget(displayTypeLabel, 6, 0);
	for ( auto picInc : range ( 4 ) ) {
		softwareAccumulateAll[picInc] = new CQCheckBox("All?", parent);
		softwareAccumulateAll[ picInc ]->setChecked( 0 );
		parent->connect (softwareAccumulateAll[picInc], &QCheckBox::stateChanged, handleChange);
		softwareAccumulateNum[picInc] = new CQLineEdit ("1", parent);
		parent->connect (softwareAccumulateNum[picInc], &QLineEdit::textChanged, handleChange);
		QHBoxLayout* tmp = new QHBoxLayout(this);
		tmp->addWidget(softwareAccumulateAll[picInc], 0);
		tmp->addWidget(softwareAccumulateNum[picInc], 1);
		layout2->addLayout(tmp, 6, picInc + 1);
	}
	setPictureControlEnabled (0, true);
	setPictureControlEnabled (1, false);
	setPictureControlEnabled (2, false);
	setPictureControlEnabled (3, false);
	layout->addLayout(layout1);
	layout->addLayout(layout2);
}

std::array<displayTypeOption, 4> PictureSettingsControl::getDisplayTypeOptions( ){
	std::array<displayTypeOption, 4> options;
	unsigned counter = 0;
	for ( auto& combo : displayTypeCombos ){
		auto sel = combo->currentIndex( );
		if ( sel < 0 || sel > 4 ){
			thrower ( "Invalid selection in display type combo???" );
		}
		options[counter].isDiff = sel != 0;
		options[counter].whichPicForDif = sel;
		counter++;
	}
	return options;
}

std::array<std::string, 4> PictureSettingsControl::getThresholdStrings(){
	std::array<std::string, 4> res;
	// grab the thresholds
	for ( int thresholdInc = 0; thresholdInc < 4; thresholdInc++ ){
		auto& picThresholds = currentPicSettings.thresholds[ thresholdInc ];
		picThresholds.resize ( 1 );
		res[ thresholdInc ] = str(thresholdEdits[thresholdInc]->text ());
	}
	return res;
}

void PictureSettingsControl::handleSaveConfig(ConfigStream& saveFile){
	saveFile << "PICTURE_SETTINGS\n";
	saveFile << "/*Transformation Mode:*/ " << str (transformationModeCombo->currentText ());
	saveFile << "\n/*Color Options:*/ ";
	for (auto color : currentPicSettings.colors){
		saveFile << color << " ";
	}
	saveFile << "\n/*Threshold Settings:*/ ";
	for (auto threshold : getThresholdStrings() ){
		saveFile << threshold << " ";
	}
	saveFile << "\n/*Software Accumulation (accum all / Number)*/ ";
	for ( auto saOpt : getSoftwareAccumulationOptions ( ) ){
		saveFile << saOpt.accumAll << " " << saOpt.accumNum << " ";
	}
	saveFile << "\n/*Pic Scale Factor:*/\t" << str(picScaleFactorEdit->text());
	saveFile << "\nEND_PICTURE_SETTINGS\n";
}

andorPicSettingsGroup PictureSettingsControl::getPictureSettingsFromConfig (ConfigStream& configFile ){
	andorPicSettingsGroup fileSettings;
	std::string transformationMode;
	configFile >> fileSettings.tMode;
	for ( auto& color : fileSettings.colors ){
		configFile >> color;
	}
	for ( auto& threshold : fileSettings.thresholdStrs ){
		configFile >> threshold;
	}
	for ( auto& opt : fileSettings.saOpts ){
		configFile >> opt.accumAll >> opt.accumNum;
	}
	return fileSettings;
}

void PictureSettingsControl::handleOpenConfig(ConfigStream& openFile, AndorCameraCore* andor){
	ConfigSystem::checkDelimiterLine(openFile, "PICTURE_SETTINGS");
	auto settings = getPictureSettingsFromConfig ( openFile );
	updateAllSettings ( settings );
	ConfigSystem::checkDelimiterLine(openFile, "END_PICTURE_SETTINGS");
}

void PictureSettingsControl::setSoftwareAccumulationOptions ( std::array<softwareAccumulationOption, 4> opts ){
	for ( auto picInc : range ( 4 ) ) {
		softwareAccumulateAll[ picInc ]->setChecked ( opts[ picInc ].accumAll );
		softwareAccumulateNum[ picInc ]->setText ( cstr ( opts[ picInc ].accumNum ) );
	}
}

std::array<softwareAccumulationOption, 4> PictureSettingsControl::getSoftwareAccumulationOptions ( ){
	std::array<softwareAccumulationOption, 4> opts;
	for ( auto picInc : range(4)){
		opts[ picInc ].accumAll = softwareAccumulateAll[ picInc ]->isChecked ( );
		try{
			opts[ picInc ].accumNum  = boost::lexical_cast<unsigned>( str(softwareAccumulateNum[picInc]->text ()) );
		}
		catch ( boost::bad_lexical_cast& ){
			thrower ( "Failed to convert software accumulation number to an unsigned integer!" );
		}
	}
	return opts;
}

void PictureSettingsControl::setPictureControlEnabled (int pic, bool enabled){
	if (pic > 3){
		return;
	}
	if (!exposureEdits[pic] || !thresholdEdits[pic] || !colormapCombos[pic] || !displayTypeCombos[pic]
		|| !softwareAccumulateAll[pic] || !softwareAccumulateNum[pic]) {
		return;
	}
	exposureEdits[pic]->setEnabled(enabled);
	thresholdEdits[pic]->setEnabled (enabled);
	colormapCombos[pic]->setEnabled (enabled);
	displayTypeCombos[pic]->setEnabled (enabled);
	softwareAccumulateAll[pic]->setEnabled (enabled);
	softwareAccumulateNum[pic]->setEnabled (enabled);
}

unsigned PictureSettingsControl::getPicsPerRepetition(){
	unsigned which = 0, count=0;
	for ( auto& ctrl : totalNumberChoice ){
		count++;
		which = ctrl->isChecked ( ) ? count : which;
	}
	if ( which == 0 ){
		thrower ( "ERROR: failed to get pics per repetition?!?" );
	}
	return which;
}

void PictureSettingsControl::setUnofficialPicsPerRep( unsigned picNum ){
	if ( picNum < 1 || picNum > 4 ){
		thrower ( "Tried to set bad number of pics per rep: " + str ( picNum ) );
	}
	unofficialPicsPerRep = picNum;
	unsigned count = 0;
	for (auto& totalNumRadio : totalNumberChoice){
		count++;
		totalNumRadio->setChecked (count == unofficialPicsPerRep);
		setPictureControlEnabled (count-1, count <= unofficialPicsPerRep);
	}
}

void PictureSettingsControl::handleOptionChange( ){
	for (auto radioInc : range(totalNumberChoice.size())){
		if (totalNumberChoice[radioInc]->isChecked()){
			setUnofficialPicsPerRep( radioInc + 1 );
		}
	}
}

std::array<float, 4> PictureSettingsControl::getExposureTimes ( ){
	std::array<float, 4> times;
	for ( auto ctrlNum : range(exposureEdits.size()) ){
		auto& ctrl = exposureEdits[ ctrlNum ];
		if (!ctrl) {
			return times;
		}
		try	{
			times[ctrlNum] = ctrl->text ().toDouble ()*1e-3;
			//times[ ctrlNum ] = boost::lexical_cast<double>( str(ctrl->text ()) ) * 1e-3;
		}
		catch ( boost::bad_lexical_cast& ){
			thrower ( "Failed to convert exposure time to a float!" );
		}
	}
	return times;
}

std::vector<float> PictureSettingsControl::getUsedExposureTimes() {
	updateSettings( );
	auto allTimes = getExposureTimes();
	std::vector<float> usedTimes(std::begin(allTimes), std::end(allTimes));
	usedTimes.resize ( getPicsPerRepetition ( ));
	return usedTimes;
}

void PictureSettingsControl::setThresholds( std::array<std::string, 4> newThresholds){
	for (unsigned thresholdInc = 0; thresholdInc < newThresholds.size(); thresholdInc++){
		thresholdEdits[thresholdInc]->setText(newThresholds[thresholdInc].c_str());
	}
}

std::array<int, 4> PictureSettingsControl::getPictureColors(){
	updateSettings ( );
	return currentPicSettings.colors;
}

void PictureSettingsControl::updateColormaps ( std::array<int, 4> colorIndexes ){
	currentPicSettings.colors = colorIndexes;
	for ( auto picInc : range(4) ){
		colormapCombos[ picInc ]->setCurrentIndex ( currentPicSettings.colors[ picInc ] );
	}
}

void PictureSettingsControl::setUnofficialExposures ( std::vector<float> times ){
	unsigned count = 0;
	for ( auto ti : times ){
		exposureEdits[ count++ ]->setText ( cstr ( ti*1e3,5) );
	}
}

void PictureSettingsControl::updateAllSettings ( andorPicSettingsGroup inputSettings ) {
	updateColormaps ( inputSettings.colors );
	setThresholds ( inputSettings.thresholdStrs );
	setSoftwareAccumulationOptions ( inputSettings.saOpts );
	if (inputSettings.tMode == "Fast") {
		transformationModeCombo->setCurrentIndex (0);
	}
	else {
		transformationModeCombo->setCurrentIndex (1);
	}
	picScaleFactorEdit->setText(qstr(inputSettings.picScaleFactor));
}

std::array<std::vector<int>, 4> PictureSettingsControl::getThresholds ( ){
	updateSettings ( );
	return currentPicSettings.thresholds;
}

void PictureSettingsControl::updateSettings( ){
	// grab the thresholds
	for (auto thresholdInc : range(4) ){
		if (!thresholdEdits[thresholdInc]) {
			return;
		}
		auto& picThresholds = currentPicSettings.thresholds[ thresholdInc ];
		picThresholds.resize ( 1 );
		int threshold;

		try{
			QString txt = thresholdEdits[thresholdInc]->text ();
			threshold = txt.toInt ();
			picThresholds[0] = threshold;
		}
		catch ( boost::bad_lexical_cast& ){
			picThresholds.clear ( );
			// assume it's a file location.
			std::ifstream thresholdFile;
			thresholdFile.open ( str(thresholdEdits[thresholdInc]->text ()).c_str() );
			if ( !thresholdFile.is_open ( ) ){
				thrower  ( "ERROR: failed to convert threshold number " + str ( thresholdInc + 1 ) + " to an integer, "
						 "and it wasn't the address of a threshold-file." );
			}
			while ( true ){
				double indv_file_threshold;
				thresholdFile >> indv_file_threshold;
				if ( thresholdFile.eof ( ) ) { break; }
				picThresholds.push_back ( indv_file_threshold );
			}
		}
	}
	for (auto colorInc : range (4)) {
		currentPicSettings.colors[colorInc] = colormapCombos[colorInc]->currentIndex();
	}
}

Qt::TransformationMode PictureSettingsControl::getTransformationMode (){
	if (transformationModeCombo->currentText () == "Fast") {
		return Qt::TransformationMode::FastTransformation;
	}
	else {
		return Qt::TransformationMode::SmoothTransformation;
	}
}

void PictureSettingsControl::setEnabledStatus (bool viewRunningSettings) {
	if (viewRunningSettings) {
		for (auto num : range (4)) {
			totalNumberChoice[num]->setEnabled (false);
			exposureEdits[num]->setEnabled (false);
			thresholdEdits[num]->setEnabled (false);
			colormapCombos[num]->setEnabled (false);
			displayTypeCombos[num]->setEnabled (false);
			softwareAccumulateAll[num]->setEnabled (false);
			softwareAccumulateNum[num]->setEnabled (false);
		}
	}
	else {
		for (auto num : range (4)) {
			totalNumberChoice[num]->setEnabled (true);
		}
		setUnofficialPicsPerRep (unofficialPicsPerRep);
	}
}

int PictureSettingsControl::getPicScaleFactor() {
	try {
		return boost::lexical_cast<int>(str(picScaleFactorEdit->text()));
	}
	catch (boost::bad_lexical_cast& err) {
		thrower("Failed to convert picture scale factor to integer!");
	}
}

max_stars_repo_name: zzpwahaha/Chimera-Control-Trim

max_issues_repo_name: zzpwahaha/Chimera-Control-Trim

max_forks_repo_name: zzpwahaha/Chimera-Control-Trim


text:
/* (c) 2016, 2021 FFF Services. For details refers to LICENSE.txt */
#pragma once

#include <graphene/chain/protocol/types.hpp>
#include <graphene/db/object.hpp>
#include <graphene/db/generic_index.hpp>

#include <fc/reflect/reflect.hpp>
#include <fc/time.hpp>

#include <boost/multi_index/composite_key.hpp>

namespace graphene { namespace chain {

   /// Tracks subscription rom consumer to author
   class subscription_object : public graphene::db::abstract_object<implementation_ids, impl_subscription_object_type, subscription_object>
   {
   public:
      account_id_type from;
      account_id_type to;
      fc::time_point_sec expiration;
      bool automatic_renewal;
   };

   struct by_from;
   struct by_to;
   struct by_expiration;
   struct by_from_to;
   struct by_from_expiration;
   struct by_to_expiration;
   struct by_renewal;
   struct by_to_renewal;

   typedef boost::multi_index_container<
      subscription_object,
      db::mi::indexed_by<
         db::object_id_index,
         db::mi::ordered_non_unique<db::mi::tag<by_from>,
            db::mi::member<subscription_object, account_id_type, &subscription_object::from>
         >,
         db::mi::ordered_non_unique<db::mi::tag<by_to>,
            db::mi::member<subscription_object, account_id_type, &subscription_object::to>
         >,
         db::mi::ordered_non_unique<db::mi::tag<by_expiration>,
            db::mi::member<subscription_object, fc::time_point_sec, &subscription_object::expiration>, std::greater<fc::time_point_sec>
         >,
         db::mi::ordered_unique<db::mi::tag<by_from_to>,
            db::mi::composite_key<subscription_object,
               db::mi::member<subscription_object, account_id_type, &subscription_object::from>,
               db::mi::member<subscription_object, account_id_type, &subscription_object::to>
            >
         >,
         db::mi::ordered_non_unique<db::mi::tag<by_from_expiration>,
            db::mi::composite_key<subscription_object,
               db::mi::member<subscription_object, account_id_type, &subscription_object::from>,
               db::mi::member<subscription_object, fc::time_point_sec, &subscription_object::expiration>
            >,
            db::mi::composite_key_compare<
               std::less<account_id_type>,
               std::greater<fc::time_point_sec>
            >
         >,
         db::mi::ordered_non_unique<db::mi::tag<by_to_expiration>,
            db::mi::composite_key<subscription_object,
               db::mi::member<subscription_object, account_id_type, &subscription_object::to>,
               db::mi::member<subscription_object, fc::time_point_sec, &subscription_object::expiration>
            >,
            db::mi::composite_key_compare<
               std::less<account_id_type>,
                 std::greater<fc::time_point_sec>
               >
         >,
         db::mi::ordered_non_unique<db::mi::tag<by_renewal>,
            db::mi::member<subscription_object, bool, &subscription_object::automatic_renewal>, std::greater<bool>
         >,
         db::mi::ordered_non_unique<db::mi::tag<by_to_renewal>,
            db::mi::composite_key<subscription_object,
               db::mi::member<subscription_object, account_id_type, &subscription_object::to>,
               db::mi::member<subscription_object, bool, &subscription_object::automatic_renewal>
            >
         >
      >
   >subscription_object_multi_index_type;

typedef graphene::db::generic_index< subscription_object, subscription_object_multi_index_type > subscription_index;

} } // graphene::chain

FC_REFLECT_DERIVED(graphene::chain::subscription_object, (graphene::db::object), (from)(to)(expiration)(automatic_renewal) )


text:
//
// Created by Necip Fazil Yildiran on 06/18/19.
//
#ifndef _OPENGR_IO_HPP_
#define _OPENGR_IO_HPP_

#include <Eigen/Geometry>

#include <string>
#include <iterator>

#ifdef USE_BOOST
#include <boost/filesystem.hpp>
#endif

#define LINE_BUF_SIZE 100

using namespace std;
using namespace gr;

////////////////////////////////////////////////////////////////////////////////
/// Write
////////////////////////////////////////////////////////////////////////////////
template<typename PointRange,
         typename TextCoordRange,
         typename NormalRange,
         typename TrisRange,
         typename MTLSRange>
bool IOManager::WriteObject(
  const char *name,
  const PointRange &v,
  const TextCoordRange &tex_coords,
  const NormalRange &normals,
  const TrisRange &tris,
  const MTLSRange &mtls)
{
  std::string filename (name);

  bool haveExt = filename.at(filename.size()-4) == '.';

  if (tris.size() == 0){
    return WritePly(haveExt ?
                    filename.substr(0,filename.size()-3).append("ply") :
                    filename.append(".ply"),
                    v, normals);
  }
  else{
    return WriteObj(haveExt ?
                    filename.substr(0,filename.size()-3).append("obj") :
                    filename.append(".obj"),
                    v,
                    tex_coords,
                    normals,
                    tris,
                    mtls);
  }
}

template<typename PointRange, typename NormalRange>
bool
IOManager::WritePly(
  std::string filename,
  const PointRange &v,
  const NormalRange &normals)
{
  std::ofstream plyFile;
  plyFile.open (filename.c_str(), std::ios::out |  std::ios::trunc | std::ios::binary);
  if (! plyFile.is_open()){
    std::cerr << "Cannot open file to write!" << std::endl;
    return false;
  }

  bool useNormals = normals.size() == v.size();
  // we check if we have colors by looking if the first rgb vector is void
  auto has_color = [](const typename PointRange::value_type& p ) {
    using Scalar = typename PointRange::value_type::Scalar;
    return p.rgb().squaredNorm() > Scalar(0.001);
  };
  bool useColors = false;
  for(const auto& p : v)
  {
    if( has_color(p) )
    {
      useColors = true;
      break;
    }
  }

  plyFile.imbue(std::locale::classic());

  // Write Header
  plyFile << "ply" << std::endl;
  plyFile << "format binary_little_endian 1.0" << std::endl;
  plyFile << "comment Super4PCS output file" << std::endl;
  plyFile << "element vertex " << v.size() << std::endl;
  plyFile << "property float x" << std::endl;
  plyFile << "property float y" << std::endl;
  plyFile << "property float z" << std::endl;

  if(useNormals) {
    plyFile << "property float nx" << std::endl;
    plyFile << "property float ny" << std::endl;
    plyFile << "property float nz" << std::endl;
  }

  if(useColors) {
    plyFile << "property uchar red" << std::endl;
    plyFile << "property uchar green" << std::endl;
    plyFile << "property uchar blue" << std::endl;
  }

  plyFile << "end_header" << std::endl;

  // Read all elements in data, correct their depth and print them in the file
  char tmpChar;
  float tmpFloat;
  typename NormalRange::const_iterator normal_it = normals.cbegin();
  for(const auto& p : v)
  {
    tmpFloat = static_cast<float>(p.pos()(0));
    plyFile.write(reinterpret_cast<const char*>(&tmpFloat),sizeof(float));
    tmpFloat = static_cast<float>(p.pos()(1));
    plyFile.write(reinterpret_cast<const char*>(&tmpFloat),sizeof(float));
    tmpFloat = static_cast<float>(p.pos()(2));
    plyFile.write(reinterpret_cast<const char*>(&tmpFloat),sizeof(float));

    if(useNormals) // size check is done earlier
    {
      plyFile.write(reinterpret_cast<const char*>( &(*normal_it)(0) ),sizeof(float));
      plyFile.write(reinterpret_cast<const char*>( &(*normal_it)(1) ),sizeof(float));
      plyFile.write(reinterpret_cast<const char*>( &(*normal_it)(2) ),sizeof(float));
      ++normal_it;
    }

    if(useColors)
    {
      tmpChar = static_cast<char>( p.rgb()(0) );
      plyFile.write(reinterpret_cast<const char*>(&tmpChar),sizeof(char));
      tmpChar = static_cast<char>( p.rgb()(1) );
      plyFile.write(reinterpret_cast<const char*>(&tmpChar),sizeof(char));
      tmpChar = static_cast<char>( p.rgb()(2) );
      plyFile.write(reinterpret_cast<const char*>(&tmpChar),sizeof(char));

    }
  }

  plyFile.close();

  return true;
}

template<typename PointRange,
         typename TexCoordRange,
         typename NormalRange,
         typename TrisRange,
         typename MTLSRange>
bool
IOManager::WriteObj(std::string filename,
         const PointRange &v,
         const TexCoordRange &tex_coords,
         const NormalRange &normals,
         const TrisRange &tris,
         const MTLSRange &mtls)
{
  std::fstream f(filename.c_str(), std::ios::out);
  if (!f || f.fail()) return false;
  size_t i;

  for(const auto& m : mtls)
  {
    f << "mtllib " << m << std::endl;
  }

  for(const auto& p : v)
  {
    f << "v "
      << p.pos()(0) << " " << p.pos()(1) << " " << p.pos()(2) << " ";

    if (p.rgb()(0) != 0) // TODO: What about hasColor?
      f << p.rgb()(0) << " " << p.rgb()(1) << " " << p.rgb()(2);

    f << std::endl;
  }

  for(const auto& n : normals)
  {
    f << "vn " << n(0) << " " << n(1) << " " << n(2)
      << std::endl;
  }

  for(const auto& t : tex_coords)
  {
    f << "vt " << t(0) << " " << t(1) << std::endl;
  }

  auto is_normals_empty = [&]() { return normals.begin() == normals.end(); };
  auto is_texcoords_empty = [&]() { return tex_coords.begin() == tex_coords.end(); };

  for(const auto& t : tris)
  {
    if(is_normals_empty() && is_texcoords_empty())
      f << "f " << t.a << " " << t.b << " " << t.c << std::endl;
    else if(!is_texcoords_empty())
      f << "f " << t.a << "/" << t.t1 << " " << t.b << "/"
        << t.t2 << " " << t.c << "/" << t.t3 << std::endl;
    else
      f << "f " << t.a << "/" << t.n1 << " " << t.b << "/"
        << t.n2 << " " << t.c << "/" << t.n3 << std::endl;
  }

  f.close();

  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// Read
////////////////////////////////////////////////////////////////////////////////
template<typename Scalar>
bool
IOManager::ReadObject(const char *name,
           vector<Point3D<Scalar> > &v,
           vector<Eigen::Matrix2f> &tex_coords,
           vector<typename Point3D<Scalar>::VectorType> &normals,
           vector<tripple> &tris,
           vector<std::string> &mtls){
  string filename (name);

  if (filename.length() < 4) return false;

  string ext = filename.substr(filename.size()-3);

  if ( ext.compare ("ply") == 0 )
    return ReadPly<Scalar> (name, v, normals);
  if ( ext.compare ("obj") == 0 )
    return ReadObj<Scalar> (name, v, tex_coords, normals, tris, mtls);
  if ( ext.compare ("ptx") == 0 )
    return ReadPtx<Scalar> (name, v);

  std::cerr << "Unsupported file format" << std::endl;
  return false;
}

template<typename Scalar>
bool IOManager::ReadPtx(const char *filename, vector<Point3D<Scalar> > &vertex)
{
    fstream f(filename, ios::in);
    if (!f || f.fail()) {
        cerr << "(PTX) error opening file" << endl;
        return false;
    }

    int numOfVertices;
    int rows, cols;
    char line[LINE_BUF_SIZE];

    {
        f.getline(line,LINE_BUF_SIZE);
        std::stringstream ss(line); ss >> cols;
    }
    {
        f.getline(line,LINE_BUF_SIZE);
        std::stringstream ss(line); ss >> rows;
    }

    numOfVertices = cols*rows;

    // skip matrices declaration
    for(int i=0; i<8; i++) f.getline(line,LINE_BUF_SIZE);

    Point3D<Scalar> ptx;
    float intensity;
    typename Point3D<Scalar>::VectorType rgb;

    vertex.clear();
    vertex.reserve(numOfVertices);

    for (int i = 0; i < numOfVertices && ! f.eof(); i++) {
        f.getline(line,LINE_BUF_SIZE);
        std::stringstream ss(line);

        ss >> ptx.x();
        ss >> ptx.y();
        ss >> ptx.z();
        ss >> intensity;
        ss >> rgb(0);
        ss >> rgb(1);
        ss >> rgb(2);

        ptx.set_rgb(rgb);

        vertex.push_back( ptx );
    }

    f.close();

    return vertex.size() == numOfVertices;
}

template<typename Scalar>
bool
IOManager::ReadObj(const char *filename,
                   vector<Point3D<Scalar> > &v,
                   vector<Eigen::Matrix2f> &tex_coords,
                   vector<typename Point3D<Scalar>::VectorType> &normals,
                   vector<tripple> &tris,
                   vector<std::string> &mtls)
{

#ifdef USE_BOOST
    using namespace boost;
    const string workingDir = filesystem::path(filename).parent_path().native()
            + filesystem::path::preferred_separator;
#endif

  fstream f(filename, ios::in);
  if (!f || f.fail()) return false;
  char str[1024];
  float x, y, z;
  v.clear();
  tris.clear();
  while (!f.eof()) {
    f.getline(str, 1023);
    char ch[128];
    sscanf(str, "%s %*s", ch);
    if (strcmp(ch, "v") == 0) {
      sscanf(str, "%s %f %f %f", ch, &x, &y, &z);
      v.emplace_back(x, y, z);
      v[v.size() - 1].set_rgb(Point3D<Scalar>::VectorType::Zero());
    } else if (strcmp(ch, "vt") == 0) {
      Eigen::Matrix2f tex_coord;
      sscanf(str, "%s %f %f", ch, &tex_coord.coeffRef(0), &tex_coord.coeffRef(1));
      tex_coords.push_back(tex_coord);
    } else if (strcmp(ch, "vn") == 0) {
      typename Point3D<Scalar>::VectorType normal;
      sscanf(str, "%s %f %f %f", ch, &x, &y, &z);
      normal << x, y, z;
      normals.push_back(normal);
    } else if (strcmp(ch, "f") == 0) {
      tripple triangle;
      if (normals.size() && !tex_coords.size()) {
        sscanf(str, "%s %d//%d %d//%d %d//%d", ch, &(triangle.a),
               &(triangle.n1), &(triangle.b), &(triangle.n2), &(triangle.c),
               &(triangle.n3));
      } else if (normals.size() && tex_coords.size()) {
        sscanf(str, "%s %d/%d/%d %d/%d/%d %d/%d/%d", ch, &(triangle.a),
               &(triangle.t1), &(triangle.n1), &(triangle.b), &(triangle.t2),
               &(triangle.n2), &(triangle.c), &(triangle.t3), &(triangle.n3));
      } else if (!normals.size() && tex_coords.size()) {
        sscanf(str, "%s %d/%d %d/%d %d/%d", ch, &(triangle.a), &(triangle.t1),
               &(triangle.b), &(triangle.t2), &(triangle.c), &(triangle.t3));
      } else if (!normals.size() && !tex_coords.size()) {
        sscanf(str, "%s %d %d %d", ch, &(triangle.a), &(triangle.b),
               &(triangle.c));
      }
      tris.push_back(triangle);
      if (normals.size()) {
        v[triangle.a - 1].set_normal(normals[triangle.n1 - 1]);
        v[triangle.b - 1].set_normal(normals[triangle.n2 - 1]);
        v[triangle.c - 1].set_normal(normals[triangle.n3 - 1]);
      }
    } else if (strcmp(ch, "mtllib") == 0) {
#ifdef USE_BOOST
        mtls.push_back(workingDir + std::string (str + 7));
#else
        std::cerr << "Skipping MTL (Boost disabled)" << std::endl;
#endif
    }
  }
  f.close();

  if(tris.size() == 0){
    // In case we have vertex and normal lists but no face, assign normal to v
    if(v.size() == normals.size()){
      for (size_t i = 0; i < v.size(); ++i)
        v[i].set_normal(normals[i]);
    }
  }else {
    if (! normals.empty()){
      // If we have normals from faces, we must rebuild the normal array to duplicate
      // original normals and get a 1 to 1 correspondances with vertices
      // We assume that the normals have already been sent to vertices
      normals.clear();
      normals.reserve(v.size());

      for (unsigned int i = 0; i!= v.size(); i++)
        normals.push_back(v[i].normal());
    }
  }

#ifdef USE_BOOST
  if (mtls.size()) {
    f.open(mtls[0].c_str(), ios::in);
    while (f && !f.fail()) {
      std::string img_name, dummy;
      f >> dummy;
      if (strcmp(dummy.c_str(), "map_Kd") == 0) {
        f >> img_name;

        // ... x = width, y = height, n = # 8-bit components per pixel ...
        int width,height,n;
        unsigned char *data = stbi_load_((workingDir + img_name).c_str(), &width, &height, &n, STBI_rgb);

        if (data != nullptr) {
            for (int i = 0; i < tris.size(); ++i) {
              const tripple &t = tris[i];
              Eigen::Matrix2f tc1 = tex_coords[t.t1 - 1];
              Eigen::Matrix2f tc2 = tex_coords[t.t2 - 1];
              Eigen::Matrix2f tc3 = tex_coords[t.t3 - 1];
              if ((tc1.array() < 1.0 && tc1.array() > 1.0 ).all() &&
                  (tc2.array() < 1.0 && tc2.array() > 1.0 ).all() &&
                  (tc3.array() < 1.0 && tc3.array() > 1.0 ).all()) {
              }
              auto setcolor = [data, width, height](Point3D<Scalar>& p, float u, float v) {
                  //using Scalar = typename Point3D<Scalar>::Scalar; // Scalar is already defined
                  unsigned char *ptr = (data + int(STBI_rgb) * int(v * height * width +  u * width));
                  int r = ptr[0];
                  int g = ptr[1];
                  int b = ptr[2];
                  p.set_rgb(Eigen::Matrix<int, 3, 1>(r,g,b).cast<Scalar>());
              };

              setcolor( v[t.a - 1], tc1.coeffRef(0), tc1.coeffRef(1) );
              setcolor( v[t.b - 1], tc2.coeffRef(0), tc2.coeffRef(1) );
              setcolor( v[t.c - 1], tc3.coeffRef(0), tc3.coeffRef(1) );
            }
            stbi_image_free_(data);
        } else {
            std::cerr << "Image loading failed: "
                      << stbi_failure_reason_() << "\n"
                      << "Path: " << workingDir + img_name
                      << std::endl;
        }
      }
    }
  }
#endif
  f.close();

  if (v.size() == 0) return false;
  return true;
}

#endif

max_stars_repo_name: sgiraudot/OpenGR

max_issues_repo_name: sgiraudot/OpenGR

max_forks_repo_name: sgiraudot/OpenGR


text:
/*
 * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbSarImageMetadataInterface.h"
#include "otbRadarsat2ImageMetadataInterface.h"
#include "otbSARMetadata.h"

#include "otbMacro.h"
#include "itkMetaDataObject.h"
#include "otbImageKeywordlist.h"

// useful constants
#include <otbMath.h>
#include "otbXMLMetadataSupplier.h"
#include <boost/filesystem.hpp>

namespace otb
{

Radarsat2ImageMetadataInterface::Radarsat2ImageMetadataInterface()
{
}

bool Radarsat2ImageMetadataInterface::CanRead() const
{
  std::string sensorID = GetSensorID();

  if (sensorID.find("RADARSAT-2") != std::string::npos)
  {
    return true;
  }
  else
    return false;
}

void Radarsat2ImageMetadataInterface::CreateCalibrationLookupData(const short type)
{
  std::string lut = "SigmaNought";

  switch (type)
  {
  case SarCalibrationLookupData::BETA:
  {
    lut = "BetaNought";
  }
  break;

  case SarCalibrationLookupData::GAMMA:
  {
    lut = "GammaNought";
  }
  break;

  case SarCalibrationLookupData::DN:
  {
    lut = "DN";
  }
  break;

  case SarCalibrationLookupData::SIGMA:
  default:
  {
    lut = "SigmaNought";
  }
  break;
  }

  const ImageKeywordlistType imageKeywordlist = this->GetImageKeywordlist();
  const std::string          key              = "referenceNoiseLevel[" + lut + "].gain";

  Radarsat2CalibrationLookupData::GainListType glist;
  int                                          offset = 0;

  Utils::ConvertStringToVector(imageKeywordlist.GetMetadataByKey("referenceNoiseLevel[" + lut + "].gain"), glist, "referenceNoiseLevel[" + lut + "].gain");

  Utils::LexicalCast<int>(imageKeywordlist.GetMetadataByKey("referenceNoiseLevel[" + lut + "].offset"), "referenceNoiseLevel[" + lut + "].offset");

  Radarsat2CalibrationLookupData::Pointer sarLut;
  sarLut = Radarsat2CalibrationLookupData::New();
  sarLut->InitParameters(type, offset, glist);
  this->SetCalibrationLookupData(sarLut);
}

void Radarsat2ImageMetadataInterface::ParseDateTime(const char* key, std::vector<int>& dateFields) const
{
  if (dateFields.size() < 1)
  {
    // parse from keyword list
    if (!this->CanRead())
    {
      itkExceptionMacro(<< "Invalid Metadata, not a valid product");
    }

    const ImageKeywordlistType imageKeywordlist = this->GetImageKeywordlist();
    if (!imageKeywordlist.HasKey(key))
    {
      itkExceptionMacro(<< "no key named '" << key << "'");
    }

    std::string date_time_str = imageKeywordlist.GetMetadataByKey(key);
    date_time_str.resize(date_time_str.size() - 1);
    Utils::ConvertStringToVector(date_time_str, dateFields, key, "-T:.");
  }
}

int Radarsat2ImageMetadataInterface::GetYear() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if (m_AcquisitionDateFields.size() > 0)
  {
    value = Utils::LexicalCast<int>(m_AcquisitionDateFields[0], "support_data.image_date(year)");
  }
  return value;
}

int Radarsat2ImageMetadataInterface::GetMonth() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if (m_AcquisitionDateFields.size() > 1)
  {
    value = Utils::LexicalCast<int>(m_AcquisitionDateFields[1], "support_data.image_date(month)");
  }
  return value;
}

int Radarsat2ImageMetadataInterface::GetDay() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if (m_AcquisitionDateFields.size() > 2)
  {
    value = Utils::LexicalCast<int>(m_AcquisitionDateFields[2], "support_data.image_date(day)");
  }
  return value;
}

int Radarsat2ImageMetadataInterface::GetHour() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if (m_AcquisitionDateFields.size() > 3)
  {
    value = Utils::LexicalCast<int>(m_AcquisitionDateFields[3], "support_data.image_date(hour)");
  }
  return value;
}

int Radarsat2ImageMetadataInterface::GetMinute() const
{
  int value = 0;
  ParseDateTime("support_data.image_date", m_AcquisitionDateFields);
  if (m_AcquisitionDateFields.size() > 4)
  {
    value = Utils::LexicalCast<int>(m_AcquisitionDateFields[4], "support_data.image_date(minute)");
  }
  return value;
}

int Radarsat2ImageMetadataInterface::GetProductionYear() const
{
  int value = 0;
  ParseDateTime("support_data.date", m_ProductionDateFields);
  if (m_ProductionDateFields.size() > 0)
  {
    value = Utils::LexicalCast<int>(m_ProductionDateFields[0], "support_data.image_date(year)");
  }
  return value;
}

int Radarsat2ImageMetadataInterface::GetProductionMonth() const
{
  int value = 0;
  ParseDateTime("support_data.date", m_ProductionDateFields);
  if (m_ProductionDateFields.size() > 1)
  {
    value = Utils::LexicalCast<int>(m_ProductionDateFields[1], "support_data.image_date(production month)");
  }
  return value;
}

int Radarsat2ImageMetadataInterface::GetProductionDay() const
{
  int value = 0;
  ParseDateTime("support_data.date", m_ProductionDateFields);
  if (m_ProductionDateFields.size() > 2)
  {
    value = Utils::LexicalCast<int>(m_ProductionDateFields[2], "support_data.image_date(production day)");
  }
  return value;
}

double Radarsat2ImageMetadataInterface::GetPRF() const
{
  return 0;
}

double Radarsat2ImageMetadataInterface::GetRSF() const
{
  return 0;
}

double Radarsat2ImageMetadataInterface::GetRadarFrequency() const
{
  return 0;
}

double Radarsat2ImageMetadataInterface::GetCenterIncidenceAngle() const
{
  return 0;
}

Radarsat2ImageMetadataInterface::UIntVectorType Radarsat2ImageMetadataInterface::GetDefaultDisplay() const
{
  UIntVectorType rgb(3);
  rgb[0] = 0;
  rgb[1] = 0;
  rgb[2] = 0;
  return rgb;
}

//"

void Radarsat2ImageMetadataInterface::ParseGdal(const MetadataSupplierInterface & mds)
{
  // Metadata read by GDAL
  Fetch(MDTime::AcquisitionStartTime, mds, "ACQUISITION_START_TIME");
  // Fetch(MDTime::AcquisitionStopTime, mds, "PROCESSING_TIME");
  Fetch(MDStr::BeamMode, mds, "BEAM_MODE");
  Fetch("FACILITY_IDENTIFIER", mds, "FACILITY_IDENTIFIER");
  Fetch(MDNum::LineSpacing, mds, "LINE_SPACING");
  Fetch(MDNum::PixelSpacing, mds, "PIXEL_SPACING");
  // Fetch(MDStr::Mode, mds, "MODE");
  Fetch(MDStr::OrbitDirection, mds, "ORBIT_DIRECTION");
  // Fetch(MDNum::OrbitNumber, mds, "ORBIT_NUMBER");
  Fetch(MDStr::ProductType, mds, "PRODUCT_TYPE");
  Fetch(MDStr::Instrument, mds, "SATELLITE_IDENTIFIER");
  Fetch(MDStr::SensorID, mds, "SENSOR_IDENTIFIER");

  // Product file
  std::string ProductFilePath = mds.GetResourceFile("product.xml");
  if (!ProductFilePath.empty())
    {
    XMLMetadataSupplier ProductMS(ProductFilePath);
    m_Imd.Add(MDStr::Mission, ProductMS.GetAs<std::string>("product.sourceAttributes.satellite"));

    m_Imd.Add(MDNum::NumberOfLines, ProductMS.GetAs<int>("product.imageAttributes.rasterAttributes.numberOfLines"));
    m_Imd.Add(MDNum::NumberOfColumns, ProductMS.GetAs<int>("product.imageAttributes.rasterAttributes.numberOfSamplesPerLine"));
    m_Imd.Add(MDTime::ProductionDate,
        ProductMS.GetFirstAs<MetaData::Time>("product.imageGenerationParameters.generalProcessingInformation.processingTime"));
    // m_Imd.Add(MDNum::RadarFrequency, ProductMS.GetAs<double>("product.sourceAttributes.radarParameters.radarCenterFrequency"));
    m_Imd.Add(MDNum::AverageSceneHeight, ProductMS.GetAs<double>("product.imageAttributes.geographicInformation.referenceEllipsoidParameters.geodeticTerrainHeight"));

    m_Imd.Add(MDNum::RadarFrequency, this->GetRadarFrequency());
    m_Imd.Add(MDNum::PRF, this->GetPRF());
    m_Imd.Add(MDNum::RSF, this->GetRSF());
    m_Imd.Add(MDNum::CenterIncidenceAngle, this->GetCenterIncidenceAngle());

    assert(mds.GetNbBands() == this->m_Imd.Bands.size());

    SARParam sarParam;
    for (int bandId = 0 ; bandId < mds.GetNbBands() ; ++bandId)
      {
      Fetch(MDStr::Polarization, mds, "POLARIMETRIC_INTERP", bandId);
      m_Imd.Bands[bandId].Add(MDGeom::SAR, sarParam);
      }
    }
}

void Radarsat2ImageMetadataInterface::ParseGeom(const MetadataSupplierInterface & mds)
{
  // Metadata read by GDAL
  Fetch(MDTime::AcquisitionStartTime, mds, "support_data.image_date");
  Fetch(MDNum::LineSpacing, mds, "meters_per_pixel_y");
  Fetch(MDNum::PixelSpacing, mds, "meters_per_pixel_x");
  Fetch(MDStr::Instrument, mds, "sensor");
  m_Imd.Add(MDStr::SensorID, "SAR");

  // Product file
  auto ProductFilePath = boost::filesystem::path(mds.GetResourceFile());
  if (!ProductFilePath.empty())
  {
    XMLMetadataSupplier ProductMS((ProductFilePath.remove_filename() /= "product.xml").string());
    m_Imd.Add(MDStr::Mission, ProductMS.GetAs<std::string>("product.sourceAttributes.satellite"));
    m_Imd.Add(MDNum::NumberOfLines, ProductMS.GetAs<int>("product.imageAttributes.rasterAttributes.numberOfLines"));
    m_Imd.Add(MDNum::NumberOfColumns, ProductMS.GetAs<int>("product.imageAttributes.rasterAttributes.numberOfSamplesPerLine"));
    m_Imd.Add(MDTime::ProductionDate,
	      ProductMS.GetFirstAs<MetaData::Time>("product.imageGenerationParameters.generalProcessingInformation.processingTime"));
    m_Imd.Add(MDNum::AverageSceneHeight,
	      ProductMS.GetAs<double>("product.imageAttributes.geographicInformation.referenceEllipsoidParameters.geodeticTerrainHeight"));
    m_Imd.Add(MDNum::RadarFrequency, this->GetRadarFrequency());
    m_Imd.Add(MDNum::PRF, this->GetPRF());
    m_Imd.Add(MDNum::RSF, this->GetRSF());
    m_Imd.Add(MDNum::CenterIncidenceAngle, this->GetCenterIncidenceAngle());
    m_Imd.Add(MDStr::BeamMode, ProductMS.GetAs<std::string>("product.sourceAttributes.beamModeMnemonic"));
    m_Imd.Add("FACILITY_IDENTIFIER", ProductMS.GetAs<std::string>("product.sourceAttributes.inputDatasetFacilityId"));
    m_Imd.Add(MDStr::OrbitDirection, ProductMS.GetAs<std::string>("product.sourceAttributes.orbitAndAttitude.orbitInformation.passDirection"));
    m_Imd.Add(MDStr::ProductType, ProductMS.GetAs<std::string>("product.imageGenerationParameters.generalProcessingInformation.productType"));

    auto polarizations = ProductMS.GetAsVector<std::string>("product.sourceAttributes.radarParameters.polarizations");
    assert(polarizations.size() == m_Imd.Bands.size());
    SARParam sarParam;
    for (int bandId = 0 ; bandId < polarizations.size() ; ++bandId)
    {
      m_Imd.Bands[bandId].Add(MDStr::Polarization, polarizations[bandId]);
      m_Imd.Bands[bandId].Add(MDGeom::SAR, sarParam);
    }
  }
}

void Radarsat2ImageMetadataInterface::Parse(const MetadataSupplierInterface & mds)
{
  // Try to fetch the metadata from GDAL Metadata Supplier
  if (mds.GetAs<std::string>("", "SATELLITE_IDENTIFIER") == "RADARSAT-2")
    this->ParseGdal(mds);
  // Try to fetch the metadata from GEOM file
  else if (mds.GetAs<std::string>("", "sensor") == "RADARSAT-2")
    this->ParseGeom(mds);
  // Failed to fetch the metadata
  else
    otbGenericExceptionMacro(MissingMetadataException,
			     << "Not a Sentinel1 product");
}

} // end namespace otb

ext: cxx

max_stars_repo_name: heralex/OTB

max_issues_repo_name: heralex/OTB

max_forks_repo_name: heralex/OTB


text: #include <boost/spirit/include/qi_symbols.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino