<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <fc2d_clawpack46.H>
#include <fclaw2d_map.h>
#include <p4est_connectivity.h>

#include <forestclaw2d.H>
#include <amr_utils.H>
#include <fclaw2d_map_query.h>

#include <fclaw_register.h>

#include "interface_user.H"

typedef struct user_options
{
    int example;
    double rhol;
    double cl;
    double rhor;
    double cr;

    int is_registered;

} user_options_t;

static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
    user_options_t* user = (user_options_t*) package;

    /* [user] User options */
    sc_options_add_double (opt, 0, "rho", &user->rhol, 1.0, "[user] rho (left) [1]");
    sc_options_add_double (opt, 0, "bulk", &user->cl, 1.0, "[user] c (left) [1]");
    sc_options_add_double (opt, 0, "rho", &user->rhor, 4.0, "[user] rho (right) [4]");
    sc_options_add_double (opt, 0, "bulk", &user->cr, 0.5, "[user] c (right) [0.5]");

    user->is_registered = 1;
    return NULL;
}

static const fclaw_app_options_vtable_t options_vtable_user =
{
    options_register_user,
    NULL,
    NULL,
    NULL
};

static
void register_user_options (fclaw_app_t * app,
                            const char *configfile,
                            user_options_t* user)
{
    FCLAW_ASSERT (app != NULL);

    fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
                                user);
}

void run_program(fclaw_app_t* app)
{
    sc_MPI_Comm            mpicomm;

    /* Mapped, multi-block domain */
    p4est_connectivity_t     *conn = NULL;
    fclaw2d_domain_t	     *domain;
    fclaw2d_map_context_t    *cont = NULL;

    amr_options_t              *gparms;
#if 0
    fc2d_clawpack46_options_t  *clawpack_options;
    user_options_t             *user;
#endif

    mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
    gparms = fclaw_forestclaw_get_options(app);

#if 0
    clawpack_options = fc2d_clawpack46_get_options(app);
    user = (user_options_t*) fclaw_app_get_user(app);
#endif

    /* ---------------------------------------------------------- */
    /* Use [ax,bx]x[ay,by] */
    conn = p4est_connectivity_new_unitsquare();
    cont = fclaw2d_map_new_nomap();

    domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

    /* ---------------------------------------------------------- */
    fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO);
    fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);

    /* ---------------------------------------------------------- */
    init_domain_data(domain);
    fclaw2d_domain_set_app(domain,app);

#if 0
    set_domain_parms(domain,gparms);
    fc2d_clawpack46_set_options(domain,clawpack_options);

    link_problem_setup(domain,fc2d_clawpack46_setprob);

    link_regrid_functions(domain,interface_patch_tag4refinement,
                          interface_patch_tag4coarsening);
#endif

    interface_link_solvers(domain);

    /* ---------------------------------------------------------- */
    amrinit(&domain);
    amrrun(&domain);
    amrreset(&domain);

    /* ---------------------------------------------------------- */
    fclaw2d_map_destroy(cont);
}

int
main (int argc, char **argv)
{
    fclaw_app_t *app;
    int first_arg;
    fclaw_exit_type_t vexit;

    /* Options */
    sc_options_t                  *options;
    user_options_t                suser_options, *user = &suser_options;

    int retval;

    /* Initialize application */
    app = fclaw_app_new (&argc, &argv, user);

    /* Register packages */
    fclaw_forestclaw_register(app,"fclaw_options.ini");
    fc2d_clawpack46_register(app,"fclaw_options.ini");

    /* User defined options (defined above) */
    register_user_options (app, "fclaw_options.ini", user);

    /* Read configuration file(s) */
    options = fclaw_app_get_options (app);
    retval = fclaw_options_read_from_file(options);
    vexit =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

    link_app_to_clawpatch(app);

    if (!retval & !vexit)
    {
        run_program(app);
    }

    fclaw_forestclaw_destroy(app);
    fclaw_app_destroy (app);

    return 0;
}
<commit_msg>(interface) remove unused code<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <fc2d_clawpack46.H>
#include <fclaw2d_map.h>
#include <p4est_connectivity.h>

#include <forestclaw2d.H>
#include <amr_utils.H>
#include <fclaw2d_map_query.h>

#include <fclaw_register.h>

#include "interface_user.H"

typedef struct user_options
{
    int example;
    double rhol;
    double cl;
    double rhor;
    double cr;

    int is_registered;

} user_options_t;

static void *
options_register_user (fclaw_app_t * app, void *package, sc_options_t * opt)
{
    user_options_t* user = (user_options_t*) package;

    /* [user] User options */
    sc_options_add_double (opt, 0, "rho", &user->rhol, 1.0, "[user] rho (left) [1]");
    sc_options_add_double (opt, 0, "bulk", &user->cl, 1.0, "[user] c (left) [1]");
    sc_options_add_double (opt, 0, "rho", &user->rhor, 4.0, "[user] rho (right) [4]");
    sc_options_add_double (opt, 0, "bulk", &user->cr, 0.5, "[user] c (right) [0.5]");

    user->is_registered = 1;
    return NULL;
}

static const fclaw_app_options_vtable_t options_vtable_user =
{
    options_register_user,
    NULL,
    NULL,
    NULL
};

static
void register_user_options (fclaw_app_t * app,
                            const char *configfile,
                            user_options_t* user)
{
    FCLAW_ASSERT (app != NULL);

    fclaw_app_options_register (app,"user", configfile, &options_vtable_user,
                                user);
}

void run_program(fclaw_app_t* app)
{
    sc_MPI_Comm            mpicomm;

    /* Mapped, multi-block domain */
    p4est_connectivity_t     *conn = NULL;
    fclaw2d_domain_t	     *domain;
    fclaw2d_map_context_t    *cont = NULL;

    amr_options_t              *gparms;

    mpicomm = fclaw_app_get_mpi_size_rank (app, NULL, NULL);
    gparms = fclaw_forestclaw_get_options(app);

    /* ---------------------------------------------------------- */
    /* Use [ax,bx]x[ay,by] */
    conn = p4est_connectivity_new_unitsquare();
    cont = fclaw2d_map_new_nomap();

    domain = fclaw2d_domain_new_conn_map (mpicomm, gparms->minlevel, conn, cont);

    /* ---------------------------------------------------------- */
    fclaw2d_domain_list_levels(domain, FCLAW_VERBOSITY_INFO);
    fclaw2d_domain_list_neighbors(domain, FCLAW_VERBOSITY_DEBUG);

    /* ---------------------------------------------------------- */
    init_domain_data(domain);
    fclaw2d_domain_set_app(domain,app);

    interface_link_solvers(domain);

    /* ---------------------------------------------------------- */
    amrinit(&domain);
    amrrun(&domain);
    amrreset(&domain);

    /* ---------------------------------------------------------- */
    fclaw2d_map_destroy(cont);
}

int
main (int argc, char **argv)
{
    fclaw_app_t *app;
    int first_arg;
    fclaw_exit_type_t vexit;

    /* Options */
    sc_options_t                  *options;
    user_options_t                suser_options, *user = &suser_options;

    int retval;

    /* Initialize application */
    app = fclaw_app_new (&argc, &argv, user);

    /* Register packages */
    fclaw_forestclaw_register(app,"fclaw_options.ini");
    fc2d_clawpack46_register(app,"fclaw_options.ini");

    /* User defined options (defined above) */
    register_user_options (app, "fclaw_options.ini", user);

    /* Read configuration file(s) */
    options = fclaw_app_get_options (app);
    retval = fclaw_options_read_from_file(options);
    vexit =  fclaw_app_options_parse (app, &first_arg,"fclaw_options.ini.used");

    link_app_to_clawpatch(app);

    if (!retval & !vexit)
    {
        run_program(app);
    }

    fclaw_forestclaw_destroy(app);
    fclaw_app_destroy (app);

    return 0;
}
<|endoftext|>


<commit_before>extern "C"{
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
}
#include <string>
using namespace std;
extern "C" {
static char * ngx_http_mytest(ngx_conf_t *cf,ngx_command_t *cmd,void *conf);
static ngx_int_t ngx_http_mytest_handler(ngx_http_request_t *r);
}
static ngx_command_t ngx_http_mytest_commands[] ={
    {
        ngx_string("mytest"),
        NGX_HTTP_MAIN_CONF | NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | \
        NGX_HTTP_LMT_CONF | NGX_CONF_NOARGS,
        ngx_http_mytest,
        NGX_HTTP_LOC_CONF_OFFSET,
        0,
        NULL
    },
    ngx_null_command
};
static ngx_http_module_t ngx_http_mytest_module_ctx = {
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL
};
ngx_module_t ngx_http_mytest_module = {
    NGX_MODULE_V1,
    &ngx_http_mytest_module_ctx,
    ngx_http_mytest_commands,
    NGX_HTTP_MODULE,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NULL,
    NGX_MODULE_V1_PADDING
};
static ngx_int_t ngx_http_mytest_handler(ngx_http_request_t *r){
    if(!(r->method &(NGX_HTTP_GET | NGX_HTTP_HEAD))){
        return NGX_HTTP_NOT_ALLOWED;
    }
    ngx_int_t rc = ngx_http_discard_request_body(r);
    if (rc != NGX_OK){
        return rc;
    }
    ngx_str_t type = ngx_string("text/plain");
    string str("hello nima world");
    //ngx_str_t response = ngx_string("Hello World");
    ngx_str_t response ;
    response.data = (u_char *)str.data();
    response.len = str.length();
    r->headers_out.status = NGX_HTTP_OK;
    r->headers_out.content_length_n = response.len;
    r->headers_out.content_type = type;
    rc = ngx_http_send_header(r);
    if (rc == NGX_ERROR || rc > NGX_OK || r->header_only){
        return rc;
    }
    ngx_buf_t *b;
    b = ngx_create_temp_buf(r->pool,response.len);
    if(b == NULL){
        return NGX_HTTP_INTERNAL_SERVER_ERROR;
    }
    ngx_memcpy(b->pos,response.data,response.len);
    b->last = b->pos + response.len;
    b->last_buf = 1;
    ngx_chain_t out;
    out.buf = b;
    out.next = NULL;
    return ngx_http_output_filter(r,&out);
}
static char * ngx_http_mytest(ngx_conf_t *cf,ngx_command_t *cmd,void *conf){
    ngx_http_core_loc_conf_t *clcf;
    clcf = static_cast<ngx_http_core_loc_conf_t *> (static_cast<ngx_http_conf_ctx_t *>ngx_http_conf_get_module_loc_conf(cf,ngx_http_core_module));
    clcf->handler = ngx_http_mytest_handler;
    return NGX_CONF_OK;
}

<commit_msg>Delete ngx_http_mytest_module.cpp<commit_after><|endoftext|>


<commit_before>
#include "potentialfunctioncbspl.h"

PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_,
        const int ncutcoeff_, const double min_, const double max_) :
                        PotentialFunction(nlam_,min_,max_) {

    /* Here nlam_ is the total number of coeff values that are to be optimized
     * To ensure that potential and force go to zero smoothly near cut-off,
     * as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to
     * cut-off and beyond take a value of zero.
     *
     * Since region less than rmin is not sampled sufficiently for stability
     * first _nexcl coefficients are not optimized instead their values are
     * extrapolated from first statistically significant knot values near rmin
     */

    // number of break points = _lam.size() - 2
    _nbreak = _lam.size() - 2;

     _dr = ( _cut_off )/( double (_nbreak - 1) );

    // break point locations
    // since ncoeff = nbreak +2 , r values for last two coefficients are also
    // computed
    _rbreak.resize(_lam.size(),false);

    _rbreak.clear();

    for( int i = 0; i < _lam.size(); i++)
        _rbreak(i) = i*_dr;

    _nexcl = min( int( ( _min )/_dr ), _nbreak - 2 ) + 1;

    _ncutcoeff = ncutcoeff_;

    _M.resize(4,4,false);
    _M.clear();
    _M(0,0) =  1.0; _M(0,1) =  4.0; _M(0,2) =  1.0; _M(0,3) = 0.0;
    _M(1,0) = -3.0; _M(1,1) =  0.0; _M(1,2) =  3.0; _M(1,3) = 0.0;
    _M(2,0) =  3.0; _M(2,1) = -6.0; _M(2,2) =  3.0; _M(2,3) = 0.0;
    _M(3,0) = -1.0; _M(3,1) =  3.0; _M(3,2) = -3.0; _M(3,3) = 1.0;
    _M /= 6.0;

}

int PotentialFunctionCBSPL::getOptParamSize() const {

    return _lam.size() - _nexcl - _ncutcoeff;
}

void PotentialFunctionCBSPL::setParam(string filename) {

        Table param;
        param.Load(filename);

        _lam.clear();

        if( param.size() != _lam.size()) {

            throw std::runtime_error("Potential parameters size mismatch!\n"
                    "Check input parameter file \""
                    + filename + "\" \nThere should be "
                    + boost::lexical_cast<string>( _lam.size() ) + " parameters");
        } else {
            // force last _ncutcoeff to be zero
            for( int i = 0; i < _lam.size() - _ncutcoeff; i++){

                _rbreak(i) = param.x(i);
                _lam(i) = param.y(i);

            }

        }

    }

void PotentialFunctionCBSPL::SaveParam(const string& filename){

    extrapolExclParam();

    Table param;
    param.SetHasYErr(false);
    param.resize(_lam.size(), false);

    for (int i = 0; i < _lam.size(); i++){

        param.set(i, _rbreak(i), _lam(i), 'i');
    }

    param.Save(filename);

}

void PotentialFunctionCBSPL::SavePotTab(const string& filename,
        const double step) {

    extrapolExclParam();

    PotentialFunction::SavePotTab(filename,step);

}

void PotentialFunctionCBSPL::extrapolExclParam(){

    // extrapolate first _nexcl knot values using exponential extrapolation
    // u(r) = a * exp( b * r)
    // a = u0 * exp ( - m * r0/u0 )
    // b = m/u0
    // m = (u1-u0)/(r1-r0)

    double u0 = _lam(_nexcl);
    double r0 = _rbreak(_nexcl);
    double m = (_lam(_nexcl + 1) - _lam(_nexcl)) /
            (_rbreak(_nexcl + 1) - _rbreak(_nexcl));
    double a = u0 * exp(-m * r0 / u0);
    double b = m / u0;

    for (int i = 0; i < _nexcl; i++) {

        double r = _rbreak(i);
        double u = a * exp(b * r);
        _lam(i) = u;

    }

}

void PotentialFunctionCBSPL::setOptParam(const int i, const double val){

    _lam( i + _nexcl ) = val;

}

double PotentialFunctionCBSPL::getOptParam(const int i) const{

    return _lam( i + _nexcl );

}

double PotentialFunctionCBSPL::CalculateF (const double r) const {

    if( r >= _min && r <= _cut_off){

        ub::vector<double> R;
        ub::vector<double> B;

        int indx = min( int( r /_dr ) , _nbreak-2 );

        double rk = indx*_dr;

        double t = ( r - rk)/_dr;

        R.resize(4,false); R.clear();

        R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;

        ub::vector<double> RM = ub::prod(R,_M);

        B.resize(4,false); B.clear();

        B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2);
        B(3) = _lam(indx+3);

        double u = ub::inner_prod(B,RM);

        return u;

    } else {

        return 0.0;

    }

}
    // calculate first derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{

    // since first _nexcl parameters are not optimized for stability reasons
    //i = i + _nexcl;

    if ( r >= _min && r <= _cut_off ) {

        int indx = min( int( ( r )/_dr ), _nbreak-2 );

        if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){

            ub::vector<double> R;

            double rk = indx*_dr;

            double t = ( r - rk)/_dr;

            R.resize(4,false); R.clear();

            R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;

            ub::vector<double> RM = ub::prod(R,_M);

            return RM(i + _nexcl-indx);

        }else{

            return 0.0;

        }

    } else {

        return 0;

    }
}
    // calculate second derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j,
        const double r) const {

    // for cubic B-SPlines D2F is zero for all lamdas
    return 0.0;

}
<commit_msg>modified to save extrapolatated bspl knots with o flag<commit_after>
#include "potentialfunctioncbspl.h"

PotentialFunctionCBSPL::PotentialFunctionCBSPL(const int nlam_,
        const int ncutcoeff_, const double min_, const double max_) :
                        PotentialFunction(nlam_,min_,max_) {

    /* Here nlam_ is the total number of coeff values that are to be optimized
     * To ensure that potential and force go to zero smoothly near cut-off,
     * as suggested in Ref. PCCP, 11, 1901, 2009, coeff values leading up to
     * cut-off and beyond take a value of zero.
     *
     * Since region less than rmin is not sampled sufficiently for stability
     * first _nexcl coefficients are not optimized instead their values are
     * extrapolated from first statistically significant knot values near rmin
     */

    // number of break points = _lam.size() - 2
    _nbreak = _lam.size() - 2;

     _dr = ( _cut_off )/( double (_nbreak - 1) );

    // break point locations
    // since ncoeff = nbreak +2 , r values for last two coefficients are also
    // computed
    _rbreak.resize(_lam.size(),false);

    _rbreak.clear();

    for( int i = 0; i < _lam.size(); i++)
        _rbreak(i) = i*_dr;

    _nexcl = min( int( ( _min )/_dr ), _nbreak - 2 ) + 1;

    _ncutcoeff = ncutcoeff_;

    _M.resize(4,4,false);
    _M.clear();
    _M(0,0) =  1.0; _M(0,1) =  4.0; _M(0,2) =  1.0; _M(0,3) = 0.0;
    _M(1,0) = -3.0; _M(1,1) =  0.0; _M(1,2) =  3.0; _M(1,3) = 0.0;
    _M(2,0) =  3.0; _M(2,1) = -6.0; _M(2,2) =  3.0; _M(2,3) = 0.0;
    _M(3,0) = -1.0; _M(3,1) =  3.0; _M(3,2) = -3.0; _M(3,3) = 1.0;
    _M /= 6.0;

}

int PotentialFunctionCBSPL::getOptParamSize() const {

    return _lam.size() - _nexcl - _ncutcoeff;
}

void PotentialFunctionCBSPL::setParam(string filename) {

        Table param;
        param.Load(filename);

        _lam.clear();

        if( param.size() != _lam.size()) {

            throw std::runtime_error("Potential parameters size mismatch!\n"
                    "Check input parameter file \""
                    + filename + "\" \nThere should be "
                    + boost::lexical_cast<string>( _lam.size() ) + " parameters");
        } else {
            // force last _ncutcoeff to be zero
            for( int i = 0; i < _lam.size() - _ncutcoeff; i++){

                _rbreak(i) = param.x(i);
                _lam(i) = param.y(i);

            }

        }

    }

void PotentialFunctionCBSPL::SaveParam(const string& filename){

    extrapolExclParam();

    Table param;
    param.SetHasYErr(false);
    param.resize(_lam.size(), false);

    // write extrapolated knots with flat 'o'
    for (int i = 0; i < _nexcl; i++){

        param.set(i, _rbreak(i), _lam(i), 'o');
    }

    for (int i = _nexcl; i < _lam.size(); i++){

        param.set(i, _rbreak(i), _lam(i), 'i');
    }

    param.Save(filename);

}

void PotentialFunctionCBSPL::SavePotTab(const string& filename,
        const double step) {

    extrapolExclParam();

    PotentialFunction::SavePotTab(filename,step);

}

void PotentialFunctionCBSPL::extrapolExclParam(){

    // extrapolate first _nexcl knot values using exponential extrapolation
    // u(r) = a * exp( b * r)
    // a = u0 * exp ( - m * r0/u0 )
    // b = m/u0
    // m = (u1-u0)/(r1-r0)

    double u0 = _lam(_nexcl);
    double r0 = _rbreak(_nexcl);
    double m = (_lam(_nexcl + 1) - _lam(_nexcl)) /
            (_rbreak(_nexcl + 1) - _rbreak(_nexcl));
    double a = u0 * exp(-m * r0 / u0);
    double b = m / u0;

    for (int i = 0; i < _nexcl; i++) {

        double r = _rbreak(i);
        double u = a * exp(b * r);
        _lam(i) = u;

    }

}

void PotentialFunctionCBSPL::setOptParam(const int i, const double val){

    _lam( i + _nexcl ) = val;

}

double PotentialFunctionCBSPL::getOptParam(const int i) const{

    return _lam( i + _nexcl );

}

double PotentialFunctionCBSPL::CalculateF (const double r) const {

    if( r >= _min && r <= _cut_off){

        ub::vector<double> R;
        ub::vector<double> B;

        int indx = min( int( r /_dr ) , _nbreak-2 );

        double rk = indx*_dr;

        double t = ( r - rk)/_dr;

        R.resize(4,false); R.clear();

        R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;

        ub::vector<double> RM = ub::prod(R,_M);

        B.resize(4,false); B.clear();

        B(0) = _lam(indx); B(1) = _lam(indx+1); B(2) = _lam(indx+2);
        B(3) = _lam(indx+3);

        double u = ub::inner_prod(B,RM);

        return u;

    } else {

        return 0.0;

    }

}
    // calculate first derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateDF(const int i, const double r) const{

    // since first _nexcl parameters are not optimized for stability reasons
    //i = i + _nexcl;

    if ( r >= _min && r <= _cut_off ) {

        int indx = min( int( ( r )/_dr ), _nbreak-2 );

        if ( i + _nexcl >= indx && i + _nexcl <= indx+3 ){

            ub::vector<double> R;

            double rk = indx*_dr;

            double t = ( r - rk)/_dr;

            R.resize(4,false); R.clear();

            R(0) = 1.0; R(1) = t; R(2) = t*t; R(3) = t*t*t;

            ub::vector<double> RM = ub::prod(R,_M);

            return RM(i + _nexcl-indx);

        }else{

            return 0.0;

        }

    } else {

        return 0;

    }
}
    // calculate second derivative w.r.t. ith parameter
double PotentialFunctionCBSPL::CalculateD2F(const int i, const int j,
        const double r) const {

    // for cubic B-SPlines D2F is zero for all lamdas
    return 0.0;

}
<|endoftext|>


<commit_before>/**************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "crashhandler.h"
#include "crashhandlerdialog.h"
#include "ui_crashhandlerdialog.h"
#include "utils.h"

#include <app/app_version.h>
#include <utils/checkablemessagebox.h>

#include <QClipboard>
#include <QIcon>
#include <QSettings>

static const char SettingsApplication[] = "QtCreator";
static const char SettingsKeySkipWarningAbortingBacktrace[]
    = "CrashHandler/SkipWarningAbortingBacktrace";

CrashHandlerDialog::CrashHandlerDialog(CrashHandler *handler, const QString &signalName,
                                       QWidget *parent) :
    QDialog(parent),
    m_crashHandler(handler),
    m_ui(new Ui::CrashHandlerDialog)
{
    m_ui->setupUi(this);
    m_ui->introLabel->setTextFormat(Qt::RichText);
    m_ui->introLabel->setOpenExternalLinks(true);
    m_ui->debugInfoEdit->setReadOnly(true);
    m_ui->progressBar->setMinimum(0);
    m_ui->progressBar->setMaximum(0);

    const QStyle * const style = QApplication::style();
    m_ui->closeButton->setIcon(style->standardIcon(QStyle::SP_DialogCloseButton));

    const int iconSize = style->pixelMetric(QStyle::PM_MessageBoxIconSize, 0);
    QIcon icon = style->standardIcon(QStyle::SP_MessageBoxCritical);
    m_ui->iconLabel->setPixmap(icon.pixmap(iconSize, iconSize));

    connect(m_ui->copyToClipBoardButton, SIGNAL(clicked()), this, SLOT(copyToClipboardClicked()));
    connect(m_ui->reportBugButton, SIGNAL(clicked()), m_crashHandler, SLOT(openBugTracker()));
    connect(m_ui->debugAppButton, SIGNAL(clicked()), m_crashHandler, SLOT(debugApplication()));
    connect(m_ui->closeButton, SIGNAL(clicked()), this, SLOT(close()));

    setApplicationInfo(signalName);
}

CrashHandlerDialog::~CrashHandlerDialog()
{
    delete m_ui;
}

bool CrashHandlerDialog::runDebuggerWhileBacktraceNotFinished()
{
    // Check settings.
    QSettings settings(QSettings::IniFormat, QSettings::UserScope,
        QLatin1String(Core::Constants::IDE_SETTINGSVARIANT_STR),
        QLatin1String(SettingsApplication));
    if (settings.value(QLatin1String(SettingsKeySkipWarningAbortingBacktrace), false).toBool())
        return true;

    // Ask user.
    const QString title = tr("Run Debugger And Abort Collecting Backtrace?");
    const QString message = tr(
        ""
          "
Run the debugger and abort collecting backtrace?
"
          "
You have requested to run the debugger while collecting the backtrace was not "
          "finished.
"
        "");
    const QString checkBoxText = tr("Do not &ask again.");
    bool checkBoxSetting = false;
    const QDialogButtonBox::StandardButton button = Utils::CheckableMessageBox::question(this,
        title, message, checkBoxText, &checkBoxSetting,
        QDialogButtonBox::Yes|QDialogButtonBox::No, QDialogButtonBox::No);
    if (checkBoxSetting)
        settings.setValue(QLatin1String(SettingsKeySkipWarningAbortingBacktrace), checkBoxSetting);

    return button == QDialogButtonBox::Yes;
}

void CrashHandlerDialog::setToFinalState()
{
    m_ui->progressBar->hide();
    m_ui->copyToClipBoardButton->setEnabled(true);
    m_ui->reportBugButton->setEnabled(true);
}

void CrashHandlerDialog::disableRestartAppCheckBox()
{
    m_ui->restartAppCheckBox->setDisabled(true);
}

void CrashHandlerDialog::disableDebugAppButton()
{
    m_ui->debugAppButton->setDisabled(true);
}

void CrashHandlerDialog::setApplicationInfo(const QString &signalName)
{
    const QString ideName = QLatin1String("Qt Creator");
    const QString title = tr("%1 has closed unexpectedly (Signal \"%2\")").arg(ideName, signalName);
    const QString introLabelContents = tr(
        "
%1.
"
        "
Please file a bug report with the debug information provided below.
")
        .arg(title, QLatin1String(URL_BUGTRACKER));
    m_ui->introLabel->setText(introLabelContents);
    setWindowTitle(title);

    QString revision;
#ifdef IDE_REVISION
     revision = tr(" from revision %1").arg(QString::fromLatin1(Core::Constants::IDE_REVISION_STR).left(10));
#endif
    const QString versionInformation = tr(
        "%1 %2%3, built on %4 at %5, based on Qt %6 (%7 bit)\n")
            .arg(ideName, QLatin1String(Core::Constants::IDE_VERSION_LONG), revision,
                 QLatin1String(__DATE__), QLatin1String(__TIME__), QLatin1String(QT_VERSION_STR),
                 QString::number(QSysInfo::WordSize));
    m_ui->debugInfoEdit->append(versionInformation);
}

void CrashHandlerDialog::appendDebugInfo(const QString &chunk)
{
    m_ui->debugInfoEdit->append(chunk);
}

void CrashHandlerDialog::selectLineWithContents(const QString &text)
{
    // The selected line will be the first line visible.

    // Go to end.
    QTextCursor cursor = m_ui->debugInfoEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    m_ui->debugInfoEdit->setTextCursor(cursor);

    // Find text by searching backwards.
    m_ui->debugInfoEdit->find(text, QTextDocument::FindCaseSensitively | QTextDocument::FindBackward);

    // Highlight whole line.
    cursor = m_ui->debugInfoEdit->textCursor();
    cursor.select(QTextCursor::LineUnderCursor);
    m_ui->debugInfoEdit->setTextCursor(cursor);
}

void CrashHandlerDialog::copyToClipboardClicked()
{
    QApplication::clipboard()->setText(m_ui->debugInfoEdit->toPlainText());
}

void CrashHandlerDialog::close()
{
    if (m_ui->restartAppCheckBox->isEnabled() && m_ui->restartAppCheckBox->isChecked())
        m_crashHandler->restartApplication();
    qApp->quit();
}
<commit_msg>Fix Krazy warnings about includes/header guards in crash handler.<commit_after>/**************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "crashhandlerdialog.h"
#include "crashhandler.h"
#include "ui_crashhandlerdialog.h"
#include "utils.h"

#include <app/app_version.h>
#include <utils/checkablemessagebox.h>

#include <QClipboard>
#include <QIcon>
#include <QSettings>

static const char SettingsApplication[] = "QtCreator";
static const char SettingsKeySkipWarningAbortingBacktrace[]
    = "CrashHandler/SkipWarningAbortingBacktrace";

CrashHandlerDialog::CrashHandlerDialog(CrashHandler *handler, const QString &signalName,
                                       QWidget *parent) :
    QDialog(parent),
    m_crashHandler(handler),
    m_ui(new Ui::CrashHandlerDialog)
{
    m_ui->setupUi(this);
    m_ui->introLabel->setTextFormat(Qt::RichText);
    m_ui->introLabel->setOpenExternalLinks(true);
    m_ui->debugInfoEdit->setReadOnly(true);
    m_ui->progressBar->setMinimum(0);
    m_ui->progressBar->setMaximum(0);

    const QStyle * const style = QApplication::style();
    m_ui->closeButton->setIcon(style->standardIcon(QStyle::SP_DialogCloseButton));

    const int iconSize = style->pixelMetric(QStyle::PM_MessageBoxIconSize, 0);
    QIcon icon = style->standardIcon(QStyle::SP_MessageBoxCritical);
    m_ui->iconLabel->setPixmap(icon.pixmap(iconSize, iconSize));

    connect(m_ui->copyToClipBoardButton, SIGNAL(clicked()), this, SLOT(copyToClipboardClicked()));
    connect(m_ui->reportBugButton, SIGNAL(clicked()), m_crashHandler, SLOT(openBugTracker()));
    connect(m_ui->debugAppButton, SIGNAL(clicked()), m_crashHandler, SLOT(debugApplication()));
    connect(m_ui->closeButton, SIGNAL(clicked()), this, SLOT(close()));

    setApplicationInfo(signalName);
}

CrashHandlerDialog::~CrashHandlerDialog()
{
    delete m_ui;
}

bool CrashHandlerDialog::runDebuggerWhileBacktraceNotFinished()
{
    // Check settings.
    QSettings settings(QSettings::IniFormat, QSettings::UserScope,
        QLatin1String(Core::Constants::IDE_SETTINGSVARIANT_STR),
        QLatin1String(SettingsApplication));
    if (settings.value(QLatin1String(SettingsKeySkipWarningAbortingBacktrace), false).toBool())
        return true;

    // Ask user.
    const QString title = tr("Run Debugger And Abort Collecting Backtrace?");
    const QString message = tr(
        ""
          "
Run the debugger and abort collecting backtrace?
"
          "
You have requested to run the debugger while collecting the backtrace was not "
          "finished.
"
        "");
    const QString checkBoxText = tr("Do not &ask again.");
    bool checkBoxSetting = false;
    const QDialogButtonBox::StandardButton button = Utils::CheckableMessageBox::question(this,
        title, message, checkBoxText, &checkBoxSetting,
        QDialogButtonBox::Yes|QDialogButtonBox::No, QDialogButtonBox::No);
    if (checkBoxSetting)
        settings.setValue(QLatin1String(SettingsKeySkipWarningAbortingBacktrace), checkBoxSetting);

    return button == QDialogButtonBox::Yes;
}

void CrashHandlerDialog::setToFinalState()
{
    m_ui->progressBar->hide();
    m_ui->copyToClipBoardButton->setEnabled(true);
    m_ui->reportBugButton->setEnabled(true);
}

void CrashHandlerDialog::disableRestartAppCheckBox()
{
    m_ui->restartAppCheckBox->setDisabled(true);
}

void CrashHandlerDialog::disableDebugAppButton()
{
    m_ui->debugAppButton->setDisabled(true);
}

void CrashHandlerDialog::setApplicationInfo(const QString &signalName)
{
    const QString ideName = QLatin1String("Qt Creator");
    const QString title = tr("%1 has closed unexpectedly (Signal \"%2\")").arg(ideName, signalName);
    const QString introLabelContents = tr(
        "
%1.
"
        "
Please file a bug report with the debug information provided below.
")
        .arg(title, QLatin1String(URL_BUGTRACKER));
    m_ui->introLabel->setText(introLabelContents);
    setWindowTitle(title);

    QString revision;
#ifdef IDE_REVISION
     revision = tr(" from revision %1").arg(QString::fromLatin1(Core::Constants::IDE_REVISION_STR).left(10));
#endif
    const QString versionInformation = tr(
        "%1 %2%3, built on %4 at %5, based on Qt %6 (%7 bit)\n")
            .arg(ideName, QLatin1String(Core::Constants::IDE_VERSION_LONG), revision,
                 QLatin1String(__DATE__), QLatin1String(__TIME__), QLatin1String(QT_VERSION_STR),
                 QString::number(QSysInfo::WordSize));
    m_ui->debugInfoEdit->append(versionInformation);
}

void CrashHandlerDialog::appendDebugInfo(const QString &chunk)
{
    m_ui->debugInfoEdit->append(chunk);
}

void CrashHandlerDialog::selectLineWithContents(const QString &text)
{
    // The selected line will be the first line visible.

    // Go to end.
    QTextCursor cursor = m_ui->debugInfoEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    m_ui->debugInfoEdit->setTextCursor(cursor);

    // Find text by searching backwards.
    m_ui->debugInfoEdit->find(text, QTextDocument::FindCaseSensitively | QTextDocument::FindBackward);

    // Highlight whole line.
    cursor = m_ui->debugInfoEdit->textCursor();
    cursor.select(QTextCursor::LineUnderCursor);
    m_ui->debugInfoEdit->setTextCursor(cursor);
}

void CrashHandlerDialog::copyToClipboardClicked()
{
    QApplication::clipboard()->setText(m_ui->debugInfoEdit->toPlainText());
}

void CrashHandlerDialog::close()
{
    if (m_ui->restartAppCheckBox->isEnabled() && m_ui->restartAppCheckBox->isChecked())
        m_crashHandler->restartApplication();
    qApp->quit();
}
<|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 "remoting/host/desktop_process.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_channel_proxy.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_message.h"
#include "media/video/capture/screen/screen_capturer_fake.h"
#include "remoting/base/auto_thread.h"
#include "remoting/base/auto_thread_task_runner.h"
#include "remoting/host/chromoting_messages.h"
#include "remoting/host/desktop_process.h"
#include "remoting/host/host_exit_codes.h"
#include "remoting/host/host_mock_objects.h"
#include "remoting/protocol/protocol_mock_objects.h"
#include "testing/gmock_mutant.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using testing::_;
using testing::AnyNumber;
using testing::InSequence;
using testing::Return;

namespace remoting {

namespace {

class MockDaemonListener : public IPC::Listener {
 public:
  MockDaemonListener() {}
  virtual ~MockDaemonListener() {}

  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;

  MOCK_METHOD1(OnDesktopAttached, void(IPC::PlatformFileForTransit));
  MOCK_METHOD1(OnChannelConnected, void(int32));
  MOCK_METHOD0(OnChannelError, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockDaemonListener);
};

class MockNetworkListener : public IPC::Listener {
 public:
  MockNetworkListener() {}
  virtual ~MockNetworkListener() {}

  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;

  MOCK_METHOD1(OnDesktopAttached, void(IPC::PlatformFileForTransit));
  MOCK_METHOD1(OnChannelConnected, void(int32));
  MOCK_METHOD0(OnChannelError, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockNetworkListener);
};

bool MockDaemonListener::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(MockDaemonListener, message)
    IPC_MESSAGE_HANDLER(ChromotingDesktopDaemonMsg_DesktopAttached,
                        OnDesktopAttached)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  EXPECT_TRUE(handled);
  return handled;
}

bool MockNetworkListener::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;

  // TODO(alexeypa): handle received messages here.

  EXPECT_TRUE(handled);
  return handled;
}

}  // namespace

class DesktopProcessTest : public testing::Test {
 public:
  DesktopProcessTest();
  virtual ~DesktopProcessTest();

  // testing::Test overrides
  virtual void SetUp() OVERRIDE;
  virtual void TearDown() OVERRIDE;

  // MockDaemonListener mocks
  void ConnectNetworkChannel(IPC::PlatformFileForTransit desktop_process);
  void OnDesktopAttached(IPC::PlatformFileForTransit desktop_process);

  // Creates a DesktopEnvironment with a fake media::ScreenCapturer, to mock
  // DesktopEnvironmentFactory::Create().
  DesktopEnvironment* CreateDesktopEnvironment();

  // Creates a dummy EventExecutor, to mock
  // DesktopEnvironment::CreateEventExecutor().
  EventExecutor* CreateEventExecutor();

  // Creates a fake media::ScreenCapturer, to mock
  // DesktopEnvironment::CreateVideoCapturer().
  media::ScreenCapturer* CreateVideoCapturer();

  // Disconnects the daemon-to-desktop channel causing the desktop process to
  // exit.
  void DisconnectChannels();

  // Runs the desktop process code in a separate thread.
  void RunDesktopProcess();

  // Creates the desktop process and sends a crash request to it.
  void RunDeathTest();

  // Sends a crash request to the desktop process.
  void SendCrashRequest();

 protected:
  // The daemon's end of the daemon-to-desktop channel.
  scoped_ptr<IPC::ChannelProxy> daemon_channel_;

  // Delegate that is passed to |daemon_channel_|.
  MockDaemonListener daemon_listener_;

  // Runs the daemon's end of the channel.
  MessageLoop message_loop_;

  scoped_refptr<AutoThreadTaskRunner> io_task_runner_;

  // The network's end of the network-to-desktop channel.
  scoped_ptr<IPC::ChannelProxy> network_channel_;

  // Delegate that is passed to |network_channel_|.
  MockNetworkListener network_listener_;
};

DesktopProcessTest::DesktopProcessTest()
    : message_loop_(MessageLoop::TYPE_UI) {
}

DesktopProcessTest::~DesktopProcessTest() {
}

void DesktopProcessTest::SetUp() {
}

void DesktopProcessTest::TearDown() {
}

void DesktopProcessTest::ConnectNetworkChannel(
    IPC::PlatformFileForTransit desktop_process) {

#if defined(OS_POSIX)
  IPC::ChannelHandle channel_handle("", desktop_process);
#elif defined(OS_WIN)
  IPC::ChannelHandle channel_handle(desktop_process);
#endif  // defined(OS_WIN)

  daemon_channel_.reset(new IPC::ChannelProxy(
      channel_handle,
      IPC::Channel::MODE_CLIENT,
      &network_listener_,
      io_task_runner_));
}

void DesktopProcessTest::OnDesktopAttached(
    IPC::PlatformFileForTransit desktop_process) {
#if defined(OS_POSIX)
    DCHECK(desktop_process.auto_close);

    base::ClosePlatformFile(desktop_process.fd);
#endif  // defined(OS_POSIX)
}

DesktopEnvironment* DesktopProcessTest::CreateDesktopEnvironment() {
  MockDesktopEnvironment* desktop_environment = new MockDesktopEnvironment();
  EXPECT_CALL(*desktop_environment, CreateAudioCapturerPtr(_))
      .Times(0);
  EXPECT_CALL(*desktop_environment, CreateEventExecutorPtr(_, _))
      .Times(AnyNumber())
      .WillRepeatedly(
          InvokeWithoutArgs(this, &DesktopProcessTest::CreateEventExecutor));
  EXPECT_CALL(*desktop_environment, CreateVideoCapturerPtr(_, _))
      .Times(AnyNumber())
      .WillRepeatedly(
          InvokeWithoutArgs(this, &DesktopProcessTest::CreateVideoCapturer));
  return desktop_environment;
}

EventExecutor* DesktopProcessTest::CreateEventExecutor() {
  MockEventExecutor* event_executor = new MockEventExecutor();
  EXPECT_CALL(*event_executor, StartPtr(_));
  return event_executor;
}

media::ScreenCapturer* DesktopProcessTest::CreateVideoCapturer() {
  return new media::ScreenCapturerFake();
}

void DesktopProcessTest::DisconnectChannels() {
  daemon_channel_.reset();
  network_channel_.reset();
  io_task_runner_ = NULL;
}

void DesktopProcessTest::RunDesktopProcess() {
  base::RunLoop run_loop;
  base::Closure quit_ui_task_runner = base::Bind(
      base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask),
      message_loop_.message_loop_proxy(),
      FROM_HERE, run_loop.QuitClosure());
  scoped_refptr<AutoThreadTaskRunner> ui_task_runner = new AutoThreadTaskRunner(
      message_loop_.message_loop_proxy(), quit_ui_task_runner);

  io_task_runner_ = AutoThread::CreateWithType("IPC thread", ui_task_runner,
                                               MessageLoop::TYPE_IO);

  std::string channel_name = IPC::Channel::GenerateUniqueRandomChannelID();
  daemon_channel_.reset(new IPC::ChannelProxy(
      IPC::ChannelHandle(channel_name),
      IPC::Channel::MODE_SERVER,
      &daemon_listener_,
      io_task_runner_));

  scoped_ptr<MockDesktopEnvironmentFactory> desktop_environment_factory(
      new MockDesktopEnvironmentFactory());
  EXPECT_CALL(*desktop_environment_factory, CreatePtr())
      .Times(AnyNumber())
      .WillRepeatedly(Invoke(this,
                             &DesktopProcessTest::CreateDesktopEnvironment));
  EXPECT_CALL(*desktop_environment_factory, SupportsAudioCapture())
      .Times(AnyNumber())
      .WillRepeatedly(Return(false));

  DesktopProcess desktop_process(ui_task_runner, channel_name);
  EXPECT_TRUE(desktop_process.Start(
      desktop_environment_factory.PassAs<DesktopEnvironmentFactory>()));

  ui_task_runner = NULL;
  run_loop.Run();
}

void DesktopProcessTest::RunDeathTest() {
  InSequence s;
  EXPECT_CALL(daemon_listener_, OnChannelConnected(_));
  EXPECT_CALL(daemon_listener_, OnDesktopAttached(_))
      .WillOnce(DoAll(
          Invoke(this, &DesktopProcessTest::OnDesktopAttached),
          InvokeWithoutArgs(this, &DesktopProcessTest::SendCrashRequest)));

  RunDesktopProcess();
}

void DesktopProcessTest::SendCrashRequest() {
  tracked_objects::Location location = FROM_HERE;
  daemon_channel_->Send(new ChromotingDaemonDesktopMsg_Crash(
      location.function_name(), location.file_name(), location.line_number()));
}

// Launches the desktop process and waits when it connects back.
TEST_F(DesktopProcessTest, Basic) {
  InSequence s;
  EXPECT_CALL(daemon_listener_, OnChannelConnected(_));
  EXPECT_CALL(daemon_listener_, OnDesktopAttached(_))
      .WillOnce(DoAll(
          Invoke(this, &DesktopProcessTest::OnDesktopAttached),
          InvokeWithoutArgs(this, &DesktopProcessTest::DisconnectChannels)));

  RunDesktopProcess();
}

// Launches the desktop process and waits when it connects back.
TEST_F(DesktopProcessTest, ConnectNetworkChannel) {
  InSequence s;
  EXPECT_CALL(daemon_listener_, OnChannelConnected(_));
  EXPECT_CALL(daemon_listener_, OnDesktopAttached(_))
      .WillOnce(Invoke(this, &DesktopProcessTest::ConnectNetworkChannel));
  EXPECT_CALL(network_listener_, OnChannelConnected(_))
      .WillOnce(InvokeWithoutArgs(
          this, &DesktopProcessTest::DisconnectChannels));

  RunDesktopProcess();
}

// Run the desktop process and ask it to crash.
TEST_F(DesktopProcessTest, DeathTest) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";

  EXPECT_DEATH(RunDeathTest(), "");
}

}  // namespace remoting
<commit_msg>Added DesktopProcessTest.StartSessionAgent unit test verifying that a desktop session agent can be successfully started.<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 "remoting/host/desktop_process.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/message_loop.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_channel_proxy.h"
#include "ipc/ipc_listener.h"
#include "ipc/ipc_message.h"
#include "media/video/capture/screen/screen_capturer_fake.h"
#include "remoting/base/auto_thread.h"
#include "remoting/base/auto_thread_task_runner.h"
#include "remoting/host/chromoting_messages.h"
#include "remoting/host/desktop_process.h"
#include "remoting/host/host_exit_codes.h"
#include "remoting/host/host_mock_objects.h"
#include "remoting/protocol/protocol_mock_objects.h"
#include "testing/gmock_mutant.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using testing::_;
using testing::AnyNumber;
using testing::InSequence;
using testing::Return;

namespace remoting {

namespace {

class MockDaemonListener : public IPC::Listener {
 public:
  MockDaemonListener() {}
  virtual ~MockDaemonListener() {}

  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;

  MOCK_METHOD1(OnDesktopAttached, void(IPC::PlatformFileForTransit));
  MOCK_METHOD1(OnChannelConnected, void(int32));
  MOCK_METHOD0(OnChannelError, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockDaemonListener);
};

class MockNetworkListener : public IPC::Listener {
 public:
  MockNetworkListener() {}
  virtual ~MockNetworkListener() {}

  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE;

  MOCK_METHOD1(OnChannelConnected, void(int32));
  MOCK_METHOD0(OnChannelError, void());

  MOCK_METHOD0(OnDesktopEnvironmentCreated, void());

 private:
  DISALLOW_COPY_AND_ASSIGN(MockNetworkListener);
};

bool MockDaemonListener::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(MockDaemonListener, message)
    IPC_MESSAGE_HANDLER(ChromotingDesktopDaemonMsg_DesktopAttached,
                        OnDesktopAttached)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  EXPECT_TRUE(handled);
  return handled;
}

bool MockNetworkListener::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;

  // TODO(alexeypa): handle received messages here.

  EXPECT_TRUE(handled);
  return handled;
}

}  // namespace

class DesktopProcessTest : public testing::Test {
 public:
  DesktopProcessTest();
  virtual ~DesktopProcessTest();

  // testing::Test overrides
  virtual void SetUp() OVERRIDE;
  virtual void TearDown() OVERRIDE;

  // MockDaemonListener mocks
  void ConnectNetworkChannel(IPC::PlatformFileForTransit desktop_process);
  void OnDesktopAttached(IPC::PlatformFileForTransit desktop_process);

  // Creates a DesktopEnvironment with a fake media::ScreenCapturer, to mock
  // DesktopEnvironmentFactory::Create().
  DesktopEnvironment* CreateDesktopEnvironment();

  // Creates a dummy EventExecutor, to mock
  // DesktopEnvironment::CreateEventExecutor().
  EventExecutor* CreateEventExecutor();

  // Creates a fake media::ScreenCapturer, to mock
  // DesktopEnvironment::CreateVideoCapturer().
  media::ScreenCapturer* CreateVideoCapturer();

  // Disconnects the daemon-to-desktop channel causing the desktop process to
  // exit.
  void DisconnectChannels();

  // Posts DisconnectChannels() to |message_loop_|.
  void PostDisconnectChannels();

  // Runs the desktop process code in a separate thread.
  void RunDesktopProcess();

  // Creates the desktop process and sends a crash request to it.
  void RunDeathTest();

  // Sends a crash request to the desktop process.
  void SendCrashRequest();

  // Requests the desktop process to start the desktop session agent.
  void SendStartSessionAgent();

 protected:
  // The daemon's end of the daemon-to-desktop channel.
  scoped_ptr<IPC::ChannelProxy> daemon_channel_;

  // Delegate that is passed to |daemon_channel_|.
  MockDaemonListener daemon_listener_;

  // Runs the daemon's end of the channel.
  MessageLoop message_loop_;

  scoped_refptr<AutoThreadTaskRunner> io_task_runner_;

  // The network's end of the network-to-desktop channel.
  scoped_ptr<IPC::ChannelProxy> network_channel_;

  // Delegate that is passed to |network_channel_|.
  MockNetworkListener network_listener_;
};

DesktopProcessTest::DesktopProcessTest()
    : message_loop_(MessageLoop::TYPE_UI) {
}

DesktopProcessTest::~DesktopProcessTest() {
}

void DesktopProcessTest::SetUp() {
}

void DesktopProcessTest::TearDown() {
}

void DesktopProcessTest::ConnectNetworkChannel(
    IPC::PlatformFileForTransit desktop_process) {

#if defined(OS_POSIX)
  IPC::ChannelHandle channel_handle("", desktop_process);
#elif defined(OS_WIN)
  IPC::ChannelHandle channel_handle(desktop_process);
#endif  // defined(OS_WIN)

  network_channel_.reset(new IPC::ChannelProxy(
      channel_handle,
      IPC::Channel::MODE_CLIENT,
      &network_listener_,
      io_task_runner_));
}

void DesktopProcessTest::OnDesktopAttached(
    IPC::PlatformFileForTransit desktop_process) {
#if defined(OS_POSIX)
    DCHECK(desktop_process.auto_close);

    base::ClosePlatformFile(desktop_process.fd);
#endif  // defined(OS_POSIX)
}

DesktopEnvironment* DesktopProcessTest::CreateDesktopEnvironment() {
  MockDesktopEnvironment* desktop_environment = new MockDesktopEnvironment();
  EXPECT_CALL(*desktop_environment, CreateAudioCapturerPtr(_))
      .Times(0);
  EXPECT_CALL(*desktop_environment, CreateEventExecutorPtr(_, _))
      .Times(AnyNumber())
      .WillRepeatedly(
          InvokeWithoutArgs(this, &DesktopProcessTest::CreateEventExecutor));
  EXPECT_CALL(*desktop_environment, CreateVideoCapturerPtr(_, _))
      .Times(AnyNumber())
      .WillRepeatedly(
          InvokeWithoutArgs(this, &DesktopProcessTest::CreateVideoCapturer));

  // Notify the test that the desktop environment has been created.
  network_listener_.OnDesktopEnvironmentCreated();
  return desktop_environment;
}

EventExecutor* DesktopProcessTest::CreateEventExecutor() {
  MockEventExecutor* event_executor = new MockEventExecutor();
  EXPECT_CALL(*event_executor, StartPtr(_));
  return event_executor;
}

media::ScreenCapturer* DesktopProcessTest::CreateVideoCapturer() {
  return new media::ScreenCapturerFake();
}

void DesktopProcessTest::DisconnectChannels() {
  daemon_channel_.reset();
  network_channel_.reset();
  io_task_runner_ = NULL;
}

void DesktopProcessTest::PostDisconnectChannels() {
  message_loop_.PostTask(FROM_HERE, base::Bind(
      &DesktopProcessTest::DisconnectChannels, base::Unretained(this)));
}

void DesktopProcessTest::RunDesktopProcess() {
  base::RunLoop run_loop;
  base::Closure quit_ui_task_runner = base::Bind(
      base::IgnoreResult(&base::SingleThreadTaskRunner::PostTask),
      message_loop_.message_loop_proxy(),
      FROM_HERE, run_loop.QuitClosure());
  scoped_refptr<AutoThreadTaskRunner> ui_task_runner = new AutoThreadTaskRunner(
      message_loop_.message_loop_proxy(), quit_ui_task_runner);

  io_task_runner_ = AutoThread::CreateWithType("IPC thread", ui_task_runner,
                                               MessageLoop::TYPE_IO);

  std::string channel_name = IPC::Channel::GenerateUniqueRandomChannelID();
  daemon_channel_.reset(new IPC::ChannelProxy(
      IPC::ChannelHandle(channel_name),
      IPC::Channel::MODE_SERVER,
      &daemon_listener_,
      io_task_runner_));

  scoped_ptr<MockDesktopEnvironmentFactory> desktop_environment_factory(
      new MockDesktopEnvironmentFactory());
  EXPECT_CALL(*desktop_environment_factory, CreatePtr())
      .Times(AnyNumber())
      .WillRepeatedly(Invoke(this,
                             &DesktopProcessTest::CreateDesktopEnvironment));
  EXPECT_CALL(*desktop_environment_factory, SupportsAudioCapture())
      .Times(AnyNumber())
      .WillRepeatedly(Return(false));

  DesktopProcess desktop_process(ui_task_runner, channel_name);
  EXPECT_TRUE(desktop_process.Start(
      desktop_environment_factory.PassAs<DesktopEnvironmentFactory>()));

  ui_task_runner = NULL;
  run_loop.Run();
}

void DesktopProcessTest::RunDeathTest() {
  InSequence s;
  EXPECT_CALL(daemon_listener_, OnChannelConnected(_));
  EXPECT_CALL(daemon_listener_, OnDesktopAttached(_))
      .WillOnce(DoAll(
          Invoke(this, &DesktopProcessTest::OnDesktopAttached),
          InvokeWithoutArgs(this, &DesktopProcessTest::SendCrashRequest)));

  RunDesktopProcess();
}

void DesktopProcessTest::SendCrashRequest() {
  tracked_objects::Location location = FROM_HERE;
  daemon_channel_->Send(new ChromotingDaemonDesktopMsg_Crash(
      location.function_name(), location.file_name(), location.line_number()));
}

void DesktopProcessTest::SendStartSessionAgent() {
  // TODO(alexeypa): Fix DesktopProcess to use the desktop environment
  // to create the disconnect window instead of directly calling
  // DisconnectWindow::Create(). This will take care of "Uninteresting mock
  // function call" warnings printed when DisconnectWindow::Show() and
  // DisconnectWindow::Hide() are called.
  network_channel_->Send(new ChromotingNetworkDesktopMsg_StartSessionAgent(
      "user@domain/rest-of-jid"));
}

// Launches the desktop process and waits when it connects back.
TEST_F(DesktopProcessTest, Basic) {
  InSequence s;
  EXPECT_CALL(daemon_listener_, OnChannelConnected(_));
  EXPECT_CALL(daemon_listener_, OnDesktopAttached(_))
      .WillOnce(DoAll(
          Invoke(this, &DesktopProcessTest::OnDesktopAttached),
          InvokeWithoutArgs(this, &DesktopProcessTest::DisconnectChannels)));

  RunDesktopProcess();
}

// Launches the desktop process and waits when it connects back.
TEST_F(DesktopProcessTest, ConnectNetworkChannel) {
  InSequence s;
  EXPECT_CALL(daemon_listener_, OnChannelConnected(_));
  EXPECT_CALL(daemon_listener_, OnDesktopAttached(_))
      .WillOnce(Invoke(this, &DesktopProcessTest::ConnectNetworkChannel));
  EXPECT_CALL(network_listener_, OnChannelConnected(_))
      .WillOnce(InvokeWithoutArgs(
          this, &DesktopProcessTest::DisconnectChannels));

  RunDesktopProcess();
}

// Launches the desktop process, waits when it connects back and starts
// the desktop session agent.
TEST_F(DesktopProcessTest, StartSessionAgent) {
  {
    InSequence s;
    EXPECT_CALL(daemon_listener_, OnChannelConnected(_));
    EXPECT_CALL(daemon_listener_, OnDesktopAttached(_))
        .WillOnce(Invoke(this, &DesktopProcessTest::ConnectNetworkChannel));
    EXPECT_CALL(network_listener_, OnChannelConnected(_))
        .WillOnce(InvokeWithoutArgs(
            this, &DesktopProcessTest::SendStartSessionAgent));
  }

  EXPECT_CALL(network_listener_, OnDesktopEnvironmentCreated())
      .WillOnce(InvokeWithoutArgs(
          this, &DesktopProcessTest::PostDisconnectChannels));

  RunDesktopProcess();
}

// Run the desktop process and ask it to crash.
TEST_F(DesktopProcessTest, DeathTest) {
  testing::GTEST_FLAG(death_test_style) = "threadsafe";

  EXPECT_DEATH(RunDeathTest(), "");
}

}  // namespace remoting
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "PefDecoder.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

PefDecoder::PefDecoder(TiffIFD *rootIFD, FileMap* file) :
    RawDecoder(file), mRootIFD(rootIFD) {
      decoderVersion = 2;
}

PefDecoder::~PefDecoder(void) {
}

RawImage PefDecoder::decodeRaw() {
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS);

  if (data.empty())
    ThrowRDE("PEF Decoder: No image data found");

  TiffIFD* raw = data[0];

  int compression = raw->getEntry(COMPRESSION)->getInt();

  if (1 == compression) {
    decodeUncompressed(raw);
    return mRaw;
  }

  if (65535 != compression)
    ThrowRDE("PEF Decoder: Unsupported compression");

  TiffEntry *offsets = raw->getEntry(STRIPOFFSETS);
  TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS);

  if (offsets->count != 1) {
    ThrowRDE("PEF Decoder: Multiple Strips found: %u", offsets->count);
  }
  if (counts->count != offsets->count) {
    ThrowRDE("PEF Decoder: Byte count number does not match strip size: count:%u, strips:%u ", counts->count, offsets->count);
  }
  if (!mFile->isValid(offsets->getInt() + counts->getInt()))
    ThrowRDE("PEF Decoder: Truncated file.");

  uint32 width = raw->getEntry(IMAGEWIDTH)->getInt();
  uint32 height = raw->getEntry(IMAGELENGTH)->getInt();

  mRaw->dim = iPoint2D(width, height);
  mRaw->bpp = 2;
  mRaw->createData();
  try {
    PentaxDecompressor l(mFile, mRaw);
    l.decodePentax(mRootIFD, offsets->getInt(), counts->getInt());
  } catch (IOException e) {
    errors.push_back(_strdup(e.what()));
    // Let's ignore it, it may have delivered somewhat useful data.
  }

  return mRaw;
}

void PefDecoder::checkSupport(CameraMetaData *meta) {
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);
  if (data.empty())
    ThrowRDE("PEF Support check: Model name found");

  string make = data[0]->getEntry(MAKE)->getString();
  string model = data[0]->getEntry(MODEL)->getString();
  this->checkCameraSupported(meta, make, model, "");
}

void PefDecoder::decodeMetaData(CameraMetaData *meta) {
  mRaw->cfa.setCFA(CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE);
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);

  if (data.empty())
    ThrowRDE("PEF Meta Decoder: Model name found");

  TiffIFD* raw = data[0];

  string make = raw->getEntry(MAKE)->getString();
  string model = raw->getEntry(MODEL)->getString();

  setMetaData(meta, make, model, "");
}

} // namespace RawSpeed
<commit_msg>Add byte order hint to PEF uncompressed.<commit_after>#include "StdAfx.h"
#include "PefDecoder.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

PefDecoder::PefDecoder(TiffIFD *rootIFD, FileMap* file) :
    RawDecoder(file), mRootIFD(rootIFD) {
      decoderVersion = 2;
}

PefDecoder::~PefDecoder(void) {
}

RawImage PefDecoder::decodeRaw() {
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(STRIPOFFSETS);

  if (data.empty())
    ThrowRDE("PEF Decoder: No image data found");

  TiffIFD* raw = data[0];

  int compression = raw->getEntry(COMPRESSION)->getInt();

  if (1 == compression) {
    decodeUncompressed(raw, true);
    return mRaw;
  }

  if (65535 != compression)
    ThrowRDE("PEF Decoder: Unsupported compression");

  TiffEntry *offsets = raw->getEntry(STRIPOFFSETS);
  TiffEntry *counts = raw->getEntry(STRIPBYTECOUNTS);

  if (offsets->count != 1) {
    ThrowRDE("PEF Decoder: Multiple Strips found: %u", offsets->count);
  }
  if (counts->count != offsets->count) {
    ThrowRDE("PEF Decoder: Byte count number does not match strip size: count:%u, strips:%u ", counts->count, offsets->count);
  }
  if (!mFile->isValid(offsets->getInt() + counts->getInt()))
    ThrowRDE("PEF Decoder: Truncated file.");

  uint32 width = raw->getEntry(IMAGEWIDTH)->getInt();
  uint32 height = raw->getEntry(IMAGELENGTH)->getInt();

  mRaw->dim = iPoint2D(width, height);
  mRaw->bpp = 2;
  mRaw->createData();
  try {
    PentaxDecompressor l(mFile, mRaw);
    l.decodePentax(mRootIFD, offsets->getInt(), counts->getInt());
  } catch (IOException e) {
    errors.push_back(_strdup(e.what()));
    // Let's ignore it, it may have delivered somewhat useful data.
  }

  return mRaw;
}

void PefDecoder::checkSupport(CameraMetaData *meta) {
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);
  if (data.empty())
    ThrowRDE("PEF Support check: Model name found");

  string make = data[0]->getEntry(MAKE)->getString();
  string model = data[0]->getEntry(MODEL)->getString();
  this->checkCameraSupported(meta, make, model, "");
}

void PefDecoder::decodeMetaData(CameraMetaData *meta) {
  mRaw->cfa.setCFA(CFA_RED, CFA_GREEN, CFA_GREEN2, CFA_BLUE);
  vector<TiffIFD*> data = mRootIFD->getIFDsWithTag(MODEL);

  if (data.empty())
    ThrowRDE("PEF Meta Decoder: Model name found");

  TiffIFD* raw = data[0];

  string make = raw->getEntry(MAKE)->getString();
  string model = raw->getEntry(MODEL)->getString();

  setMetaData(meta, make, model, "");
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>#include <list>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
namespace edn {
  using std::cout;
  using std::endl;
  using std::string;
  using std::list;

  enum TokenType {
    TokenString,
    TokenAtom,
    TokenParen
  };

  struct EdnToken {
    TokenType type;
    int line;
    string value;
  };

  enum NodeType {
    EdnNil,
    EdnSymbol,
    EdnKeyword,
    EdnBool,
    EdnInt,
    EdnFloat,
    EdnString,
    EdnChar,

    EdnList,
    EdnVector,
    EdnMap,
    EdnSet,

    EdnDiscard,
    EdnTagged
  };

  struct EdnNode {
    NodeType type;
    int line;
    string value;
    list<EdnNode> values;
  };

  void createToken(TokenType type, int line, string value, list<EdnToken> &tokens) {
    EdnToken token;
    token.type = type;
    token.line = line;
    token.value = value;
    tokens.push_back(token);
  }

  //by default checks if first char is in range of chars
  bool strRangeIn(string str, const char* range, int start = 0, int stop = 1) {
    string strRange = str.substr(start, stop);
    return (std::strspn(strRange.c_str(), range) == strRange.length());
  }

  list<EdnToken> lex(string edn) {
    string::iterator it;
    int line = 1;
    char escapeChar = '\\';
    bool escaping = false;
    bool inString = false;
    string stringContent = "";
    bool inComment = false;
    string token = "";
    string paren = "";
    list<EdnToken> tokens;

    for (it = edn.begin(); it != edn.end(); ++it) {
      if (*it == '\n' || *it == '\r') line++;

      if (!inString && *it == ';' && !escaping) inComment = true;

      if (inComment) {
        if (*it == '\n') {
          inComment = false;
          if (token != "") {
              createToken(TokenAtom, line, token, tokens);
              token = "";
          }
          continue;
        }
      }

      if (*it == '"' && !escaping) {
        if (inString) {
          createToken(TokenString, line, stringContent, tokens);
          inString = false;
        } else {
          stringContent = "";
          inString = true;
        }
        continue;
      }

      if (inString) {
        if (*it == escapeChar && !escaping) {
          escaping = true;
          continue;
        }

        if (escaping) {
          escaping = false;
          if (*it == 't' || *it == 'n' || *it == 'f' || *it == 'r') stringContent += escapeChar;
        }
        stringContent += *it;
      } else if (*it == '(' || *it == ')' || *it == '[' || *it == ']' || *it == '{' ||
                 *it == '}' || *it == '\t' || *it == '\n' || *it == '\r' || *it == ' ' || *it == ',') {
        if (token != "") {
          createToken(TokenAtom, line, token, tokens);
          token = "";
        }
        if (*it == '(' || *it == ')' || *it == '[' || *it == ']' || *it == '{' || *it == '}') {
          paren = "";
          paren += *it;
          createToken(TokenParen, line, paren, tokens);
        }
      } else {
        if (escaping) {
          escaping = false;
        } else if (*it == escapeChar) {
          escaping = true;
        }

        if (token == "#_") {
          createToken(TokenAtom, line, token, tokens);
          token = "";
        }
        token += *it;
      }
    }
    if (token != "") {
      createToken(TokenAtom, line, token, tokens);
    }

    return tokens;
  }

  void uppercase(string &str) {
    std::transform(str.begin(), str.end(), str.begin(), ::toupper);
  }

  bool validSymbol(string value) {
    //first we uppercase the value
    uppercase(value);

    if (std::strspn(value.c_str(), "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.*+!-_?$%&=:#/") != value.length())
      return false;

    //if the value starts with a number that is not ok
    if (strRangeIn(value, "0123456789"))
      return false;

    //first char can not start with : # or / - but / by itself is valid
    if (strRangeIn(value, ":#/") && !(value.length() == 1 && value[0] == '/'))
      return false;

    //if the first car is - + or . then the next char must NOT be numeric, by by themselves they are valid
    if (strRangeIn(value, "-+.") && value.length() > 1 && strRangeIn(value, "0123456789", 1))
      return false;

    if (std::count(value.begin(), value.end(), '/') > 1)
      return false;

    return true;
  }

  bool validKeyword(string value) {
    return (value[0] == ':' && validSymbol(value.substr(1,value.length() - 1)));
  }

  bool validNil(string value) {
    return (value == "nil");
  }

  bool validBool(string value) {
    return (value == "true" || value == "false");
  }

  bool validInt(string value, bool allowSign = true) {
    //if we have a positive or negative symbol that is ok but remove it for testing
    if (strRangeIn(value, "-+") && value.length() > 1 && allowSign)
      value = value.substr(1, value.length() - 1);

    //if string ends with N or M that is ok, but remove it for testing
    if (strRangeIn(value, "NM", value.length() - 1, 1))
      value = value.substr(0, value.length() - 2);

    if (std::strspn(value.c_str(), "0123456789") != value.length())
      return false;

    return true;
  }

  bool validFloat(string value) {
    uppercase(value);

    string front;
    string back;
    int epos;
    int periodPos = value.find_first_of('.');
    if (periodPos) {
      front = value.substr(0, periodPos);
      back = value.substr(periodPos + 1);
    } else {
      front = "";
      back = value;
    }

    if(front == "" || validInt(front)) {
      epos = back.find_first_of('E');
      if(epos > -1) {
        //ends with E which is invalid
        if ((unsigned)epos == back.length() - 1) return false;

        //both the decimal and exponent should be valid - do not allow + or - on dec (pass false as arg to validInt)
        if (!validInt(back.substr(0, epos), false) || !validInt(back.substr(epos + 1))) return false;
      } else {
        //if back ends with M remove for validation
        if (strRangeIn(back, "M", back.length() - 1, 1))
          back = back.substr(0, back.length() - 1);

        if (!validInt(back, false)) return false;
      }
      return true;
    }

    return false;
  }

  bool validChar(string value) {
    return (value.at(0) == '\\' && value.length() == 2);
  }

  EdnNode handleAtom(EdnToken token) {
    EdnNode node;
    node.line = token.line;
    node.value = token.value;

    if (validNil(token.value))
      node.type = EdnNil;
    else if (token.type == TokenString)
      node.type = EdnString;
    else if (validChar(token.value))
      node.type = EdnChar;
    else if (validBool(token.value))
      node.type = EdnBool;
    else if (validInt(token.value))
      node.type = EdnInt;
    else if (validFloat(token.value))
      node.type = EdnFloat;
    else if (validKeyword(token.value))
      node.type = EdnKeyword;
    else if (validSymbol(token.value))
      node.type = EdnSymbol;
    else
      throw "Could not parse atom";

    return node;
  }

  EdnNode handleCollection(EdnToken token, list<EdnNode> values) {
    EdnNode node;
    node.line = token.line;
    node.values = values;

    if (token.value == "(") {
      node.type = EdnList;
    }
    else if (token.value == "[") {
      node.type = EdnVector;
    }
    if (token.value == "{") {
      node.type = EdnMap;
    }
    return node;
  }

  EdnNode handleTagged(EdnToken token, EdnNode value) {
    EdnNode node;
    node.line = token.line;

    string tagName = token.value.substr(1, token.value.length() - 1);
    if (tagName == "_") {
      node.type = EdnDiscard;
    } else if (tagName == "") {
      //special case where we return early as # { is a set - thus tagname is empty
      node.type = EdnSet;
      if (value.type != EdnMap) {
        throw "Was expection a { } after hash to build set";
      }
      node.values = value.values;
      return node;
    } else {
      node.type = EdnTagged;
    }

    if (!validSymbol(tagName)) {
      throw "Invalid tag name";
    }

    EdnToken symToken;
    symToken.type = TokenAtom;
    symToken.line = token.line;
    symToken.value = tagName;

    list<EdnNode> values;
    values.push_back(handleAtom(symToken));
    values.push_back(value);

    node.values = values;
    return node;
  }

  EdnToken shiftToken(list<EdnToken> &tokens) {
    EdnToken nextToken = tokens.front();
    tokens.pop_front();
    return nextToken;
  }

  EdnNode readAhead(EdnToken token, list<EdnToken> &tokens) {
    if (token.type == TokenParen) {

      EdnToken nextToken;
      list<EdnNode> L;
      string closeParen;
      if (token.value == "(") closeParen = ")";
      if (token.value == "[") closeParen = "]";
      if (token.value == "{") closeParen = "}";

      while (true) {
        if (tokens.empty()) throw "unexpected end of list";

        nextToken = shiftToken(tokens);

        if (nextToken.value == closeParen) {
          return handleCollection(token, L);
        } else {
          L.push_back(readAhead(nextToken, tokens));
        }
      }
    } else if (token.value == ")" || token.value == "]" || token.value == "}") {
      throw "Unexpected " + token.value;
    } else {
      if (token.value.at(0) == '#') {
        return handleTagged(token, readAhead(shiftToken(tokens), tokens));
      } else {
        return handleAtom(token);
      }
    }
  }

  string escapeQuotes(const string &before) {
    string after;
    after.reserve(before.length() + 4);

    for (string::size_type i = 0; i < before.length(); ++i) {
      switch (before[i]) {
        case '"':
        case '\\':
          after += '\\';
        default:
          after += before[i];
      }
    }
    return after;
  }

  string pprint(EdnNode node) {
    string output;
    if (node.type == EdnList || node.type == EdnSet || node.type == EdnVector || node.type == EdnMap) {
      string vals = "";
      for (list<EdnNode>::iterator it=node.values.begin(); it != node.values.end(); ++it) {
        if (vals.length() > 0) {
          vals += " ";
        }
        vals += pprint(*it);
      }

      if (node.type == EdnList) output = "(" + vals + ")";
      else if (node.type == EdnMap) output = "{" + vals + "}";
      else if (node.type == EdnVector) output = "[" + vals + "]";

      #ifdef DEBUG
        switch (node.type) {
          case EdnList: output = "<EdnList " + output + ">"; break;
          case EdnMap: output = "<EdnMap " + output + ">"; break;
          case EdnVector: output = "<EdnVector " + output + ">"; break;
          default: output = "<OTHER? " + output + ">"; break;
        }
        return output;
      #endif
    } else if (node.type == EdnTagged) {
      output = "#" + pprint(node.values.front()) + " " + pprint(node.values.back());
      #ifdef DEBUG
        return "<EdnTagged " + output + ">";
      #endif
    } else if (node.type == EdnString) {
      output = "\"" + escapeQuotes(node.value) + "\"";
      #ifdef DEBUG
        return "<EdnString " + output + ">";
      #endif
    } else {
      #ifdef DEBUG
        output = "<";
        switch (node.type) {
          case EdnSymbol: output += "EdnSymbol"; break;
          case EdnKeyword: output += "EdnKeyword"; break;
          case EdnInt: output += "EdnInt"; break;
          case EdnFloat: output += "EdnFloat"; break;
          case EdnChar: output += "EdnChar"; break;
          case EdnBool: output += "EdnBool"; break;
          case EdnNil: output += "EdnNil"; break;
          case EdnString: output += "EdnString"; break;
          case EdnTagged: output += "EdnTagged"; break;
          default: output += "Other"; break;
        }
        return output + " " + node.value + ">";
      #endif

      output = node.value;
    }
    return output;
  }

  EdnNode read(string edn) {
    list<EdnToken> tokens = lex(edn);

    if (tokens.size() == 0) {
      throw "No parsable tokens found in string";
    }

    return readAhead(shiftToken(tokens), tokens);
  }
}
<commit_msg>adding typeToString helper for debugging goodness<commit_after>#include <list>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
namespace edn {
  using std::cout;
  using std::endl;
  using std::string;
  using std::list;

  enum TokenType {
    TokenString,
    TokenAtom,
    TokenParen
  };

  struct EdnToken {
    TokenType type;
    int line;
    string value;
  };

  enum NodeType {
    EdnNil,
    EdnSymbol,
    EdnKeyword,
    EdnBool,
    EdnInt,
    EdnFloat,
    EdnString,
    EdnChar,

    EdnList,
    EdnVector,
    EdnMap,
    EdnSet,

    EdnDiscard,
    EdnTagged
  };

  struct EdnNode {
    NodeType type;
    int line;
    string value;
    list<EdnNode> values;
  };

  void createToken(TokenType type, int line, string value, list<EdnToken> &tokens) {
    EdnToken token;
    token.type = type;
    token.line = line;
    token.value = value;
    tokens.push_back(token);
  }

  string typeToString(NodeType type) {
    string output;
    switch (type) {
      case EdnSymbol:  output = "EdnSymbol";   break;
      case EdnKeyword: output = "EdnKeyword";  break;
      case EdnInt:     output = "EdnInt";      break;
      case EdnFloat:   output = "EdnFloat";    break;
      case EdnChar:    output = "EdnChar";     break;
      case EdnBool:    output = "EdnBool";     break;
      case EdnNil:     output = "EdnNil";      break;
      case EdnString:  output = "EdnString";   break;
      case EdnTagged:  output = "EdnTagged";   break;
      case EdnList:    output = "EdnList";     break;
      case EdnVector:  output = "EdnVector";   break;
      case EdnSet:     output = "EdnSet";      break;
      case EdnMap:     output = "EdnMap";      break;
      case EdnDiscard: output = "EdnDiscard";  break;
    }
    return output;
  }

  //by default checks if first char is in range of chars
  bool strRangeIn(string str, const char* range, int start = 0, int stop = 1) {
    string strRange = str.substr(start, stop);
    return (std::strspn(strRange.c_str(), range) == strRange.length());
  }

  list<EdnToken> lex(string edn) {
    string::iterator it;
    int line = 1;
    char escapeChar = '\\';
    bool escaping = false;
    bool inString = false;
    string stringContent = "";
    bool inComment = false;
    string token = "";
    string paren = "";
    list<EdnToken> tokens;

    for (it = edn.begin(); it != edn.end(); ++it) {
      if (*it == '\n' || *it == '\r') line++;

      if (!inString && *it == ';' && !escaping) inComment = true;

      if (inComment) {
        if (*it == '\n') {
          inComment = false;
          if (token != "") {
              createToken(TokenAtom, line, token, tokens);
              token = "";
          }
          continue;
        }
      }

      if (*it == '"' && !escaping) {
        if (inString) {
          createToken(TokenString, line, stringContent, tokens);
          inString = false;
        } else {
          stringContent = "";
          inString = true;
        }
        continue;
      }

      if (inString) {
        if (*it == escapeChar && !escaping) {
          escaping = true;
          continue;
        }

        if (escaping) {
          escaping = false;
          if (*it == 't' || *it == 'n' || *it == 'f' || *it == 'r') stringContent += escapeChar;
        }
        stringContent += *it;
      } else if (*it == '(' || *it == ')' || *it == '[' || *it == ']' || *it == '{' ||
                 *it == '}' || *it == '\t' || *it == '\n' || *it == '\r' || *it == ' ' || *it == ',') {
        if (token != "") {
          createToken(TokenAtom, line, token, tokens);
          token = "";
        }
        if (*it == '(' || *it == ')' || *it == '[' || *it == ']' || *it == '{' || *it == '}') {
          paren = "";
          paren += *it;
          createToken(TokenParen, line, paren, tokens);
        }
      } else {
        if (escaping) {
          escaping = false;
        } else if (*it == escapeChar) {
          escaping = true;
        }

        if (token == "#_") {
          createToken(TokenAtom, line, token, tokens);
          token = "";
        }
        token += *it;
      }
    }
    if (token != "") {
      createToken(TokenAtom, line, token, tokens);
    }

    return tokens;
  }

  void uppercase(string &str) {
    std::transform(str.begin(), str.end(), str.begin(), ::toupper);
  }

  bool validSymbol(string value) {
    //first we uppercase the value
    uppercase(value);

    if (std::strspn(value.c_str(), "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ.*+!-_?$%&=:#/") != value.length())
      return false;

    //if the value starts with a number that is not ok
    if (strRangeIn(value, "0123456789"))
      return false;

    //first char can not start with : # or / - but / by itself is valid
    if (strRangeIn(value, ":#/") && !(value.length() == 1 && value[0] == '/'))
      return false;

    //if the first car is - + or . then the next char must NOT be numeric, by by themselves they are valid
    if (strRangeIn(value, "-+.") && value.length() > 1 && strRangeIn(value, "0123456789", 1))
      return false;

    if (std::count(value.begin(), value.end(), '/') > 1)
      return false;

    return true;
  }

  bool validKeyword(string value) {
    return (value[0] == ':' && validSymbol(value.substr(1,value.length() - 1)));
  }

  bool validNil(string value) {
    return (value == "nil");
  }

  bool validBool(string value) {
    return (value == "true" || value == "false");
  }

  bool validInt(string value, bool allowSign = true) {
    //if we have a positive or negative symbol that is ok but remove it for testing
    if (strRangeIn(value, "-+") && value.length() > 1 && allowSign)
      value = value.substr(1, value.length() - 1);

    //if string ends with N or M that is ok, but remove it for testing
    if (strRangeIn(value, "NM", value.length() - 1, 1))
      value = value.substr(0, value.length() - 2);

    if (std::strspn(value.c_str(), "0123456789") != value.length())
      return false;

    return true;
  }

  bool validFloat(string value) {
    uppercase(value);

    string front;
    string back;
    int epos;
    int periodPos = value.find_first_of('.');
    if (periodPos) {
      front = value.substr(0, periodPos);
      back = value.substr(periodPos + 1);
    } else {
      front = "";
      back = value;
    }

    if(front == "" || validInt(front)) {
      epos = back.find_first_of('E');
      if(epos > -1) {
        //ends with E which is invalid
        if ((unsigned)epos == back.length() - 1) return false;

        //both the decimal and exponent should be valid - do not allow + or - on dec (pass false as arg to validInt)
        if (!validInt(back.substr(0, epos), false) || !validInt(back.substr(epos + 1))) return false;
      } else {
        //if back ends with M remove for validation
        if (strRangeIn(back, "M", back.length() - 1, 1))
          back = back.substr(0, back.length() - 1);

        if (!validInt(back, false)) return false;
      }
      return true;
    }

    return false;
  }

  bool validChar(string value) {
    return (value.at(0) == '\\' && value.length() == 2);
  }

  EdnNode handleAtom(EdnToken token) {
    EdnNode node;
    node.line = token.line;
    node.value = token.value;

    if (validNil(token.value))
      node.type = EdnNil;
    else if (token.type == TokenString)
      node.type = EdnString;
    else if (validChar(token.value))
      node.type = EdnChar;
    else if (validBool(token.value))
      node.type = EdnBool;
    else if (validInt(token.value))
      node.type = EdnInt;
    else if (validFloat(token.value))
      node.type = EdnFloat;
    else if (validKeyword(token.value))
      node.type = EdnKeyword;
    else if (validSymbol(token.value))
      node.type = EdnSymbol;
    else
      throw "Could not parse atom";

    return node;
  }

  EdnNode handleCollection(EdnToken token, list<EdnNode> values) {
    EdnNode node;
    node.line = token.line;
    node.values = values;

    if (token.value == "(") {
      node.type = EdnList;
    }
    else if (token.value == "[") {
      node.type = EdnVector;
    }
    if (token.value == "{") {
      node.type = EdnMap;
    }
    return node;
  }

  EdnNode handleTagged(EdnToken token, EdnNode value) {
    EdnNode node;
    node.line = token.line;

    string tagName = token.value.substr(1, token.value.length() - 1);
    if (tagName == "_") {
      node.type = EdnDiscard;
    } else if (tagName == "") {
      //special case where we return early as # { is a set - thus tagname is empty
      node.type = EdnSet;
      if (value.type != EdnMap) {
        throw "Was expection a { } after hash to build set";
      }
      node.values = value.values;
      return node;
    } else {
      node.type = EdnTagged;
    }

    if (!validSymbol(tagName)) {
      throw "Invalid tag name";
    }

    EdnToken symToken;
    symToken.type = TokenAtom;
    symToken.line = token.line;
    symToken.value = tagName;

    list<EdnNode> values;
    values.push_back(handleAtom(symToken));
    values.push_back(value);

    node.values = values;
    return node;
  }

  EdnToken shiftToken(list<EdnToken> &tokens) {
    EdnToken nextToken = tokens.front();
    tokens.pop_front();
    return nextToken;
  }

  EdnNode readAhead(EdnToken token, list<EdnToken> &tokens) {
    if (token.type == TokenParen) {

      EdnToken nextToken;
      list<EdnNode> L;
      string closeParen;
      if (token.value == "(") closeParen = ")";
      if (token.value == "[") closeParen = "]";
      if (token.value == "{") closeParen = "}";

      while (true) {
        if (tokens.empty()) throw "unexpected end of list";

        nextToken = shiftToken(tokens);

        if (nextToken.value == closeParen) {
          return handleCollection(token, L);
        } else {
          L.push_back(readAhead(nextToken, tokens));
        }
      }
    } else if (token.value == ")" || token.value == "]" || token.value == "}") {
      throw "Unexpected " + token.value;
    } else {
      if (token.value.at(0) == '#') {
        return handleTagged(token, readAhead(shiftToken(tokens), tokens));
      } else {
        return handleAtom(token);
      }
    }
  }

  string escapeQuotes(const string &before) {
    string after;
    after.reserve(before.length() + 4);

    for (string::size_type i = 0; i < before.length(); ++i) {
      switch (before[i]) {
        case '"':
        case '\\':
          after += '\\';
        default:
          after += before[i];
      }
    }
    return after;
  }

  string pprint(EdnNode node) {
    string output;
    if (node.type == EdnList || node.type == EdnSet || node.type == EdnVector || node.type == EdnMap) {
      string vals = "";
      for (list<EdnNode>::iterator it=node.values.begin(); it != node.values.end(); ++it) {
        if (vals.length() > 0) {
          vals += " ";
        }
        vals += pprint(*it);
      }

      if (node.type == EdnList) output = "(" + vals + ")";
      else if (node.type == EdnMap) output = "{" + vals + "}";
      else if (node.type == EdnVector) output = "[" + vals + "]";

      #ifdef DEBUG
        return "<" + typeToString(node.type) + " " + output + ">";
      #endif
    } else if (node.type == EdnTagged) {
      output = "#" + pprint(node.values.front()) + " " + pprint(node.values.back());
      #ifdef DEBUG
        return "<EdnTagged " + output + ">";
      #endif
    } else if (node.type == EdnString) {
      output = "\"" + escapeQuotes(node.value) + "\"";
      #ifdef DEBUG
        return "<EdnString " + output + ">";
      #endif
    } else {
      #ifdef DEBUG
        return "<" + typeToString(node.type) + " " + node.value + ">";
      #endif

      output = node.value;
    }
    return output;
  }

  EdnNode read(string edn) {
    list<EdnToken> tokens = lex(edn);

    if (tokens.size() == 0) {
      throw "No parsable tokens found in string";
    }

    return readAhead(shiftToken(tokens), tokens);
  }
}
<|endoftext|>


<commit_before>
#include "output.h"

Output::Output(){

    _output_interval=1.;
    _no_runs=1;
}

Output::Output(const Data& data){
    _output_interval=data.return_output_interval();
    _no_runs=data.return_no_runs();

}

void Output::save_data(double t, const Model& model){
    int i=t/_output_interval;
    // std::cout <<"debug: "<<t<<" "<<i<<" "<<_timepoints.size()<<" "<<_data.size()<<std::endl;
    datatype indat=model.return_all_cells();
    if (_timepoints.size()<=i){//_data[i] does not exist
        _timepoints.push_back(t);

        for (auto& x: indat){
            for (auto& y: (x)){
                (y)/=_no_runs;
            }
        }
        _data.push_back(indat);

    }
    else {
        datatype savedat=_data[i];

        for (int x =0; x< savedat.size();++x){
            for (int y=0; y<savedat[x].size();++y){
                savedat[x][y]+=indat[x][y]/_no_runs;
            }
        }

    }

}

void Output::output_at_timpoint(double time,std::ostream & os){

    int i=find_timepoint(time);
    if (i<0 || i >= _data.size()) throw std::invalid_argument( "invalid timpoint" );
    datatype outdata=_data[i];
        for (auto& x: outdata){
            for (auto& y: (x)){
                os <<y<<" ";
            }
            os <<std::endl;;
        }
}

int Output::find_timepoint(double t) const{
    int i =_timepoints.size()-1;
    while (i > 0 && _timepoints[i] > t) --i;
    return i;
}

void Output::save_all_timepoints(std::string basepath){
    if (basepath.empty()) basepath="./";
    // std::cout <<"debug output: "<<basepath<<std::endl;

    for (auto & t: _timepoints){
        std::stringstream filnamestream;
        filnamestream <<basepath<<t<<".dat";
        std::ofstream output;
        output.open(filnamestream.str().c_str());
        if (output.is_open()){
            output_at_timpoint(t,output);
            output.close();
        }
        else {
            std::cout <<"#cannot open "<<filnamestream.str()<<std::endl;
        }

    }

}
<commit_msg>Fixed output bug.<commit_after>
#include "output.h"

Output::Output(){

    _output_interval=1.;
    _no_runs=1;
}

Output::Output(const Data& data){
    _output_interval=data.return_output_interval();
    _no_runs=data.return_no_runs();

}

void Output::save_data(double t, const Model& model){
    int i=t/_output_interval;
    // std::cout <<"debug: "<<t<<" "<<i<<" "<<_timepoints.size()<<" "<<_data.size()<<std::endl;
    datatype indat=model.return_all_cells();
    if (_timepoints.size()<=i){//_data[i] does not exist
        _timepoints.push_back(t);

        for (auto& x: indat){
            for (auto& y: (x)){
                (y)/=_no_runs;
            }
        }
        _data.push_back(indat);

    }
    else {
        datatype& savedat=_data[i];

        for (int x =0; x< savedat.size();++x){
            for (int y=0; y<savedat[x].size();++y){
                savedat[x][y]+=indat[x][y]/_no_runs;
            }
        }

    }

}

void Output::output_at_timpoint(double time,std::ostream & os){

    int i=find_timepoint(time);
    if (i<0 || i >= _data.size()) throw std::invalid_argument( "invalid timpoint" );
    datatype outdata=_data[i];
        for (auto& x: outdata){
            for (auto& y: (x)){
                os <<y<<" ";
            }
            os <<std::endl;;
        }
}

int Output::find_timepoint(double t) const{
    int i =_timepoints.size()-1;
    while (i > 0 && _timepoints[i] > t) --i;
    return i;
}

void Output::save_all_timepoints(std::string basepath){
    if (basepath.empty()) basepath="./";
    // std::cout <<"debug output: "<<basepath<<std::endl;

    for (auto & t: _timepoints){
        std::stringstream filnamestream;
        filnamestream <<basepath<<t<<".dat";
        std::ofstream output;
        output.open(filnamestream.str().c_str());
        if (output.is_open()){
            output_at_timpoint(t,output);
            output.close();
        }
        else {
            std::cout <<"#cannot open "<<filnamestream.str()<<std::endl;
        }

    }

}
<|endoftext|>


<commit_before>
/*
 * 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.
 */

/*
 * $Id$
 */

#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/AtomicOpManagers/MacOSAtomicOpMgr.hpp>

#include <CoreServices/CoreServices.h>

XERCES_CPP_NAMESPACE_BEGIN

MacOSAtomicOpMgr::MacOSAtomicOpMgr()
{
}

MacOSAtomicOpMgr::~MacOSAtomicOpMgr()
{
}

// Atomic operations
void*
MacOSAtomicOpMgr::compareAndSwap(void**            toFill
							 , const void* const newValue
							 , const void* const toCompare)
{
    // Replace *toFill with newValue iff *toFill == toCompare,
    // returning previous value of *toFill

    Boolean success = CompareAndSwap(
        reinterpret_cast<UInt32>(toCompare),
        reinterpret_cast<UInt32>(newValue),
        reinterpret_cast<UInt32*>(toFill));

    return (success) ? const_cast<void*>(toCompare) : *toFill;
}

//
//	Atomic Increment and Decrement
//
//	Apple's routines return the value as it was before the
//	operation, while these routines want to return it as it
//	is after. So we perform the translation before returning
//	the value.
//
int
MacOSAtomicOpMgr::increment(int &location)
{
    return IncrementAtomic(reinterpret_cast<long*>(&location)) + 1;
}

int
MacOSAtomicOpMgr::decrement(int &location)
{
    return DecrementAtomic(reinterpret_cast<long*>(&location)) - 1;
}

XERCES_CPP_NAMESPACE_END
<commit_msg>Use OSAtomic routines, rather than DriverSyncronization routines, for compatibility with 64 bit pointers when we're being used on a 64 bit architecture.<commit_after>
/*
 * 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.
 */

/*
 * $Id$
 */

#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/AtomicOpManagers/MacOSAtomicOpMgr.hpp>

#include <libkern/OSAtomic.h>

XERCES_CPP_NAMESPACE_BEGIN

MacOSAtomicOpMgr::MacOSAtomicOpMgr()
{
}

MacOSAtomicOpMgr::~MacOSAtomicOpMgr()
{
}

// Atomic operations
void*
MacOSAtomicOpMgr::compareAndSwap(void**            toFill
							 , const void* const newValue
							 , const void* const toCompare)
{
    // Replace *toFill with newValue iff *toFill == toCompare,
    // returning previous value of *toFill
    bool success = OSAtomicCompareAndSwapPtrBarrier(
    	const_cast<void*>(toCompare),
    	const_cast<void*>(newValue),
    	toFill
    	);

    return (success) ? const_cast<void*>(toCompare) : *toFill;
}

//
//	Atomic Increment and Decrement
//
//	The return value is the value following the increment or decrement operation
//
int
MacOSAtomicOpMgr::increment(int &location)
{
    return OSAtomicIncrement32Barrier(reinterpret_cast<int32_t*>(&location));
}

int
MacOSAtomicOpMgr::decrement(int &location)
{
    return OSAtomicDecrement32Barrier(reinterpret_cast<int32_t*>(&location));
}

XERCES_CPP_NAMESPACE_END
<|endoftext|>