<commit_before>#ifndef PYTHONMULTIMAPPING_INL
#define PYTHONMULTIMAPPING_INL

#include "PythonMultiMapping.h"

namespace sofa {
namespace component {
namespace mapping {

template<class TIn, class TOut>
PythonMultiMapping<TIn, TOut>::PythonMultiMapping() :
    matrix(initData(&matrix, "jacobian", "jacobian for the mapping (row-major)")),
    value(initData(&value, "value", "mapping value")),
    gs_matrix(initData(&gs_matrix, "geometric_stiffness", "mapping geometric stiffness matrix (row-major)")),
    use_gs(initData(&use_gs, true, "use_geometric_stiffness", "mapping geometric stiffness matrix (row-major)")),
    out_force(initData(&out_force, "out_force", "output force used to compute geometric stiffness (read-only)")) {

}

template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::assemble_geometric( const helper::vector<typename self::in_pos_type>& in,
														const typename self::const_out_deriv_type& out) {

    if(use_gs.getValue()) {
        // copy force in data
        set(out_force) = out.ref();

        // std::cout << "c++ out_force: " << set(out_force) << std::endl;

        // hand over to python
        if(this->py_callback) {
            this->py_callback( gs_state );
        }

        // assemble sparse jacobian from data
        unsigned rows = 0;

        for(unsigned i = 0, n = in.size(); i < n; ++i) {
            rows += this->from(i)->getMatrixSize();
        }

        typedef typename self::geometric_type::CompressedMatrix gs_type;
        gs_type& dJ = this->geometric.compressedMatrix;

        dJ.resize(rows, rows);
        dJ.setZero();

        const unsigned size = rows * rows;

        const matrix_type& gs = gs_matrix.getValue();
        if( gs.size() != size ) {

            if( gs.size() ) {
                serr << "assemble: incorrect geometric stiffness size, treating as zero";
            }

            return;
        }

        for(unsigned i = 0; i < rows; ++i) {
            dJ.startVec(i);

            for(unsigned j = 0; j < rows; ++j) {
                const SReal value = gs[ rows * i + j];
                if(value ) dJ.insertBack(i, j) = value;
            }

        }

        dJ.finalize();

        // std::cout << "c++ dJT" << std::endl
        //           << dJ << std::endl;
    }

}

template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::assemble( const helper::vector<typename self::in_pos_type>& in )  {
    // initialize jacobians

    const value_type& value = this->value.getValue();
    const matrix_type& matrix = this->matrix.getValue();

    typedef typename self::jacobian_type::CompressedMatrix block_type;

    // resize jacobian blocks
    unsigned size = 0;

    const unsigned rows = value.size() * out_deriv_size;

    for(unsigned j = 0, m = in.size(); j < m; ++j) {
        block_type& block = this->jacobian(j).compressedMatrix;

        const unsigned cols = this->from(j)->getMatrixSize();

        block.resize(rows, cols);
        block.setZero();
        size += rows * cols;
    }

    if(matrix.size() != size) {

        // note: empty 'jacobian' will be silently treated as zero
        if( matrix.size() ) {
            serr << "assemble: incorrect jacobian size, treating as zero" << sendl;
        }

        return;
    }

    // each out dof
    unsigned off = 0;

    // each output mstate
    for(unsigned i = 0, n = value.size(); i < n; ++i) {

        for(unsigned v = 0; v < out_deriv_size; ++v) {

            // each input mstate
            for(unsigned j = 0, m = in.size(); j < m; ++j) {
                block_type& block = this->jacobian(j).compressedMatrix;

                const unsigned dim = this->from(j)->getMatrixSize();

                const unsigned r = out_deriv_size * i + v;
                block.startVec(r);

                // each input mstate dof
                for(unsigned k = 0, p = in[j].size(); k < p; ++k) {

                    // each dof dimension
                    for(unsigned u = 0; u < in_deriv_size; ++u) {
                        const unsigned c = k * in_deriv_size + u;
                        const SReal value = matrix[off + c];
                        if( value ) block.insertBack(r, c) = value;
                    }
                }
                off += dim;
            }

        }

    }
    assert( off == matrix.size() );

    // each input mstate
    for(unsigned j = 0, m = in.size(); j < m; ++j) {
        block_type& block = this->jacobian(j).compressedMatrix;

        block.finalize();
    }

}

template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::apply(typename self::out_pos_type& out,
                                          const helper::vector<typename self::in_pos_type>& /*in*/ ){

    if(this->py_callback) {
        this->py_callback( apply_state );
    }

    const value_type& value = this->value.getValue();

    if( out.size() != value.size() ) {
        serr << "apply: size for data 'value' does not match output, auto-resizing" << sendl;
        const_cast<value_type&>(value).resize( out.size() );
    }

    for(unsigned i = 0, n = out.size(); i < n; ++i) {
        out[i] = value[i];
    }

}

}
}
}

#endif

<commit_msg>[Compliant] some debug info in python mappings<commit_after>#ifndef PYTHONMULTIMAPPING_INL
#define PYTHONMULTIMAPPING_INL

#include "PythonMultiMapping.h"

namespace sofa {
namespace component {
namespace mapping {

template<class TIn, class TOut>
PythonMultiMapping<TIn, TOut>::PythonMultiMapping() :
    matrix(initData(&matrix, "jacobian", "jacobian for the mapping (row-major)")),
    value(initData(&value, "value", "mapping value")),
    gs_matrix(initData(&gs_matrix, "geometric_stiffness", "mapping geometric stiffness matrix (row-major)")),
    use_gs(initData(&use_gs, true, "use_geometric_stiffness", "mapping geometric stiffness matrix (row-major)")),
    out_force(initData(&out_force, "out_force", "output force used to compute geometric stiffness (read-only)")) {

}

template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::assemble_geometric( const helper::vector<typename self::in_pos_type>& in,
														const typename self::const_out_deriv_type& out) {

    if(use_gs.getValue()) {
        // copy force in data
        set(out_force) = out.ref();

        // std::cout << "c++ out_force: " << set(out_force) << std::endl;

        // hand over to python
        if(this->py_callback) {
            this->py_callback( gs_state );
        }

        // assemble sparse jacobian from data
        unsigned rows = 0;

        for(unsigned i = 0, n = in.size(); i < n; ++i) {
            rows += this->from(i)->getMatrixSize();
        }

        typedef typename self::geometric_type::CompressedMatrix gs_type;
        gs_type& dJ = this->geometric.compressedMatrix;

        dJ.resize(rows, rows);
        dJ.setZero();

        const unsigned size = rows * rows;

        const matrix_type& gs = gs_matrix.getValue();
        if( gs.size() != size ) {

            if( gs.size() ) {
                serr << "assemble: incorrect geometric stiffness size, treating as zero";
            }

            return;
        }

        for(unsigned i = 0; i < rows; ++i) {
            dJ.startVec(i);

            for(unsigned j = 0; j < rows; ++j) {
                const SReal value = gs[ rows * i + j];
                if(value ) dJ.insertBack(i, j) = value;
            }

        }

        dJ.finalize();

        // std::cout << "c++ dJT" << std::endl
        //           << dJ << std::endl;
    }

}

template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::assemble( const helper::vector<typename self::in_pos_type>& in )  {
    // initialize jacobians

    const value_type& value = this->value.getValue();
    const matrix_type& matrix = this->matrix.getValue();

    typedef typename self::jacobian_type::CompressedMatrix block_type;

    // resize jacobian blocks
    unsigned size = 0;

    const unsigned rows = value.size() * out_deriv_size;

    for(unsigned j = 0, m = in.size(); j < m; ++j) {
        block_type& block = this->jacobian(j).compressedMatrix;

        const unsigned cols = this->from(j)->getMatrixSize();

        block.resize(rows, cols);
        block.setZero();
        size += rows * cols;
    }

    if(matrix.size() != size) {

        // note: empty 'jacobian' will be silently treated as zero
        if( matrix.size() ) {
            serr << "assemble: incorrect jacobian size, treating as zero (solve *will* fail !)"
                 << sendl;
        }

        return;
    }

    // each out dof
    unsigned off = 0;

    unsigned nnz = 0;

    // each output mstate
    for(unsigned i = 0, n = value.size(); i < n; ++i) {

        for(unsigned v = 0; v < out_deriv_size; ++v) {

            // each input mstate
            for(unsigned j = 0, m = in.size(); j < m; ++j) {
                block_type& block = this->jacobian(j).compressedMatrix;

                const unsigned dim = this->from(j)->getMatrixSize();

                const unsigned r = out_deriv_size * i + v;
                block.startVec(r);

                // each input mstate dof
                for(unsigned k = 0, p = in[j].size(); k < p; ++k) {

                    // each dof dimension
                    for(unsigned u = 0; u < in_deriv_size; ++u) {
                        const unsigned c = k * in_deriv_size + u;
                        const SReal value = matrix[off + c];

                        if( value ) {
                            block.insertBack(r, c) = value;
                            ++nnz;
                        }
                    }
                }
                off += dim;
            }

        }

    }
    assert( off == matrix.size() );

    if(!nnz) {
        serr << "assemble: zero jacobian, solve *will* fail !" << sendl;
    }

    // each input mstate
    for(unsigned j = 0, m = in.size(); j < m; ++j) {
        block_type& block = this->jacobian(j).compressedMatrix;

        block.finalize();
    }

}

template<class TIn, class TOut>
void PythonMultiMapping<TIn, TOut>::apply(typename self::out_pos_type& out,
                                          const helper::vector<typename self::in_pos_type>& /*in*/ ){

    if(this->py_callback) {
        this->py_callback( apply_state );
    }

    const value_type& value = this->value.getValue();

    if( out.size() != value.size() ) {
        serr << "apply: size for data 'value' does not match output, auto-resizing" << sendl;
        const_cast<value_type&>(value).resize( out.size() );
    }

    for(unsigned i = 0, n = out.size(); i < n; ++i) {
        out[i] = value[i];
    }

}

}
}
}

#endif

<|endoftext|>


<commit_before>//
// Created by everettjf on 2017/7/5.
//

#include "CommonDisplay.h"
#include <iostream>
#include "../util/Utility.h"
#include <libmoex/node/loadcommand.h>

using namespace std;

bool CommonDisplay::Init(const std::string & filepath,bool is_csv){
    print_ = BeautyTextPrinterFactory::CreatePrinter(is_csv);

    try{
        bin_ = std::make_shared<moex::Binary>(filepath);
    }catch(std::exception & ex){
        cout << "Parse failed : " << ex.what() <<endl;
        return false;
    }

    return true;
}

void CommonDisplay::ForEachHeader(std::function<void(moex::MachHeaderPtr)> callback){
    bin_->ForEachHeader([&](moex::MachHeaderPtr header) {
        std::string arch = moex::hp::GetArchStringFromCpuType(header->data_ptr()->cputype);
        if(!arch_.empty() && arch != arch_)
            return;
        callback(header);
    });
}

void CommonDisplay::IsFat(){
    cout << (bin_->IsFat() ? "true" : "false") <<endl;
}
void CommonDisplay::FatList(){
    if(!bin_->IsFat())
        return;

    print_->SetHeaders({"cputype","cpusubtype","offset","size","align"});
    print_->SetWidths({15,14,10,10,10});
    print_->Begin();

    for(auto & arch : bin_->fath()->archs()){
        const fat_arch & f = arch->data();
        print_->AddRow({
                moex::hp::GetCpuTypeString(f.cputype),
                moex::hp::GetCpuSubTypeString(f.cpusubtype),
                ToString(f.offset),
                ToString(f.size),
                ToString(f.align),
                });
    }

    print_->End();
}

void CommonDisplay::HeaderList(){

    print_->SetHeaders({"magic","cputype","cpusubtype","ncmds","sizeofcmds","flags"});
    print_->SetWidths({10,15,14,10,10,10});
    print_->Begin();

    bin_->ForEachHeader([&](moex::MachHeaderPtr header){
        mach_header *h = header->data_ptr();
        print_->AddRow({
                               ToString(h->magic),
                               moex::hp::GetCpuTypeString(h->cputype),
                               moex::hp::GetCpuSubTypeString(h->cpusubtype),
                               ToString(h->ncmds),
                               ToString(h->sizeofcmds),
                               ToString(h->flags),
                       });
    });

    print_->End();
}

void CommonDisplay::ArchList(){
    print_->SetHeaders({"arch"});
    print_->SetWidths({10});
    print_->Begin();
    bin_->ForEachHeader([&](moex::MachHeaderPtr header){
        mach_header *h = header->data_ptr();
        print_->AddRow({
                        moex::hp::GetArchStringFromCpuType(h->cputype)
                       });

    });
    print_->End();
}

void CommonDisplay::LoadCommandList(){
    ForEachHeader([&](moex::MachHeaderPtr header){
        print_->SetHeaders({header->GetArch() + "/ cmd","cmdsize","cmdtype","description"});
        print_->SetWidths({20,10,25,130});
        print_->Begin();

        for(auto cmd : header->loadcmds_ref()){
            print_->AddRow({
                    ToString(cmd->offset()->cmd),
                    ToString(cmd->offset()->cmdsize),
                    cmd->GetTypeName(),
                    cmd->GetDescription()
                           });
        }

        print_->End();
        cout << endl;
    });

}

void CommonDisplay::SegmentList(){
    ForEachHeader([&](moex::MachHeaderPtr header){
        print_->SetHeaders({header->GetArch() + " / cmd","cmdsize","segname","vmaddr","vmsize",
                            "fileoff","filesize","maxprot","initprot","nsects",
                            "flags","cmdtype"});
        print_->SetWidths({10,10,20,15,15,
                           10,10,10,10,10,
                           10,20});
        print_->Begin();

        for(auto cmd : header->loadcmds_ref()){
            if(cmd->offset()->cmd == LC_SEGMENT) {
                moex::LoadCommand_LC_SEGMENT *seg = static_cast<moex::LoadCommand_LC_SEGMENT*>(cmd.get());
                print_->AddRow({
                        ToString(seg->cmd()->cmd),
                        ToString(seg->cmd()->cmdsize),
                        seg->segment_name(),
                        ToString(seg->cmd()->vmaddr),
                        ToString(seg->cmd()->vmsize),

                        ToString(seg->cmd()->fileoff),
                        ToString(seg->cmd()->filesize),
                        ToString(seg->cmd()->maxprot),
                        ToString(seg->cmd()->initprot),
                        ToString(seg->cmd()->nsects),

                        ToString(seg->cmd()->flags),
                        seg->GetTypeName(),
                               });
            }else if(cmd->offset()->cmd == LC_SEGMENT_64) {
                moex::LoadCommand_LC_SEGMENT_64 *seg = static_cast<moex::LoadCommand_LC_SEGMENT_64*>(cmd.get());
                print_->AddRow({
                       ToString(seg->cmd()->cmd),
                       ToString(seg->cmd()->cmdsize),
                       seg->segment_name(),
                       ToString(seg->cmd()->vmaddr),
                       ToString(seg->cmd()->vmsize),

                       ToString(seg->cmd()->fileoff),
                       ToString(seg->cmd()->filesize),
                       ToString(seg->cmd()->maxprot),
                       ToString(seg->cmd()->initprot),
                       ToString(seg->cmd()->nsects),

                       ToString(seg->cmd()->flags),
                       seg->GetTypeName(),
                           });
            }
        }
        print_->End();
    });

}
void CommonDisplay::SectionList(){
    ForEachHeader([&](moex::MachHeaderPtr header){
        print_->SetHeaders({header->GetArch() + " / section","segment","addr","size","offset",
                            "align","reloff","nreloc","flags"});
        print_->SetWidths({20,15,10,10,10,
                           10,10,10,10});
        print_->Begin();

        for(auto cmd : header->loadcmds_ref()){
            if(cmd->offset()->cmd == LC_SEGMENT) {
                moex::LoadCommand_LC_SEGMENT *seg = static_cast<moex::LoadCommand_LC_SEGMENT*>(cmd.get());
                for(auto sect : seg->sections_ref()){
                    print_->AddRow({
                            sect->section_name(),
                            sect->segment_name(),
                            ToString(sect->offset()->addr),
                            ToString(sect->offset()->size),
                            ToString(sect->offset()->offset),
                            ToString(sect->offset()->align),
                            ToString(sect->offset()->reloff),
                            ToString(sect->offset()->nreloc),
                            ToString(sect->offset()->flags),
                                   });
                }
            }else if(cmd->offset()->cmd == LC_SEGMENT_64) {
                moex::LoadCommand_LC_SEGMENT_64 *seg = static_cast<moex::LoadCommand_LC_SEGMENT_64*>(cmd.get());
                for(auto sect : seg->sections_ref()){
                    print_->AddRow({
                                           sect->section_name(),
                                           sect->segment_name(),
                                           ToString(sect->offset()->addr),
                                           ToString(sect->offset()->size),
                                           ToString(sect->offset()->offset),
                                           ToString(sect->offset()->align),
                                           ToString(sect->offset()->reloff),
                                           ToString(sect->offset()->nreloc),
                                           ToString(sect->offset()->flags),
                                   });
                }
            }
        }
        print_->End();
    });

}
void CommonDisplay::SymbolList(){
    ForEachHeader([&](moex::MachHeaderPtr header){
        print_->SetHeaders({header->GetArch() + " / strx","type","sect","desc"});
        print_->SetWidths({20,15,10,10});
        print_->Begin();

        for(auto cmd : header->loadcmds_ref()){
            if(cmd->offset()->cmd == LC_SYMTAB) {
                moex::LoadCommand_LC_SYMTAB *seg = static_cast<moex::LoadCommand_LC_SYMTAB*>(cmd.get());
                if(seg->is64()){
                    for(auto & item : seg->nlist64s_ref()){
                        print_->AddRow({
                            ToString(item->offset()->n_un.n_strx),
                            ToString(item->offset()->n_type),
                            ToString(item->offset()->n_sect),
                            ToString(item->offset()->n_desc)
                        });
                    }
                }else{
                    for(auto & item : seg->nlists_ref()){
                        print_->AddRow({
                            ToString(item->offset()->n_un.n_strx),
                            ToString(item->offset()->n_type),
                            ToString(item->offset()->n_sect),
                            ToString(item->offset()->n_desc)
                        });
                    }
                }
            }
        }
        print_->End();
    });
}
<commit_msg>n_value<commit_after>//
// Created by everettjf on 2017/7/5.
//

#include "CommonDisplay.h"
#include <iostream>
#include "../util/Utility.h"
#include <libmoex/node/loadcommand.h>

using namespace std;

bool CommonDisplay::Init(const std::string & filepath,bool is_csv){
    print_ = BeautyTextPrinterFactory::CreatePrinter(is_csv);

    try{
        bin_ = std::make_shared<moex::Binary>(filepath);
    }catch(std::exception & ex){
        cout << "Parse failed : " << ex.what() <<endl;
        return false;
    }

    return true;
}

void CommonDisplay::ForEachHeader(std::function<void(moex::MachHeaderPtr)> callback){
    bin_->ForEachHeader([&](moex::MachHeaderPtr header) {
        std::string arch = moex::hp::GetArchStringFromCpuType(header->data_ptr()->cputype);
        if(!arch_.empty() && arch != arch_)
            return;
        callback(header);
    });
}

void CommonDisplay::IsFat(){
    cout << (bin_->IsFat() ? "true" : "false") <<endl;
}
void CommonDisplay::FatList(){
    if(!bin_->IsFat())
        return;

    print_->SetHeaders({"cputype","cpusubtype","offset","size","align"});
    print_->SetWidths({15,14,10,10,10});
    print_->Begin();

    for(auto & arch : bin_->fath()->archs()){
        const fat_arch & f = arch->data();
        print_->AddRow({
                moex::hp::GetCpuTypeString(f.cputype),
                moex::hp::GetCpuSubTypeString(f.cpusubtype),
                ToString(f.offset),
                ToString(f.size),
                ToString(f.align),
                });
    }

    print_->End();
}

void CommonDisplay::HeaderList(){

    print_->SetHeaders({"magic","cputype","cpusubtype","ncmds","sizeofcmds","flags"});
    print_->SetWidths({10,15,14,10,10,10});
    print_->Begin();

    bin_->ForEachHeader([&](moex::MachHeaderPtr header){
        mach_header *h = header->data_ptr();
        print_->AddRow({
                               ToString(h->magic),
                               moex::hp::GetCpuTypeString(h->cputype),
                               moex::hp::GetCpuSubTypeString(h->cpusubtype),
                               ToString(h->ncmds),
                               ToString(h->sizeofcmds),
                               ToString(h->flags),
                       });
    });

    print_->End();
}

void CommonDisplay::ArchList(){
    print_->SetHeaders({"arch"});
    print_->SetWidths({10});
    print_->Begin();
    bin_->ForEachHeader([&](moex::MachHeaderPtr header){
        mach_header *h = header->data_ptr();
        print_->AddRow({
                        moex::hp::GetArchStringFromCpuType(h->cputype)
                       });

    });
    print_->End();
}

void CommonDisplay::LoadCommandList(){
    ForEachHeader([&](moex::MachHeaderPtr header){
        print_->SetHeaders({header->GetArch() + "/ cmd","cmdsize","cmdtype","description"});
        print_->SetWidths({20,10,25,130});
        print_->Begin();

        for(auto cmd : header->loadcmds_ref()){
            print_->AddRow({
                    ToString(cmd->offset()->cmd),
                    ToString(cmd->offset()->cmdsize),
                    cmd->GetTypeName(),
                    cmd->GetDescription()
                           });
        }

        print_->End();
        cout << endl;
    });

}

void CommonDisplay::SegmentList(){
    ForEachHeader([&](moex::MachHeaderPtr header){
        print_->SetHeaders({header->GetArch() + " / cmd","cmdsize","segname","vmaddr","vmsize",
                            "fileoff","filesize","maxprot","initprot","nsects",
                            "flags","cmdtype"});
        print_->SetWidths({10,10,20,15,15,
                           10,10,10,10,10,
                           10,20});
        print_->Begin();

        for(auto cmd : header->loadcmds_ref()){
            if(cmd->offset()->cmd == LC_SEGMENT) {
                moex::LoadCommand_LC_SEGMENT *seg = static_cast<moex::LoadCommand_LC_SEGMENT*>(cmd.get());
                print_->AddRow({
                        ToString(seg->cmd()->cmd),
                        ToString(seg->cmd()->cmdsize),
                        seg->segment_name(),
                        ToString(seg->cmd()->vmaddr),
                        ToString(seg->cmd()->vmsize),

                        ToString(seg->cmd()->fileoff),
                        ToString(seg->cmd()->filesize),
                        ToString(seg->cmd()->maxprot),
                        ToString(seg->cmd()->initprot),
                        ToString(seg->cmd()->nsects),

                        ToString(seg->cmd()->flags),
                        seg->GetTypeName(),
                               });
            }else if(cmd->offset()->cmd == LC_SEGMENT_64) {
                moex::LoadCommand_LC_SEGMENT_64 *seg = static_cast<moex::LoadCommand_LC_SEGMENT_64*>(cmd.get());
                print_->AddRow({
                       ToString(seg->cmd()->cmd),
                       ToString(seg->cmd()->cmdsize),
                       seg->segment_name(),
                       ToString(seg->cmd()->vmaddr),
                       ToString(seg->cmd()->vmsize),

                       ToString(seg->cmd()->fileoff),
                       ToString(seg->cmd()->filesize),
                       ToString(seg->cmd()->maxprot),
                       ToString(seg->cmd()->initprot),
                       ToString(seg->cmd()->nsects),

                       ToString(seg->cmd()->flags),
                       seg->GetTypeName(),
                           });
            }
        }
        print_->End();
    });

}
void CommonDisplay::SectionList(){
    ForEachHeader([&](moex::MachHeaderPtr header){
        print_->SetHeaders({header->GetArch() + " / section","segment","addr","size","offset",
                            "align","reloff","nreloc","flags"});
        print_->SetWidths({20,15,10,10,10,
                           10,10,10,10});
        print_->Begin();

        for(auto cmd : header->loadcmds_ref()){
            if(cmd->offset()->cmd == LC_SEGMENT) {
                moex::LoadCommand_LC_SEGMENT *seg = static_cast<moex::LoadCommand_LC_SEGMENT*>(cmd.get());
                for(auto & sect : seg->sections_ref()){
                    print_->AddRow({
                            sect->section_name(),
                            sect->segment_name(),
                            ToString(sect->offset()->addr),
                            ToString(sect->offset()->size),
                            ToString(sect->offset()->offset),
                            ToString(sect->offset()->align),
                            ToString(sect->offset()->reloff),
                            ToString(sect->offset()->nreloc),
                            ToString(sect->offset()->flags),
                                   });
                }
            }else if(cmd->offset()->cmd == LC_SEGMENT_64) {
                moex::LoadCommand_LC_SEGMENT_64 *seg = static_cast<moex::LoadCommand_LC_SEGMENT_64*>(cmd.get());
                for(auto & sect : seg->sections_ref()){
                    print_->AddRow({
                                           sect->section_name(),
                                           sect->segment_name(),
                                           ToString(sect->offset()->addr),
                                           ToString(sect->offset()->size),
                                           ToString(sect->offset()->offset),
                                           ToString(sect->offset()->align),
                                           ToString(sect->offset()->reloff),
                                           ToString(sect->offset()->nreloc),
                                           ToString(sect->offset()->flags),
                                   });
                }
            }
        }
        print_->End();
    });

}
void CommonDisplay::SymbolList(){
    ForEachHeader([&](moex::MachHeaderPtr header){
        print_->SetHeaders({header->GetArch() + " / strx","type","sect","desc","value"});
        print_->SetWidths({20,15,10,10,10});
        print_->Begin();

        for(auto cmd : header->loadcmds_ref()){
            if(cmd->offset()->cmd == LC_SYMTAB) {
                moex::LoadCommand_LC_SYMTAB *seg = static_cast<moex::LoadCommand_LC_SYMTAB*>(cmd.get());
                if(seg->is64()){
                    for(auto & item : seg->nlist64s_ref()){
                        print_->AddRow({
                            ToString(item->offset()->n_un.n_strx),
                            ToString(item->offset()->n_type),
                            ToString(item->offset()->n_sect),
                            ToString(item->offset()->n_desc),
                            ToString(item->offset()->n_value)
                        });
                    }
                }else{
                    for(auto & item : seg->nlists_ref()){
                        print_->AddRow({
                            ToString(item->offset()->n_un.n_strx),
                            ToString(item->offset()->n_type),
                            ToString(item->offset()->n_sect),
                            ToString(item->offset()->n_desc),
                            ToString(item->offset()->n_value)
                        });
                    }
                }
            }
        }
        print_->End();
    });
}
<|endoftext|>


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

#include "modules/planning/planner/em/em_planner.h"

#include <fstream>
#include <utility>

#include "modules/common/log.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/planning/common/data_center.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/em_planning_data.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"

namespace apollo {
namespace planning {

using apollo::common::TrajectoryPoint;
using apollo::common::vehicle_state::VehicleState;

EMPlanner::EMPlanner() {}

bool EMPlanner::MakePlan(const TrajectoryPoint& start_point,
                         std::vector<TrajectoryPoint>* discretized_trajectory) {
  DataCenter* data_center = DataCenter::instance();
  // Frame* frame = data_center->current_frame();

  frame->set_planning_data(new EMPlanningData());
//  frame->mutable_planning_data()->set_reference_line(reference_line);
//  frame->mutable_planning_data()->set_decision_data(decision_data);
//  frame->mutable_planning_data()->set_init_planning_point(
//      frame->environment().vehicle_state_proxy().init_point(data_center->last_frame()));

  return true;
}

std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
    const double init_v, const double init_a) {
  // TODO(@lianglia_apollo): this is a dummy simple hot start, need refine later
  std::array<double, 3> start_state;

  // distance 0.0
  start_state[0] = 0.0;

  // start velocity
  start_state[1] = init_v;

  // start acceleration
  start_state[2] = init_a;

  std::array<double, 2> end_state;
  // end state velocity
  end_state[0] = 10.0;

  // end state acceleration
  end_state[1] = 0.0;

  // pre assume the curve time is 8 second, can be change later
  QuarticPolynomialCurve1d speed_curve(start_state, end_state,
                                       FLAGS_trajectory_time_length);

  // assume the time resolution is 0.1
  std::size_t num_time_steps =
      static_cast<std::size_t>(FLAGS_trajectory_time_length /
                               FLAGS_trajectory_time_resolution) +
      1;
  std::vector<SpeedPoint> speed_profile;
  speed_profile.reserve(num_time_steps);

  for (std::size_t i = 0; i < num_time_steps; ++i) {
    double t = i * FLAGS_trajectory_time_resolution;
    double s = speed_curve.evaluate(0, t);
    double v = speed_curve.evaluate(1, t);
    double a = speed_curve.evaluate(2, t);
    double da = speed_curve.evaluate(3, t);
    SpeedPoint speed_point;
    speed_point.mutable_st_point()->set_s(s);
    speed_point.mutable_st_point()->set_t(t);
    speed_point.set_v(v);
    speed_point.set_a(a);
    speed_point.set_da(da);
    speed_profile.push_back(speed_point);
  }
  return std::move(speed_profile);
}

}  // namespace planning
}  // namespace apollo
<commit_msg>fix typo.<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/planner/em/em_planner.h"

#include <fstream>
#include <utility>

#include "modules/common/log.h"
#include "modules/common/util/string_tokenizer.h"
#include "modules/planning/common/data_center.h"
#include "modules/planning/common/frame.h"
#include "modules/planning/common/planning_gflags.h"
#include "modules/planning/common/em_planning_data.h"
#include "modules/planning/math/curve1d/quartic_polynomial_curve1d.h"

namespace apollo {
namespace planning {

using apollo::common::TrajectoryPoint;
using apollo::common::vehicle_state::VehicleState;

EMPlanner::EMPlanner() {}

bool EMPlanner::MakePlan(const TrajectoryPoint& start_point,
                         std::vector<TrajectoryPoint>* discretized_trajectory) {
  DataCenter* data_center = DataCenter::instance();
  Frame* frame = data_center->current_frame();

  frame->set_planning_data(new EMPlanningData());
//  frame->mutable_planning_data()->set_reference_line(reference_line);
//  frame->mutable_planning_data()->set_decision_data(decision_data);
//  frame->mutable_planning_data()->set_init_planning_point(
//      frame->environment().vehicle_state_proxy().init_point(data_center->last_frame()));

  return true;
}

std::vector<SpeedPoint> EMPlanner::GenerateInitSpeedProfile(
    const double init_v, const double init_a) {
  // TODO(@lianglia_apollo): this is a dummy simple hot start, need refine later
  std::array<double, 3> start_state;

  // distance 0.0
  start_state[0] = 0.0;

  // start velocity
  start_state[1] = init_v;

  // start acceleration
  start_state[2] = init_a;

  std::array<double, 2> end_state;
  // end state velocity
  end_state[0] = 10.0;

  // end state acceleration
  end_state[1] = 0.0;

  // pre assume the curve time is 8 second, can be change later
  QuarticPolynomialCurve1d speed_curve(start_state, end_state,
                                       FLAGS_trajectory_time_length);

  // assume the time resolution is 0.1
  std::size_t num_time_steps =
      static_cast<std::size_t>(FLAGS_trajectory_time_length /
                               FLAGS_trajectory_time_resolution) +
      1;
  std::vector<SpeedPoint> speed_profile;
  speed_profile.reserve(num_time_steps);

  for (std::size_t i = 0; i < num_time_steps; ++i) {
    double t = i * FLAGS_trajectory_time_resolution;
    double s = speed_curve.evaluate(0, t);
    double v = speed_curve.evaluate(1, t);
    double a = speed_curve.evaluate(2, t);
    double da = speed_curve.evaluate(3, t);
    SpeedPoint speed_point;
    speed_point.mutable_st_point()->set_s(s);
    speed_point.mutable_st_point()->set_t(t);
    speed_point.set_v(v);
    speed_point.set_a(a);
    speed_point.set_da(da);
    speed_profile.push_back(speed_point);
  }
  return std::move(speed_profile);
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <BufferedStreamSocket.hxx>

#include <algorithm>

#ifdef WIN32
  // LO vs WinAPI conflict
  #undef WB_LEFT
  #undef WB_RIGHT

  #include <winsock2.h>
#else
 #include <sys/socket.h>
 #include <unistd.h>
#endif
using namespace sd;
using namespace std;
using namespace osl;

BufferedStreamSocket::BufferedStreamSocket( const osl::StreamSocket &aSocket ):
    StreamSocket( aSocket ),
    aRet( 0 ),
    aRead( 0 ),
    aBuffer(),
    mSocket( 0 ),
    usingCSocket( false )
{
}

BufferedStreamSocket::BufferedStreamSocket( int aSocket ):
    StreamSocket(),
    aRet( 0 ),
    aRead( 0 ),
    aBuffer(),
    mSocket( aSocket ),
    usingCSocket( true )
{
}

void BufferedStreamSocket::getPeerAddr(osl::SocketAddr& rAddr)
{
    assert ( !usingCSocket );
    StreamSocket::getPeerAddr( rAddr );
}

sal_Int32 BufferedStreamSocket::write( const void* pBuffer, sal_uInt32 n )
{
    if ( !usingCSocket )
        return StreamSocket::write( pBuffer, n );
    else
        return ::send(
            mSocket,
#if defined WNT
            static_cast<char *>(pBuffer),
#else
            pBuffer,
#endif
            (size_t) n, 0 );
}

void BufferedStreamSocket::close()
{
    if( usingCSocket && mSocket != -1 )
    {
#ifdef WIN32
        ::closesocket( mSocket );
#else
        ::close( mSocket );
#endif
        mSocket = -1;
    }
    else
        ::osl::StreamSocket::close();
}

sal_Int32 BufferedStreamSocket::readLine( OString& aLine )
{
    while ( true )
    {
        // Process buffer first incase data already present.
        vector<char>::iterator aIt;
        if ( (aIt = find( aBuffer.begin(), aBuffer.end(), '\n' ))
             != aBuffer.end() )
        {
            sal_uInt64 aLocation = aIt - aBuffer.begin();

            aLine = OString( &(*aBuffer.begin()), aLocation );

            aBuffer.erase( aBuffer.begin(), aIt + 1 ); // Also delete the empty line
            aRead -= (aLocation + 1);

            SAL_INFO( "sdremote.bluetooth", "recv line '" << aLine << "'" );

            return aLine.getLength() + 1;
        }

        // Then try and receive if nothing present
        aBuffer.resize( aRead + 100 );
        if ( !usingCSocket)
            aRet = StreamSocket::recv( &aBuffer[aRead], 100 );
        else
            aRet = ::recv( mSocket, &aBuffer[aRead], 100, 0 );

        SAL_INFO( "sdremote.bluetooth", "recv " << aRet << " aBuffer len " << aBuffer.size() );
        if ( aRet <= 0 )
        {
            return 0;
        }
        // Prevent buffer from growing massively large.
        if ( aRead > MAX_LINE_LENGTH )
        {
            aBuffer.erase( aBuffer.begin(), aBuffer.end() );
            return 0;
        }
        aRead += aRet;
    }

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Missing const<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <BufferedStreamSocket.hxx>

#include <algorithm>

#ifdef WIN32
  // LO vs WinAPI conflict
  #undef WB_LEFT
  #undef WB_RIGHT

  #include <winsock2.h>
#else
 #include <sys/socket.h>
 #include <unistd.h>
#endif
using namespace sd;
using namespace std;
using namespace osl;

BufferedStreamSocket::BufferedStreamSocket( const osl::StreamSocket &aSocket ):
    StreamSocket( aSocket ),
    aRet( 0 ),
    aRead( 0 ),
    aBuffer(),
    mSocket( 0 ),
    usingCSocket( false )
{
}

BufferedStreamSocket::BufferedStreamSocket( int aSocket ):
    StreamSocket(),
    aRet( 0 ),
    aRead( 0 ),
    aBuffer(),
    mSocket( aSocket ),
    usingCSocket( true )
{
}

void BufferedStreamSocket::getPeerAddr(osl::SocketAddr& rAddr)
{
    assert ( !usingCSocket );
    StreamSocket::getPeerAddr( rAddr );
}

sal_Int32 BufferedStreamSocket::write( const void* pBuffer, sal_uInt32 n )
{
    if ( !usingCSocket )
        return StreamSocket::write( pBuffer, n );
    else
        return ::send(
            mSocket,
#if defined WNT
            static_cast<char const *>(pBuffer),
#else
            pBuffer,
#endif
            (size_t) n, 0 );
}

void BufferedStreamSocket::close()
{
    if( usingCSocket && mSocket != -1 )
    {
#ifdef WIN32
        ::closesocket( mSocket );
#else
        ::close( mSocket );
#endif
        mSocket = -1;
    }
    else
        ::osl::StreamSocket::close();
}

sal_Int32 BufferedStreamSocket::readLine( OString& aLine )
{
    while ( true )
    {
        // Process buffer first incase data already present.
        vector<char>::iterator aIt;
        if ( (aIt = find( aBuffer.begin(), aBuffer.end(), '\n' ))
             != aBuffer.end() )
        {
            sal_uInt64 aLocation = aIt - aBuffer.begin();

            aLine = OString( &(*aBuffer.begin()), aLocation );

            aBuffer.erase( aBuffer.begin(), aIt + 1 ); // Also delete the empty line
            aRead -= (aLocation + 1);

            SAL_INFO( "sdremote.bluetooth", "recv line '" << aLine << "'" );

            return aLine.getLength() + 1;
        }

        // Then try and receive if nothing present
        aBuffer.resize( aRead + 100 );
        if ( !usingCSocket)
            aRet = StreamSocket::recv( &aBuffer[aRead], 100 );
        else
            aRet = ::recv( mSocket, &aBuffer[aRead], 100, 0 );

        SAL_INFO( "sdremote.bluetooth", "recv " << aRet << " aBuffer len " << aBuffer.size() );
        if ( aRet <= 0 )
        {
            return 0;
        }
        // Prevent buffer from growing massively large.
        if ( aRead > MAX_LINE_LENGTH )
        {
            aBuffer.erase( aBuffer.begin(), aBuffer.end() );
            return 0;
        }
        aRead += aRet;
    }

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


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

#include "net/base/cert_verifier.h"

#include "base/bind.h"
#include "base/file_path.h"
#include "base/format_macros.h"
#include "base/stringprintf.h"
#include "net/base/cert_test_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/test_completion_callback.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

void FailTest(int /* result */) {
  FAIL();
}

}  // namespace;

// Tests a cache hit, which should result in synchronous completion.
TEST(CertVerifierTest, CacheHit) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();
  scoped_refptr<X509Certificate> test_cert(
      ImportCertFromFile(certs_dir, "ok_cert.pem"));
  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);

  int error;
  CertVerifyResult verify_result;
  TestCompletionCallback callback;
  CertVerifier::RequestHandle request_handle;

  error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
                          callback.callback(), &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  error = callback.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_EQ(1u, verifier.requests());
  ASSERT_EQ(0u, verifier.cache_hits());
  ASSERT_EQ(0u, verifier.inflight_joins());
  ASSERT_EQ(1u, verifier.GetCacheSize());

  error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
                          callback.callback(), &request_handle, BoundNetLog());
  // Synchronous completion.
  ASSERT_NE(ERR_IO_PENDING, error);
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_TRUE(request_handle == NULL);
  ASSERT_EQ(2u, verifier.requests());
  ASSERT_EQ(1u, verifier.cache_hits());
  ASSERT_EQ(0u, verifier.inflight_joins());
  ASSERT_EQ(1u, verifier.GetCacheSize());
}

// Tests the same server certificate with different intermediate CA
// certificates.  These should be treated as different certificate chains even
// though the two X509Certificate objects contain the same server certificate.
TEST(CertVerifierTest, DifferentCACerts) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();

  scoped_refptr<X509Certificate> server_cert =
      ImportCertFromFile(certs_dir, "salesforce_com_test.pem");
  ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert);

  scoped_refptr<X509Certificate> intermediate_cert1 =
      ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2011.pem");
  ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert1);

  scoped_refptr<X509Certificate> intermediate_cert2 =
      ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2016.pem");
  ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert2);

  X509Certificate::OSCertHandles intermediates;
  intermediates.push_back(intermediate_cert1->os_cert_handle());
  scoped_refptr<X509Certificate> cert_chain1 =
      X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
                                        intermediates);

  intermediates.clear();
  intermediates.push_back(intermediate_cert2->os_cert_handle());
  scoped_refptr<X509Certificate> cert_chain2 =
      X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
                                        intermediates);

  int error;
  CertVerifyResult verify_result;
  TestCompletionCallback callback;
  CertVerifier::RequestHandle request_handle;

  error = verifier.Verify(cert_chain1, "www.example.com", 0, NULL,
                          &verify_result, callback.callback(),
                          &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  error = callback.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_EQ(1u, verifier.requests());
  ASSERT_EQ(0u, verifier.cache_hits());
  ASSERT_EQ(0u, verifier.inflight_joins());
  ASSERT_EQ(1u, verifier.GetCacheSize());

  error = verifier.Verify(cert_chain2, "www.example.com", 0, NULL,
                          &verify_result, callback.callback(),
                          &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  error = callback.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_EQ(2u, verifier.requests());
  ASSERT_EQ(0u, verifier.cache_hits());
  ASSERT_EQ(0u, verifier.inflight_joins());
  ASSERT_EQ(2u, verifier.GetCacheSize());
}

// Tests an inflight join.
TEST(CertVerifierTest, InflightJoin) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();
  scoped_refptr<X509Certificate> test_cert(
      ImportCertFromFile(certs_dir, "ok_cert.pem"));
  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);

  int error;
  CertVerifyResult verify_result;
  TestCompletionCallback callback;
  CertVerifier::RequestHandle request_handle;
  CertVerifyResult verify_result2;
  TestCompletionCallback callback2;
  CertVerifier::RequestHandle request_handle2;

  error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
                          callback.callback(), &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  error = verifier.Verify(
      test_cert, "www.example.com", 0, NULL, &verify_result2,
      callback2.callback(), &request_handle2, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle2 != NULL);
  error = callback.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  error = callback2.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_EQ(2u, verifier.requests());
  ASSERT_EQ(0u, verifier.cache_hits());
  ASSERT_EQ(1u, verifier.inflight_joins());
}

// Tests that the callback of a canceled request is never made.
TEST(CertVerifierTest, CancelRequest) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();
  scoped_refptr<X509Certificate> test_cert(
      ImportCertFromFile(certs_dir, "ok_cert.pem"));
  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);

  int error;
  CertVerifyResult verify_result;
  CertVerifier::RequestHandle request_handle;

  error = verifier.Verify(
      test_cert, "www.example.com", 0, NULL, &verify_result,
      base::Bind(&FailTest), &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  verifier.CancelRequest(request_handle);

  // Issue a few more requests to the worker pool and wait for their
  // completion, so that the task of the canceled request (which runs on a
  // worker thread) is likely to complete by the end of this test.
  TestCompletionCallback callback;
  for (int i = 0; i < 5; ++i) {
    error = verifier.Verify(
        test_cert, "www2.example.com", 0, NULL, &verify_result,
        callback.callback(), &request_handle, BoundNetLog());
    ASSERT_EQ(ERR_IO_PENDING, error);
    ASSERT_TRUE(request_handle != NULL);
    error = callback.WaitForResult();
    verifier.ClearCache();
  }
}

// Tests that a canceled request is not leaked.
TEST(CertVerifierTest, CancelRequestThenQuit) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();
  scoped_refptr<X509Certificate> test_cert(
      ImportCertFromFile(certs_dir, "ok_cert.pem"));
  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);

  int error;
  CertVerifyResult verify_result;
  TestCompletionCallback callback;
  CertVerifier::RequestHandle request_handle;

  error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
                          callback.callback(), &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  verifier.CancelRequest(request_handle);
  // Destroy |verifier| by going out of scope.
}

TEST(CertVerifierTest, RequestParamsComparators) {
  SHA1Fingerprint a_key;
  memset(a_key.data, 'a', sizeof(a_key.data));

  SHA1Fingerprint z_key;
  memset(z_key.data, 'z', sizeof(z_key.data));

  struct {
    // Keys to test
    CertVerifier::RequestParams key1;
    CertVerifier::RequestParams key2;

    // Expectation:
    // -1 means key1 is less than key2
    //  0 means key1 equals key2
    //  1 means key1 is greater than key2
    int expected_result;
  } tests[] = {
    {  // Test for basic equivalence.
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      0,
    },
    {  // Test that different certificates but with the same CA and for
       // the same host are different validation keys.
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      CertVerifier::RequestParams(z_key, a_key, "www.example.test", 0),
      -1,
    },
    {  // Test that the same EE certificate for the same host, but with
       // different chains are different validation keys.
      CertVerifier::RequestParams(a_key, z_key, "www.example.test", 0),
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      1,
    },
    {  // The same certificate, with the same chain, but for different
       // hosts are different validation keys.
      CertVerifier::RequestParams(a_key, a_key, "www1.example.test", 0),
      CertVerifier::RequestParams(a_key, a_key, "www2.example.test", 0),
      -1,
    },
    {  // The same certificate, chain, and host, but with different flags
       // are different validation keys.
      CertVerifier::RequestParams(a_key, a_key, "www.example.test",
                                  X509Certificate::VERIFY_EV_CERT),
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      1,
    }
  };
  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
    SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i));

    const CertVerifier::RequestParams& key1 = tests[i].key1;
    const CertVerifier::RequestParams& key2 = tests[i].key2;

    switch (tests[i].expected_result) {
      case -1:
        EXPECT_TRUE(key1 < key2);
        EXPECT_FALSE(key2 < key1);
        break;
      case 0:
        EXPECT_FALSE(key1 < key2);
        EXPECT_FALSE(key2 < key1);
        break;
      case 1:
        EXPECT_FALSE(key1 < key2);
        EXPECT_TRUE(key2 < key1);
        break;
      default:
        FAIL() << "Invalid expectation. Can be only -1, 0, 1";
    }
  }
}

}  // namespace net
<commit_msg>Mark CertVerifierTest.CacheHit test as FAILS_ for Mac OSX.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/base/cert_verifier.h"

#include "base/bind.h"
#include "base/file_path.h"
#include "base/format_macros.h"
#include "base/stringprintf.h"
#include "net/base/cert_test_util.h"
#include "net/base/net_errors.h"
#include "net/base/net_log.h"
#include "net/base/test_completion_callback.h"
#include "net/base/x509_certificate.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace net {

namespace {

void FailTest(int /* result */) {
  FAIL();
}

}  // namespace;

// Tests a cache hit, which should result in synchronous completion.
#if defined(OS_MACOSX)
// http://crbug.com/117372
#define MAYBE_CacheHit FAILS_CacheHit
#else
#define MAYBE_CacheHit CacheHit
#endif  // defined(OS_MACOSX)
TEST(CertVerifierTest, MAYBE_CacheHit) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();
  scoped_refptr<X509Certificate> test_cert(
      ImportCertFromFile(certs_dir, "ok_cert.pem"));
  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);

  int error;
  CertVerifyResult verify_result;
  TestCompletionCallback callback;
  CertVerifier::RequestHandle request_handle;

  error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
                          callback.callback(), &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  error = callback.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_EQ(1u, verifier.requests());
  ASSERT_EQ(0u, verifier.cache_hits());
  ASSERT_EQ(0u, verifier.inflight_joins());
  ASSERT_EQ(1u, verifier.GetCacheSize());

  error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
                          callback.callback(), &request_handle, BoundNetLog());
  // Synchronous completion.
  ASSERT_NE(ERR_IO_PENDING, error);
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_TRUE(request_handle == NULL);
  ASSERT_EQ(2u, verifier.requests());
  ASSERT_EQ(1u, verifier.cache_hits());
  ASSERT_EQ(0u, verifier.inflight_joins());
  ASSERT_EQ(1u, verifier.GetCacheSize());
}

// Tests the same server certificate with different intermediate CA
// certificates.  These should be treated as different certificate chains even
// though the two X509Certificate objects contain the same server certificate.
TEST(CertVerifierTest, DifferentCACerts) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();

  scoped_refptr<X509Certificate> server_cert =
      ImportCertFromFile(certs_dir, "salesforce_com_test.pem");
  ASSERT_NE(static_cast<X509Certificate*>(NULL), server_cert);

  scoped_refptr<X509Certificate> intermediate_cert1 =
      ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2011.pem");
  ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert1);

  scoped_refptr<X509Certificate> intermediate_cert2 =
      ImportCertFromFile(certs_dir, "verisign_intermediate_ca_2016.pem");
  ASSERT_NE(static_cast<X509Certificate*>(NULL), intermediate_cert2);

  X509Certificate::OSCertHandles intermediates;
  intermediates.push_back(intermediate_cert1->os_cert_handle());
  scoped_refptr<X509Certificate> cert_chain1 =
      X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
                                        intermediates);

  intermediates.clear();
  intermediates.push_back(intermediate_cert2->os_cert_handle());
  scoped_refptr<X509Certificate> cert_chain2 =
      X509Certificate::CreateFromHandle(server_cert->os_cert_handle(),
                                        intermediates);

  int error;
  CertVerifyResult verify_result;
  TestCompletionCallback callback;
  CertVerifier::RequestHandle request_handle;

  error = verifier.Verify(cert_chain1, "www.example.com", 0, NULL,
                          &verify_result, callback.callback(),
                          &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  error = callback.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_EQ(1u, verifier.requests());
  ASSERT_EQ(0u, verifier.cache_hits());
  ASSERT_EQ(0u, verifier.inflight_joins());
  ASSERT_EQ(1u, verifier.GetCacheSize());

  error = verifier.Verify(cert_chain2, "www.example.com", 0, NULL,
                          &verify_result, callback.callback(),
                          &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  error = callback.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_EQ(2u, verifier.requests());
  ASSERT_EQ(0u, verifier.cache_hits());
  ASSERT_EQ(0u, verifier.inflight_joins());
  ASSERT_EQ(2u, verifier.GetCacheSize());
}

// Tests an inflight join.
TEST(CertVerifierTest, InflightJoin) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();
  scoped_refptr<X509Certificate> test_cert(
      ImportCertFromFile(certs_dir, "ok_cert.pem"));
  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);

  int error;
  CertVerifyResult verify_result;
  TestCompletionCallback callback;
  CertVerifier::RequestHandle request_handle;
  CertVerifyResult verify_result2;
  TestCompletionCallback callback2;
  CertVerifier::RequestHandle request_handle2;

  error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
                          callback.callback(), &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  error = verifier.Verify(
      test_cert, "www.example.com", 0, NULL, &verify_result2,
      callback2.callback(), &request_handle2, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle2 != NULL);
  error = callback.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  error = callback2.WaitForResult();
  ASSERT_TRUE(IsCertificateError(error));
  ASSERT_EQ(2u, verifier.requests());
  ASSERT_EQ(0u, verifier.cache_hits());
  ASSERT_EQ(1u, verifier.inflight_joins());
}

// Tests that the callback of a canceled request is never made.
TEST(CertVerifierTest, CancelRequest) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();
  scoped_refptr<X509Certificate> test_cert(
      ImportCertFromFile(certs_dir, "ok_cert.pem"));
  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);

  int error;
  CertVerifyResult verify_result;
  CertVerifier::RequestHandle request_handle;

  error = verifier.Verify(
      test_cert, "www.example.com", 0, NULL, &verify_result,
      base::Bind(&FailTest), &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  verifier.CancelRequest(request_handle);

  // Issue a few more requests to the worker pool and wait for their
  // completion, so that the task of the canceled request (which runs on a
  // worker thread) is likely to complete by the end of this test.
  TestCompletionCallback callback;
  for (int i = 0; i < 5; ++i) {
    error = verifier.Verify(
        test_cert, "www2.example.com", 0, NULL, &verify_result,
        callback.callback(), &request_handle, BoundNetLog());
    ASSERT_EQ(ERR_IO_PENDING, error);
    ASSERT_TRUE(request_handle != NULL);
    error = callback.WaitForResult();
    verifier.ClearCache();
  }
}

// Tests that a canceled request is not leaked.
TEST(CertVerifierTest, CancelRequestThenQuit) {
  CertVerifier verifier;

  FilePath certs_dir = GetTestCertsDirectory();
  scoped_refptr<X509Certificate> test_cert(
      ImportCertFromFile(certs_dir, "ok_cert.pem"));
  ASSERT_NE(static_cast<X509Certificate*>(NULL), test_cert);

  int error;
  CertVerifyResult verify_result;
  TestCompletionCallback callback;
  CertVerifier::RequestHandle request_handle;

  error = verifier.Verify(test_cert, "www.example.com", 0, NULL, &verify_result,
                          callback.callback(), &request_handle, BoundNetLog());
  ASSERT_EQ(ERR_IO_PENDING, error);
  ASSERT_TRUE(request_handle != NULL);
  verifier.CancelRequest(request_handle);
  // Destroy |verifier| by going out of scope.
}

TEST(CertVerifierTest, RequestParamsComparators) {
  SHA1Fingerprint a_key;
  memset(a_key.data, 'a', sizeof(a_key.data));

  SHA1Fingerprint z_key;
  memset(z_key.data, 'z', sizeof(z_key.data));

  struct {
    // Keys to test
    CertVerifier::RequestParams key1;
    CertVerifier::RequestParams key2;

    // Expectation:
    // -1 means key1 is less than key2
    //  0 means key1 equals key2
    //  1 means key1 is greater than key2
    int expected_result;
  } tests[] = {
    {  // Test for basic equivalence.
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      0,
    },
    {  // Test that different certificates but with the same CA and for
       // the same host are different validation keys.
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      CertVerifier::RequestParams(z_key, a_key, "www.example.test", 0),
      -1,
    },
    {  // Test that the same EE certificate for the same host, but with
       // different chains are different validation keys.
      CertVerifier::RequestParams(a_key, z_key, "www.example.test", 0),
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      1,
    },
    {  // The same certificate, with the same chain, but for different
       // hosts are different validation keys.
      CertVerifier::RequestParams(a_key, a_key, "www1.example.test", 0),
      CertVerifier::RequestParams(a_key, a_key, "www2.example.test", 0),
      -1,
    },
    {  // The same certificate, chain, and host, but with different flags
       // are different validation keys.
      CertVerifier::RequestParams(a_key, a_key, "www.example.test",
                                  X509Certificate::VERIFY_EV_CERT),
      CertVerifier::RequestParams(a_key, a_key, "www.example.test", 0),
      1,
    }
  };
  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); ++i) {
    SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]", i));

    const CertVerifier::RequestParams& key1 = tests[i].key1;
    const CertVerifier::RequestParams& key2 = tests[i].key2;

    switch (tests[i].expected_result) {
      case -1:
        EXPECT_TRUE(key1 < key2);
        EXPECT_FALSE(key2 < key1);
        break;
      case 0:
        EXPECT_FALSE(key1 < key2);
        EXPECT_FALSE(key2 < key1);
        break;
      case 1:
        EXPECT_FALSE(key1 < key2);
        EXPECT_TRUE(key2 < key1);
        break;
      default:
        FAIL() << "Invalid expectation. Can be only -1, 0, 1";
    }
  }
}

}  // namespace net
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_TEST_GRIDS_HH
#define DUNE_GDT_TEST_GRIDS_HH

#include <dune/grid/sgrid.hh>
#include <dune/grid/yaspgrid.hh>
#if HAVE_ALUGRID
#include <dune/grid/alugrid.hh>
#endif

#include <dune/gdt/spaces/tools.hh>

using namespace Dune;
using namespace GDT;

#define SGRID_TYPES(dim)                                                                                \
  typedef typename SpaceTools::LeafGridPartView<SGrid<dim, dim>, false>::Type S##dim##dLeafGridPartType;               \
  typedef typename SpaceTools::LevelGridPartView<SGrid<dim, dim>, false>::Type S##dim##dLevelGridPartType;             \
  typedef typename SpaceTools::LeafGridPartView<SGrid<dim, dim>, true>::Type S##dim##dLeafGridViewType;                \
  typedef typename SpaceTools::LevelGridPartView<SGrid<dim, dim>, true>::Type S##dim##dLevelGridViewType;
SGRID_TYPES(1)
SGRID_TYPES(2)
SGRID_TYPES(3)
#undef SGRID_TYPES

#define YASPGRID_TYPES(dim)                                                                                \
  typedef typename SpaceTools::LeafGridPartView<YaspGrid<dim>, false>::Type Yasp##dim##dLeafGridPartType;              \
  typedef typename SpaceTools::LevelGridPartView<YaspGrid<dim>, false>::Type Yasp##dim##dLevelGridPartType;            \
  typedef typename SpaceTools::LeafGridPartView<YaspGrid<dim>, true>::Type Yasp##dim##dLeafGridViewType;               \
  typedef typename SpaceTools::LevelGridPartView<YaspGrid<dim>, true>::Type Yasp##dim##dLevelGridViewType;
YASPGRID_TYPES(1)
YASPGRID_TYPES(2)
YASPGRID_TYPES(3)
#undef YASPGRID_TYPES

#if HAVE_ALUGRID

typedef ALUGrid<2, 2, simplex, conforming> AluConform2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluConform2dGridType, false>::Type AluConform2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluConform2dGridType, false>::Type AluConform2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluConform2dGridType, true>::Type AluConform2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluConform2dGridType, true>::Type AluConform2dLevelGridViewType;

typedef ALUGrid<2, 2, simplex, nonconforming> AluSimplex2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex2dGridType, false>::Type AluSimplex2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex2dGridType, false>::Type AluSimplex2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex2dGridType, true>::Type AluSimplex2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex2dGridType, true>::Type AluSimplex2dLevelGridViewType;

typedef ALUGrid<3, 3, simplex, nonconforming> AluSimplex3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex3dGridType, false>::Type AluSimplex3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex3dGridType, false>::Type AluSimplex3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex3dGridType, true>::Type AluSimplex3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex3dGridType, true>::Type AluSimplex3dLevelGridViewType;

typedef ALUGrid<2, 2, cube, nonconforming> AluCube2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluCube2dGridType, false>::Type AluCube2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluCube2dGridType, false>::Type AluCube2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluCube2dGridType, true>::Type AluCube2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluCube2dGridType, true>::Type AluCube2dLevelGridViewType;

typedef ALUGrid<3, 3, cube, nonconforming> AluCube3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluCube3dGridType, false>::Type AluCube3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluCube3dGridType, false>::Type AluCube3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluCube3dGridType, true>::Type AluCube3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluCube3dGridType, true>::Type AluCube3dLevelGridViewType;

#endif // HAVE_ALUGRID

#endif // DUNE_GDT_TEST_GRIDS_HH
<commit_msg>[test.grids] add definition of AluConform3dGridType<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_TEST_GRIDS_HH
#define DUNE_GDT_TEST_GRIDS_HH

#include <dune/grid/sgrid.hh>
#include <dune/grid/yaspgrid.hh>
#if HAVE_ALUGRID
#include <dune/grid/alugrid.hh>
#endif

#include <dune/gdt/spaces/tools.hh>

using namespace Dune;
using namespace GDT;

#define SGRID_TYPES(dim)                                                                                \
  typedef typename SpaceTools::LeafGridPartView<SGrid<dim, dim>, false>::Type S##dim##dLeafGridPartType;               \
  typedef typename SpaceTools::LevelGridPartView<SGrid<dim, dim>, false>::Type S##dim##dLevelGridPartType;             \
  typedef typename SpaceTools::LeafGridPartView<SGrid<dim, dim>, true>::Type S##dim##dLeafGridViewType;                \
  typedef typename SpaceTools::LevelGridPartView<SGrid<dim, dim>, true>::Type S##dim##dLevelGridViewType;
SGRID_TYPES(1)
SGRID_TYPES(2)
SGRID_TYPES(3)
#undef SGRID_TYPES

#define YASPGRID_TYPES(dim)                                                                                \
  typedef typename SpaceTools::LeafGridPartView<YaspGrid<dim>, false>::Type Yasp##dim##dLeafGridPartType;              \
  typedef typename SpaceTools::LevelGridPartView<YaspGrid<dim>, false>::Type Yasp##dim##dLevelGridPartType;            \
  typedef typename SpaceTools::LeafGridPartView<YaspGrid<dim>, true>::Type Yasp##dim##dLeafGridViewType;               \
  typedef typename SpaceTools::LevelGridPartView<YaspGrid<dim>, true>::Type Yasp##dim##dLevelGridViewType;
YASPGRID_TYPES(1)
YASPGRID_TYPES(2)
YASPGRID_TYPES(3)
#undef YASPGRID_TYPES

#if HAVE_ALUGRID

typedef ALUGrid<2, 2, simplex, conforming> AluConform2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluConform2dGridType, false>::Type AluConform2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluConform2dGridType, false>::Type AluConform2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluConform2dGridType, true>::Type AluConform2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluConform2dGridType, true>::Type AluConform2dLevelGridViewType;

typedef ALUGrid<3, 3, simplex, conforming> AluConform3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluConform3dGridType, false>::Type AluConform3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluConform3dGridType, false>::Type AluConform3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluConform3dGridType, true>::Type AluConform3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluConform3dGridType, true>::Type AluConform3dLevelGridViewType;

typedef ALUGrid<2, 2, simplex, nonconforming> AluSimplex2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex2dGridType, false>::Type AluSimplex2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex2dGridType, false>::Type AluSimplex2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex2dGridType, true>::Type AluSimplex2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex2dGridType, true>::Type AluSimplex2dLevelGridViewType;

typedef ALUGrid<3, 3, simplex, nonconforming> AluSimplex3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex3dGridType, false>::Type AluSimplex3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex3dGridType, false>::Type AluSimplex3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluSimplex3dGridType, true>::Type AluSimplex3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluSimplex3dGridType, true>::Type AluSimplex3dLevelGridViewType;

typedef ALUGrid<2, 2, cube, nonconforming> AluCube2dGridType;
typedef typename SpaceTools::LeafGridPartView<AluCube2dGridType, false>::Type AluCube2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluCube2dGridType, false>::Type AluCube2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluCube2dGridType, true>::Type AluCube2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluCube2dGridType, true>::Type AluCube2dLevelGridViewType;

typedef ALUGrid<3, 3, cube, nonconforming> AluCube3dGridType;
typedef typename SpaceTools::LeafGridPartView<AluCube3dGridType, false>::Type AluCube3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView<AluCube3dGridType, false>::Type AluCube3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<AluCube3dGridType, true>::Type AluCube3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView<AluCube3dGridType, true>::Type AluCube3dLevelGridViewType;

#endif // HAVE_ALUGRID

#endif // DUNE_GDT_TEST_GRIDS_HH
<|endoftext|>


<commit_before>#include "serial.h"

int main()
{
    Serial gps(4800,"/dev/ttyUSB0",false);
    std::cout << gps.serialRead(41);

}
<commit_msg>Got rid of getData()<commit_after>#include "serial.h"

int main()
{
    Serial gps(4800,"/dev/ttyUSB0",false);
	std::cout << gps.serialRead(41) << std::endl;
	return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include <string>
#include <opencv2/core.hpp>
#include <opencv2/core/affine.hpp>

namespace cv
{
    typedef std::string String;

    namespace viz
    {
        class CV_EXPORTS Color : public Scalar
        {
        public:
            Color();
            Color(double gray);
            Color(double blue, double green, double red);

            Color(const Scalar& color);

            static Color black();
            static Color blue();
            static Color green();
            static Color cyan();

            static Color red();
            static Color magenta();
            static Color yellow();
            static Color white();

            static Color gray();
        };

        class CV_EXPORTS Mesh3d
        {
        public:

            Mat cloud, colors;
            Mat polygons;

            static cv::viz::Mesh3d loadMesh(const String& file);

        private:
            struct loadMeshImpl;
        };

        class CV_EXPORTS KeyboardEvent
        {
        public:
            static const unsigned int Alt   = 1;
            static const unsigned int Ctrl  = 2;
            static const unsigned int Shift = 4;

            /** \brief Constructor
              * \param[in] action    true for key was pressed, false for released
              * \param[in] key_sym   the key-name that caused the action
              * \param[in] key       the key code that caused the action
              * \param[in] alt       whether the alt key was pressed at the time where this event was triggered
              * \param[in] ctrl      whether the ctrl was pressed at the time where this event was triggered
              * \param[in] shift     whether the shift was pressed at the time where this event was triggered
              */
            KeyboardEvent (bool action, const std::string& key_sym, unsigned char key, bool alt, bool ctrl, bool shift);

            bool isAltPressed () const;
            bool isCtrlPressed () const;
            bool isShiftPressed () const;

            unsigned char getKeyCode () const;

            const String& getKeySym () const;
            bool keyDown () const;
            bool keyUp () const;

        protected:

            bool action_;
            unsigned int modifiers_;
            unsigned char key_code_;
            String key_sym_;
        };

        class CV_EXPORTS MouseEvent
        {
        public:
            enum Type { MouseMove = 1, MouseButtonPress, MouseButtonRelease, MouseScrollDown, MouseScrollUp, MouseDblClick } ;
            enum MouseButton { NoButton = 0, LeftButton, MiddleButton, RightButton, VScroll } ;

            MouseEvent (const Type& type, const MouseButton& button, const Point& p, bool alt, bool ctrl, bool shift);

            Type type;
            MouseButton button;
            Point pointer;
            unsigned int key_state;
        };

        class CV_EXPORTS Camera
        {
        public:
            Camera(float f_x, float f_y, float c_x, float c_y, const Size &window_size);
            Camera(const Vec2f &fov, const Size &window_size);
            Camera(const cv::Matx33f &K, const Size &window_size);
            Camera(const cv::Matx44f &proj, const Size &window_size);

            inline const Vec2d & getClip() const { return clip_; }
            inline void setClip(const Vec2d &clip) { clip_ = clip; }

            inline const Size & getWindowSize() const { return window_size_; }
            void setWindowSize(const Size &window_size);

            inline const Vec2f & getFov() const { return fov_; }
            inline void setFov(const Vec2f & fov) { fov_ = fov; }

            void computeProjectionMatrix(Matx44f &proj) const;

            static Camera KinectCamera(const Size &window_size);

        private:
            void init(float f_x, float f_y, float c_x, float c_y, const Size &window_size);

            Vec2d clip_;
            Vec2f fov_;
            Size window_size_;
            Vec2f principal_point_;
            Vec2f focal_;
        };

    } /* namespace viz */
} /* namespace cv */
<commit_msg>access focal length and principal point in camera<commit_after>#pragma once

#include <string>
#include <opencv2/core.hpp>
#include <opencv2/core/affine.hpp>

namespace cv
{
    typedef std::string String;

    namespace viz
    {
        class CV_EXPORTS Color : public Scalar
        {
        public:
            Color();
            Color(double gray);
            Color(double blue, double green, double red);

            Color(const Scalar& color);

            static Color black();
            static Color blue();
            static Color green();
            static Color cyan();

            static Color red();
            static Color magenta();
            static Color yellow();
            static Color white();

            static Color gray();
        };

        class CV_EXPORTS Mesh3d
        {
        public:

            Mat cloud, colors;
            Mat polygons;

            static cv::viz::Mesh3d loadMesh(const String& file);

        private:
            struct loadMeshImpl;
        };

        class CV_EXPORTS KeyboardEvent
        {
        public:
            static const unsigned int Alt   = 1;
            static const unsigned int Ctrl  = 2;
            static const unsigned int Shift = 4;

            /** \brief Constructor
              * \param[in] action    true for key was pressed, false for released
              * \param[in] key_sym   the key-name that caused the action
              * \param[in] key       the key code that caused the action
              * \param[in] alt       whether the alt key was pressed at the time where this event was triggered
              * \param[in] ctrl      whether the ctrl was pressed at the time where this event was triggered
              * \param[in] shift     whether the shift was pressed at the time where this event was triggered
              */
            KeyboardEvent (bool action, const std::string& key_sym, unsigned char key, bool alt, bool ctrl, bool shift);

            bool isAltPressed () const;
            bool isCtrlPressed () const;
            bool isShiftPressed () const;

            unsigned char getKeyCode () const;

            const String& getKeySym () const;
            bool keyDown () const;
            bool keyUp () const;

        protected:

            bool action_;
            unsigned int modifiers_;
            unsigned char key_code_;
            String key_sym_;
        };

        class CV_EXPORTS MouseEvent
        {
        public:
            enum Type { MouseMove = 1, MouseButtonPress, MouseButtonRelease, MouseScrollDown, MouseScrollUp, MouseDblClick } ;
            enum MouseButton { NoButton = 0, LeftButton, MiddleButton, RightButton, VScroll } ;

            MouseEvent (const Type& type, const MouseButton& button, const Point& p, bool alt, bool ctrl, bool shift);

            Type type;
            MouseButton button;
            Point pointer;
            unsigned int key_state;
        };

        class CV_EXPORTS Camera
        {
        public:
            Camera(float f_x, float f_y, float c_x, float c_y, const Size &window_size);
            Camera(const Vec2f &fov, const Size &window_size);
            Camera(const cv::Matx33f &K, const Size &window_size);
            Camera(const cv::Matx44f &proj, const Size &window_size);

            inline const Vec2d & getClip() const { return clip_; }
            inline void setClip(const Vec2d &clip) { clip_ = clip; }

            inline const Size & getWindowSize() const { return window_size_; }
            void setWindowSize(const Size &window_size);

            inline const Vec2f & getFov() const { return fov_; }
            inline void setFov(const Vec2f & fov) { fov_ = fov; }

            inline const Vec2f & getPrincipalPoint() const { return principal_point_; }
            inline const Vec2f & getFocalLength() const { return focal_; }

            void computeProjectionMatrix(Matx44f &proj) const;

            static Camera KinectCamera(const Size &window_size);

        private:
            void init(float f_x, float f_y, float c_x, float c_y, const Size &window_size);

            Vec2d clip_;
            Vec2f fov_;
            Size window_size_;
            Vec2f principal_point_;
            Vec2f focal_;
        };

    } /* namespace viz */
} /* namespace cv */
<|endoftext|>


<commit_before>#include <luabind/detail/typetraits.hpp>
#include <boost/static_assert.hpp>

using namespace luabind::detail;

struct tester {};

void test_type_traits()
{
	BOOST_STATIC_ASSERT(is_nonconst_reference<int&>::value);
	BOOST_STATIC_ASSERT(!is_nonconst_reference<const int&>::value);
	BOOST_STATIC_ASSERT(is_nonconst_reference<tester&>::value);
	BOOST_STATIC_ASSERT(!is_nonconst_reference<const tester&>::value);

	BOOST_STATIC_ASSERT(!is_const_reference<int&>::value);
	BOOST_STATIC_ASSERT(is_const_reference<const int&>::value);
	BOOST_STATIC_ASSERT(!is_const_reference<tester&>::value);
	BOOST_STATIC_ASSERT(is_const_reference<const tester&>::value);

	BOOST_STATIC_ASSERT(!is_const_pointer<int*>::value);
	BOOST_STATIC_ASSERT(is_const_pointer<const int*>::value);
	BOOST_STATIC_ASSERT(!is_const_pointer<tester*>::value);
	BOOST_STATIC_ASSERT(is_const_pointer<const tester*>::value);

	BOOST_STATIC_ASSERT(is_nonconst_pointer<int*>::value);
	BOOST_STATIC_ASSERT(!is_nonconst_pointer<const int*>::value);
	BOOST_STATIC_ASSERT(is_nonconst_pointer<tester*>::value);
	BOOST_STATIC_ASSERT(!is_nonconst_pointer<const tester*>::value);

	BOOST_STATIC_ASSERT(!is_const_reference<const tester>::value);
}
<commit_msg>*** empty log message ***<commit_after>#include <luabind/detail/typetraits.hpp>
#include <luabind/detail/is_indirect_const.hpp>
#include <luabind/detail/pointee_sizeof.hpp>
#include <boost/static_assert.hpp>

using namespace luabind;
using namespace luabind::detail;

struct tester {};

void test_type_traits()
{
	BOOST_STATIC_ASSERT(is_nonconst_reference<int&>::value);
	BOOST_STATIC_ASSERT(!is_nonconst_reference<const int&>::value);
	BOOST_STATIC_ASSERT(is_nonconst_reference<tester&>::value);
	BOOST_STATIC_ASSERT(!is_nonconst_reference<const tester&>::value);

	BOOST_STATIC_ASSERT(!is_const_reference<int&>::value);
	BOOST_STATIC_ASSERT(is_const_reference<const int&>::value);
	BOOST_STATIC_ASSERT(!is_const_reference<tester&>::value);
	BOOST_STATIC_ASSERT(is_const_reference<const tester&>::value);

	BOOST_STATIC_ASSERT(!is_const_pointer<int*>::value);
	BOOST_STATIC_ASSERT(is_const_pointer<const int*>::value);
	BOOST_STATIC_ASSERT(!is_const_pointer<tester*>::value);
	BOOST_STATIC_ASSERT(is_const_pointer<const tester*>::value);

	BOOST_STATIC_ASSERT(is_nonconst_pointer<int*>::value);
	BOOST_STATIC_ASSERT(!is_nonconst_pointer<const int*>::value);
	BOOST_STATIC_ASSERT(is_nonconst_pointer<tester*>::value);
	BOOST_STATIC_ASSERT(!is_nonconst_pointer<const tester*>::value);

	BOOST_STATIC_ASSERT(!is_const_reference<const tester>::value);

	BOOST_STATIC_ASSERT(!luabind::is_indirect_const<int&>::value);
	BOOST_STATIC_ASSERT(is_indirect_const<const int>::value);
	BOOST_STATIC_ASSERT(is_indirect_const<const int&>::value);
	BOOST_STATIC_ASSERT(!is_indirect_const<int*>::value);
	BOOST_STATIC_ASSERT(is_indirect_const<const int*>::value);
}
<|endoftext|>


<commit_before>#include <tiramisu/tiramisu.h>

#include "benchmarks.h"

using namespace tiramisu;

/**
 * Benchmark for BLAS GEMV
 *     out = a*A*x + b*y
 *
 *     A : is a M x N matrix
 *     x : is a size N vector
 *     y : is a size M vector
 *     a,b : are scalars
 *
 *     out : is a size M vector
**
We will make a tiramisu implementation of this code :
  for(int i=0; i<M; i++)
  {
    tmp=0;
    for(int j=0; j<N; j++){
      tmp+= A(i, j) * x(j)
    }
	tmp *= alpha
    result(i)= tmp + beta * y(i)
  }
*/

int main(int argc, char **argv)
{
    tiramisu::init("gemv");

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------
    constant MM("M", expr(M)), NN("N", expr(N));

    //Iteration variables
    var i("i", 0, MM), j("j", 0, NN);

    //Inputs
    input A("A", {i,j}, p_float64);
    input x("x", {j}, p_float64);
    input y("y", {i}, p_float64);
    input alpha("alpha", {}, p_float64);
    input beta("beta", {}, p_float64);

    //Computations
    computation result_init("result_init", {i}, expr(cast(p_float64, 0)), p_float64);
    computation sum_row("sum_row", {i,j}, p_float64);
    sum_row.set_expression(expr(sum_row(i, j-1) + A(i, j) * x(j)));
    computation mult_alpha("mult_alpha", {i}, expr(alpha(0)* sum_row(i, NN-1)), p_float64);
    computation add_y("add_y", {i}, expr(mult_alpha(i) + beta(0) * y(i)), p_float64);

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------
    add_y.after(mult_alpha, i);
    mult_alpha.after(sum_row, i);
    sum_row.after(result_init, i);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------
    //Input Buffers
    buffer buf_A("buf_A", {MM,NN}, p_float64, a_input);
    buffer buf_x("buf_x", {NN}, p_float64, a_input);
    buffer buf_y("buf_y", {MM}, p_float64, a_input);
    buffer buf_alpha("buf_alpha", {1}, p_float64, a_input);
    buffer buf_beta("buf_beta", {1}, p_float64, a_input);

    //Output Buffers
    buffer buf_result("buf_result", {MM}, p_float64, a_output);

    //Store inputs
    A.store_in(&buf_A);
    x.store_in(&buf_x);
    y.store_in(&buf_y);
    alpha.store_in(&buf_alpha);
    beta.store_in(&buf_beta);

    //Store computations
    result_init.store_in(&buf_result);
    sum_row.store_in(&buf_result, {i});
    mult_alpha.store_in(&buf_result);
    add_y.store_in(&buf_result);

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------
    tiramisu::codegen({&buf_A, &buf_x, &buf_y, &buf_alpha, &buf_beta, &buf_result}, "generated_gemv.o");

    return 0;
}
<commit_msg>Add optimizations to gemv blas function<commit_after>#include <tiramisu/tiramisu.h>

#include "benchmarks.h"

#define UNROLL_FACTOR 64

using namespace tiramisu;

/**
 * Benchmark for BLAS GEMV
 *     out = a*A*x + b*y
 *
 *     A : is a M x N matrix
 *     x : is a size N vector
 *     y : is a size M vector
 *     a,b : are scalars
 *
 *     out : is a size M vector
**
We will make a tiramisu implementation of this code :
  for(int i=0; i<M; i++)
  {
    tmp=0;
    for(int j=0; j<N; j++){
      tmp+= A(i, j) * x(j)
    }
	tmp *= alpha
    result(i)= tmp + beta * y(i)
  }
*/

int main(int argc, char **argv)
{
    tiramisu::init("gemv");

    // -------------------------------------------------------
    // Layer I
    // -------------------------------------------------------
    constant MM("M", expr(M)), NN("N", expr(N));

    //Iteration variables
    var i("i", 0, MM), j("j", 0, NN);

    //Inputs
    input A("A", {i,j}, p_float64);
    input x("x", {j}, p_float64);
    input y("y", {i}, p_float64);
    input alpha("alpha", {}, p_float64);
    input beta("beta", {}, p_float64);

    //Computations
    computation result_init("result_init", {i}, expr(cast(p_float64, 0)), p_float64);
    computation sum_row("sum_row", {i,j}, p_float64);
    sum_row.set_expression(expr(sum_row(i, j-1) + A(i, j) * x(j)));
    computation mult_alpha("mult_alpha", {i}, expr(alpha(0)* sum_row(i, NN-1)), p_float64);
    computation add_y("add_y", {i}, expr(mult_alpha(i) + beta(0) * y(i)), p_float64);

    // -------------------------------------------------------
    // Layer II
    // -------------------------------------------------------
    add_y.after(mult_alpha, i);
    mult_alpha.after(sum_row, i);
    sum_row.after(result_init, i);

	//Unrolling
    sum_row.unroll(j, UNROLL_FACTOR);
	//Parallelization
    sum_row.parallelize(i);

    // -------------------------------------------------------
    // Layer III
    // -------------------------------------------------------
    //Input Buffers
    buffer buf_A("buf_A", {MM,NN}, p_float64, a_input);
    buffer buf_x("buf_x", {NN}, p_float64, a_input);
    buffer buf_y("buf_y", {MM}, p_float64, a_input);
    buffer buf_alpha("buf_alpha", {1}, p_float64, a_input);
    buffer buf_beta("buf_beta", {1}, p_float64, a_input);

    //Output Buffers
    buffer buf_result("buf_result", {MM}, p_float64, a_output);

    //Store inputs
    A.store_in(&buf_A);
    x.store_in(&buf_x);
    y.store_in(&buf_y);
    alpha.store_in(&buf_alpha);
    beta.store_in(&buf_beta);

    //Store computations
    result_init.store_in(&buf_result);
    sum_row.store_in(&buf_result, {i});
    mult_alpha.store_in(&buf_result);
    add_y.store_in(&buf_result);

    // -------------------------------------------------------
    // Code Generation
    // -------------------------------------------------------
    tiramisu::codegen({&buf_A, &buf_x, &buf_y, &buf_alpha, &buf_beta, &buf_result}, "generated_gemv.o");

    return 0;
}
<|endoftext|>