<commit_before>//
//  main.cpp
//  Agile_RRT
//
//  Created by Timothy Caldwell.
//  Copyright (c) 2015 Timothy Caldwell. Refer to license.txt
//
//  AgileRRT motion plans the highly dynamic 3-link pendulum on a cart. It executes the rapidly exploring random tree using LQR-based steering with linearization about the zero-control trajectory.
//
//  Arguments: (default value given right of '=' sign)
//    t_h_max_upper = 1.0       | Max time horizon.
//    usezerotraj = true        | Choose linearization for steering: true -> Linearization about zero-control trajectory.
//                                                                   false -> Linearization about vertex x0.
//    max_cnt = 1000            | Max number of successful insertions into the tree. RRT ends if max_cnt reached.
//    max_miss = 1000           | Max number of failed insertions into the tree. RRT ends if max_miss reached.
//    max_samplemiss = 10000    | Max number of failed attempts to find a
//    numbruns = 1              | Number of runs of the RRT. Run more to get more statistics.
//    stopdist = 2.0            | Stops RRT if a point is explored within a ball of radius stopdist from the goal state.
//    printskip = 1             | Number of loops of the RRT to skip between printing details to standard out.
//    nndelta = LARGENUM        | Nearest Neighbor ball radius for quickly checking
//    stats_name = "0"          | Filename to store statistics as a csv. Use "0" or no arg to not make file.
//    traj_name = "0"           | Filename to store tree trajectories easily readable by Mathematica. Use "0" or no arg to not make file
//    seed = 0                  | To choose the seed to the random number generator

#include "global.h"
#include "interp.h"
#include "system.h"
#include "pendcart_3link.h"
#include "treevertex.h"
#include "tree.h"
//#include "rrtreach.h"

// Struct for all options given as inputs through arguments.
struct inputs_struct {
  double t_h_max_upper = 1.0;
  bool usezerotraj = true;
  int max_cnt = 1000;
  int max_miss = 1000;
  int max_samplemiss = 10000;
  int numbruns = 1;
  double stopdist = 0.0;
  bool computexxgoaldist = false;
  int printskip = 1;
  double nndelta = kLARGENUM;
  ofstream stats_f, traj_f;
  bool is_stats_out = false;
  bool is_traj_out = false;
  bool save_edges = false;
  double seed = 0.0;
};
// Parses arguments (see top comment for information) into inputs struct.
void SpecifyInputs(int argc, const char * argv[], inputs_struct * inputs);
// Initializes the system state and control bounds and circular obstacle constraints.
void SpecifyConstraints(sampling_bounds_struct * bounds, constraints_struct * constraints);
// Initializes quadratic cost function gains QQ, RR, P1 based on the specified state and control bounds.
// Cost function has form (using Latex syntax) J = 0.5 \int_0^{th}xx^T*QQ*xx + uu^T*RR*uu dt + 0.5*xx(th)^T*P1*xx(th).
// RRinv is the matrix inverse of RR.
void SpecifyCostGains(const sampling_bounds_struct & bounds, NSxNS_type * QQ, NIxNI_type * RR, NIxNI_type * RRinv, NSxNS_type * P1);
// Sets root trajectory to the tree to be the free trajectory for the duration of the max time horizon.
void SpecifyRootTrajectory(const ode_state_type & x0, double t_h_max_upper, InterpVector * xx_interp, InterpVector * uu_interp);
// Execute the RRT for the number of runs numbruns specified.
void Execute(const sampling_bounds_struct & bounds, TreeVertex * init_vert, inputs_struct * inputs) {
  clock_t t_start2 = clock();
  Tree tree(init_vert, inputs->t_h_max_upper, bounds, inputs->max_cnt, inputs->max_miss, inputs->max_samplemiss, inputs->printskip, inputs->seed);

  if (inputs->computexxgoaldist) {
    NSx1_type xxgoal;
    xxgoal << 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 6.0 , 0.0;
    tree.set_xxgoal_stopdist (inputs->stopdist, xxgoal);
  }

  tree.set_nndelta(inputs->nndelta);

  double meancnt = 0;
  double meanmiss = 0;
  double meandist = 0;
  double meansamplemiss = 0;
  int numbxxgoalfails = 0;
  for (int ii = 0; ii < inputs->numbruns; ++ii) {
    cout << " ########################### " << endl;
    cout << "           ii = " << ii << endl;
    cout << " ########################### " << endl;

    tree.RunRRT();

    meandist += tree.get_disttogoal()/inputs->numbruns;
    meancnt += double(tree.get_cnttot())/inputs->numbruns;
    meanmiss += double(tree.get_misstot())/inputs->numbruns;
    meansamplemiss += double(tree.get_samplemisstot())/inputs->numbruns;

    if (tree.get_disttogoal() > inputs->stopdist)
      numbxxgoalfails++;

    if (inputs->is_traj_out)
      tree.Print( 0.02, "tree_"+to_string(ii), &inputs->traj_f);

    tree.ResetTree();
  }
  cout << "mean dist is: " << meandist << endl;
  cout << "mean cnt is: " << meancnt << endl;
  cout << "mean miss is: " << meanmiss << endl;
  cout << "mean sample miss is: " << meansamplemiss << endl;
  cout << "mean run time: " << ((float)(clock()-t_start2))/CLOCKS_PER_SEC/inputs->numbruns << " seconds." << endl;
  cout << "number of xxgoal fails: " << numbxxgoalfails << endl;

  if (inputs->is_stats_out) {
    inputs->stats_f << "meandist, " << meandist << endl;
    inputs->stats_f << "meancnt, " << meancnt << endl;
    inputs->stats_f << "meanmiss, " << meanmiss << endl;
    inputs->stats_f << "meansamplemiss, " << meansamplemiss << endl;
    inputs->stats_f << "meanruntime, " << ((float)(clock()-t_start2))/CLOCKS_PER_SEC/inputs->numbruns << endl;
    inputs->stats_f << "numbxxgoalsfails, " << numbxxgoalfails << endl;
    inputs->stats_f.close();
  }
  if ( inputs->is_traj_out ) {
    inputs->traj_f << "}";
    inputs->traj_f.close();
  }
}

int main(int argc, const char * argv[])
{
  inputs_struct inputs;
  SpecifyInputs(argc, argv, &inputs);

  // The initial conditions
  ode_state_type x0 = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };

  // Set bounds and constraints.
  sampling_bounds_struct bounds;
  constraints_struct constraints;
  SpecifyConstraints(&bounds, &constraints);

  // Set cost gains.
  NSxNS_type QQ, P1;
  NIxNI_type RR, RRinv;
  SpecifyCostGains(bounds, &QQ, &RR, &RRinv, &P1);

  // Set root trajectory to free dynamics.
  InterpVector * xx_interp = nullptr;
  InterpVector * uu_interp = nullptr;
  SpecifyRootTrajectory(x0, inputs.t_h_max_upper, xx_interp, uu_interp);

  // Create initial vertex.
  TreeVertex * init_vert = new TreeVertex(x0, inputs.usezerotraj, inputs.t_h_max_upper, *xx_interp, *uu_interp, constraints, QQ, RR, P1, QQ, RR, P1, inputs.t_h_max_upper, inputs.save_edges);

  Execute(bounds, init_vert, &inputs);
}

void SpecifyInputs(int argc, const char * argv[], inputs_struct * inputs) {
  if (argc > 1)
    sscanf(argv[1], "%lf", &inputs->t_h_max_upper);
  if (argc > 2)
    if ( strcmp(argv[2],"false") == 0 ) // anything besides false is assumed true
        inputs->usezerotraj = false;
  if (argc > 3)
    sscanf(argv[3], "%d", &inputs->max_cnt);
  if (argc > 4)
    sscanf(argv[4], "%d", &inputs->max_miss);
  if (argc > 5)
    sscanf(argv[5], "%d", &inputs->max_samplemiss);
  if (argc > 6)
    sscanf(argv[6], "%d", &inputs->numbruns);
  if (argc > 7) {
    sscanf(argv[7], "%lf", &inputs->stopdist);
    if (inputs->stopdist != 0)
      inputs->computexxgoaldist = true;
  }
  if (argc > 8)
    sscanf(argv[8], "%d", &inputs->printskip);
  if (argc > 9)
    sscanf(argv[9], "%lf", &inputs->nndelta);
  if (argc > 10) {
    if ( strcmp(argv[10],"0") != 0 ) {
      inputs->stats_f.open(argv[10], ios::trunc);
      inputs->is_stats_out = true;
    }
  }
  if (argc > 11) {
    if ( strcmp(argv[11],"0") != 0 ) {
      inputs->traj_f.open(argv[11], ios::trunc);
      inputs->traj_f << "{" << argv[11];
      inputs->is_traj_out = true;
      inputs->save_edges = true;
    }
  }
  if (argc > 12)
    sscanf(argv[12], "%lf", &inputs->seed);
}

void SpecifyConstraints(sampling_bounds_struct * bounds, constraints_struct * constraints) {
  // Sets upper and lower boundaries of state and control
  double bounds_delta = 10;
  bounds->xbounds << -2.0 * M_PI    , 2.0 * M_PI,
                -bounds_delta * M_PI * 0.5   , bounds_delta * M_PI * 0.5,
                -2.0 * M_PI    , 2.0 * M_PI,
                -bounds_delta * M_PI * 0.5   , bounds_delta * M_PI * 0.5,
                -2.0 * M_PI    , 2.0 * M_PI,
                -bounds_delta * M_PI * 0.5   , bounds_delta * M_PI * 0.5,
                -1.0                       , 8.0,
                -bounds_delta * 1.5          ,bounds_delta * 1.5;
  bounds->ubounds << -20.0 , 20.0;

  constraints->xbounds = bounds->xbounds;
  constraints->ubounds = bounds->ubounds;

  // Circular obstacle details
  constraints->obs_radii = { 0.6, 0.6 };
  constraints->obs_Xs = { 3.0, 3.0 };
  constraints->obs_Ys = { 0.85, -0.85 };
}

void SpecifyCostGains(const sampling_bounds_struct & bounds, NSxNS_type * QQ, NIxNI_type * RR, NIxNI_type * RRinv, NSxNS_type * P1) {
  *QQ = NSxNS_type::Zero();
  for (int ii = 0; ii< NS; ++ii)
    (*QQ)(ii, ii) = 1/pow((bounds.xbounds(ii,1) - bounds.xbounds(ii,0))/2,2);
  *RRinv = NIxNI_type::Zero();
  *RR = NIxNI_type::Zero();
  for (int ii = 0; ii< NI; ++ii) {
    (*RRinv)(ii, ii) = pow((bounds.ubounds(ii,1) - bounds.ubounds(ii,0))/2,2);
    (*RR)(ii, ii) = 1/(*RRinv)(ii,ii);
  }
  *P1 = *QQ;
}

void SpecifyRootTrajectory(const ode_state_type & x0, double t_h_max_upper, InterpVector * xx_interp, InterpVector * uu_interp) {
  vector<double> tt_vec;
  vector<ode_state_type> xx_vec;

  // Initializing to free dynamics
  sys::IntegrateFreeDynamics(x0, t_h_max_upper, &tt_vec, &xx_vec);
  xx_interp = new InterpVector(tt_vec, xx_vec);

  // Control input is set to 0.0
  vector< vector<double> > uu_vec(3,vector<double>(NI,0.0));
  tt_vec.clear();
  tt_vec.push_back(0.0);
  tt_vec.push_back(t_h_max_upper/2.0);
  tt_vec.push_back(t_h_max_upper);
  uu_interp = new InterpVector(tt_vec, uu_vec);
}
<commit_msg>fixed saving trajectory issue<commit_after>//
//  main.cpp
//  Agile_RRT
//
//  Created by Timothy Caldwell.
//  Copyright (c) 2015 Timothy Caldwell. Refer to license.txt
//
//  AgileRRT motion plans the highly dynamic 3-link pendulum on a cart. It executes the rapidly exploring random tree using LQR-based steering with linearization about the zero-control trajectory.
//
//  Arguments: (default value given right of '=' sign)
//    t_h_max_upper = 1.0       | Max time horizon.
//    usezerotraj = true        | Choose linearization for steering: true -> Linearization about zero-control trajectory.
//                                                                   false -> Linearization about vertex x0.
//    max_cnt = 1000            | Max number of successful insertions into the tree. RRT ends if max_cnt reached.
//    max_miss = 1000           | Max number of failed insertions into the tree. RRT ends if max_miss reached.
//    max_samplemiss = 10000    | Max number of failed attempts to find a
//    numbruns = 1              | Number of runs of the RRT. Run more to get more statistics.
//    stopdist = 0.0            | Stops RRT if a point is explored within a ball of radius stopdist from the goal state.
//    printskip = 1             | Number of loops of the RRT to skip between printing details to standard out.
//    nndelta = LARGENUM        | Nearest Neighbor ball radius for quickly checking
//    stats_name = "0"          | Filename to store statistics as a csv. Use "0" or no arg to not make file.
//    traj_name = "0"           | Filename to store tree trajectories easily readable by Mathematica. Use "0" or no arg to not make file
//    seed = 0                  | To choose the seed to the random number generator

#include "global.h"
#include "interp.h"
#include "system.h"
#include "pendcart_3link.h"
#include "treevertex.h"
#include "tree.h"
//#include "rrtreach.h"

// Struct for all options given as inputs through arguments.
struct inputs_struct {
  double t_h_max_upper = 1.0;
  bool usezerotraj = true;
  int max_cnt = 1000;
  int max_miss = 1000;
  int max_samplemiss = 10000;
  int numbruns = 1;
  double stopdist = 0.0;
  bool computexxgoaldist = false;
  int printskip = 1;
  double nndelta = kLARGENUM;
  ofstream stats_f, traj_f;
  bool is_stats_out = false;
  bool is_traj_out = false;
  bool save_edges = false;
  double seed = 0.0;
};
// Parses arguments (see top comment for information) into inputs struct.
void SpecifyInputs(int argc, const char * argv[], inputs_struct * inputs);
// Initializes the system state and control bounds and circular obstacle constraints.
void SpecifyConstraints(sampling_bounds_struct * bounds, constraints_struct * constraints);
// Initializes quadratic cost function gains QQ, RR, P1 based on the specified state and control bounds.
// Cost function has form (using Latex syntax) J = 0.5 \int_0^{th}xx^T*QQ*xx + uu^T*RR*uu dt + 0.5*xx(th)^T*P1*xx(th).
// RRinv is the matrix inverse of RR.
void SpecifyCostGains(const sampling_bounds_struct & bounds, NSxNS_type * QQ, NIxNI_type * RR, NIxNI_type * RRinv, NSxNS_type * P1);
// Sets root trajectory to the tree to be the free trajectory for the duration of the max time horizon.
void SpecifyRootTrajectory(const ode_state_type & x0, double t_h_max_upper, InterpVector * xx_interp, InterpVector * uu_interp);
// Execute the RRT for the number of runs numbruns specified.
void Execute(const sampling_bounds_struct & bounds, TreeVertex * init_vert, inputs_struct * inputs);

int main(int argc, const char * argv[])
{
  inputs_struct inputs;
  SpecifyInputs(argc, argv, &inputs);
  cout << "asd" << endl;
  // The initial conditions
  ode_state_type x0 = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
  cout << "bsd" << endl;
  // Set bounds and constraints.
  sampling_bounds_struct bounds;
  constraints_struct constraints;
  SpecifyConstraints(&bounds, &constraints);
    cout << "csd" << endl;
  // Set cost gains.
  NSxNS_type QQ, P1;
  NIxNI_type RR, RRinv;
  SpecifyCostGains(bounds, &QQ, &RR, &RRinv, &P1);
  cout << "dsd" << endl;
  // Set root trajectory to free dynamics.
  InterpVector xx_interp;// = nullptr;
  InterpVector uu_interp;// = nullptr;
  SpecifyRootTrajectory(x0, inputs.t_h_max_upper, &xx_interp, &uu_interp);
  cout << "esd" << endl;
  // Create initial vertex.
  TreeVertex * init_vert = new TreeVertex(x0, inputs.usezerotraj, inputs.t_h_max_upper, xx_interp, uu_interp, constraints, QQ, RR, P1, QQ, RR, P1, inputs.t_h_max_upper, inputs.save_edges);
  cout << "fsd" << endl;
  Execute(bounds, init_vert, &inputs);
}

void SpecifyInputs(int argc, const char * argv[], inputs_struct * inputs) {
  cout << "a " << argc << endl;
  if (argc > 1)
    sscanf(argv[1], "%lf", &(inputs->t_h_max_upper));
  if (argc > 2)
    if ( strcmp(argv[2],"false") == 0 ) // anything besides false is assumed true
        inputs->usezerotraj = false;
  if (argc > 3)
    sscanf(argv[3], "%d", &(inputs->max_cnt));
  if (argc > 4)
    sscanf(argv[4], "%d", &(inputs->max_miss));
  if (argc > 5)
    sscanf(argv[5], "%d", &(inputs->max_samplemiss));
  if (argc > 6)
    sscanf(argv[6], "%d", &(inputs->numbruns));
  if (argc > 7) {
    sscanf(argv[7], "%lf", &(inputs->stopdist));
    if (inputs->stopdist != 0)
      inputs->computexxgoaldist = true;
  }
  if (argc > 8)
    sscanf(argv[8], "%d", &(inputs->printskip));
  if (argc > 9)
    sscanf(argv[9], "%lf", &(inputs->nndelta));
  if (argc > 10) {
    if ( strcmp(argv[10],"0") != 0 ) {
      inputs->stats_f.open(argv[10], ios::trunc);
      inputs->is_stats_out = true;
    }
  }
  if (argc > 11) {
      cout << "b " << endl;
      cout << argv[11];
    if (strcmp(argv[11],"0") != 0) {
      cout << "c" << endl;
      inputs->traj_f.open(argv[11], ios::trunc);
      inputs->traj_f << "{" << argv[11];
      inputs->is_traj_out = true;
      inputs->save_edges = true;
    }
  }
  if (argc > 12)
    sscanf(argv[12], "%lf", &(inputs->seed));
}

// Bounds and obstacles can be changed here.
void SpecifyConstraints(sampling_bounds_struct * bounds, constraints_struct * constraints) {
  // Sets upper and lower boundaries of state and control
  double bounds_delta = 10;
  bounds->xbounds << -2.0 * M_PI    , 2.0 * M_PI,
                -bounds_delta * M_PI * 0.5   , bounds_delta * M_PI * 0.5,
                -2.0 * M_PI    , 2.0 * M_PI,
                -bounds_delta * M_PI * 0.5   , bounds_delta * M_PI * 0.5,
                -2.0 * M_PI    , 2.0 * M_PI,
                -bounds_delta * M_PI * 0.5   , bounds_delta * M_PI * 0.5,
                -1.0                       , 8.0,
                -bounds_delta * 1.5          ,bounds_delta * 1.5;
  bounds->ubounds << -20.0 , 20.0;

  constraints->xbounds = bounds->xbounds;
  constraints->ubounds = bounds->ubounds;

  // Circular obstacle details
  // The following creates two circles of radius 0.6m at points (3.0, 0.85) and (3.0,-0.85)
  constraints->obs_radii = { 0.6, 0.6 };
  constraints->obs_Xs = { 3.0, 3.0 };
  constraints->obs_Ys = { 0.85, -0.85 };
}

void SpecifyCostGains(const sampling_bounds_struct & bounds, NSxNS_type * QQ, NIxNI_type * RR, NIxNI_type * RRinv, NSxNS_type * P1) {
  *QQ = NSxNS_type::Zero();
  for (int ii = 0; ii< NS; ++ii)
    (*QQ)(ii, ii) = 1/pow((bounds.xbounds(ii,1) - bounds.xbounds(ii,0))/2,2);
  *RRinv = NIxNI_type::Zero();
  *RR = NIxNI_type::Zero();
  for (int ii = 0; ii< NI; ++ii) {
    (*RRinv)(ii, ii) = pow((bounds.ubounds(ii,1) - bounds.ubounds(ii,0))/2,2);
    (*RR)(ii, ii) = 1/(*RRinv)(ii,ii);
  }
  *P1 = *QQ;
}

void SpecifyRootTrajectory(const ode_state_type & x0, double t_h_max_upper, InterpVector * xx_interp, InterpVector * uu_interp) {
  vector<double> tt_vec;
  vector<ode_state_type> xx_vec;

  // Initializing to free dynamics
  sys::IntegrateFreeDynamics(x0, t_h_max_upper, &tt_vec, &xx_vec);
  xx_interp = new InterpVector(tt_vec, xx_vec);

  // Control input is set to 0.0
  vector< vector<double> > uu_vec(3,vector<double>(NI,0.0));
  tt_vec.clear();
  tt_vec.push_back(0.0);
  tt_vec.push_back(t_h_max_upper/2.0);
  tt_vec.push_back(t_h_max_upper);
  uu_interp = new InterpVector(tt_vec, uu_vec);
}

void Execute(const sampling_bounds_struct & bounds, TreeVertex * init_vert, inputs_struct * inputs) {
  clock_t t_start2 = clock();
  cout << "execute start" << endl;
  Tree tree(init_vert, inputs->t_h_max_upper, bounds, inputs->max_cnt, inputs->max_miss, inputs->max_samplemiss, inputs->printskip, inputs->seed);
  cout << "tree made" << endl;

  if (inputs->computexxgoaldist) {
    NSx1_type xxgoal;
    xxgoal << 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 6.0 , 0.0;
    tree.set_xxgoal_stopdist (inputs->stopdist, xxgoal);
  }
  tree.set_nndelta(inputs->nndelta);

  cout << "xxgoal set" << endl;
  double meancnt = 0;
  double meanmiss = 0;
  double meandist = 0;
  double meansamplemiss = 0;
  int numbxxgoalfails = 0;
  // Run multiple times to collect statistics
  for (int ii = 0; ii < inputs->numbruns; ++ii) {
    cout << " ########################### " << endl;
    cout << "           ii = " << ii << endl;
    cout << " ########################### " << endl;

    tree.RunRRT();

    meandist += tree.get_disttogoal()/inputs->numbruns;
    meancnt += double(tree.get_cnttot())/inputs->numbruns;
    meanmiss += double(tree.get_misstot())/inputs->numbruns;
    meansamplemiss += double(tree.get_samplemisstot())/inputs->numbruns;

    if (tree.get_disttogoal() > inputs->stopdist)
      numbxxgoalfails++;

    cout << "plotting tree" << endl;
    if (inputs->is_traj_out)
      tree.Print(0.02, "tree_"+to_string(ii), &(inputs->traj_f));
    cout << "done plotting tree" << endl;

    tree.ResetTree();
  }
  cout << "mean dist is: " << meandist << endl;
  cout << "mean cnt is: " << meancnt << endl;
  cout << "mean miss is: " << meanmiss << endl;
  cout << "mean sample miss is: " << meansamplemiss << endl;
  cout << "mean run time: " << ((float)(clock()-t_start2))/CLOCKS_PER_SEC/inputs->numbruns << " seconds." << endl;
  cout << "number of xxgoal fails: " << numbxxgoalfails << endl;

  if (inputs->is_stats_out) {
    inputs->stats_f << "meandist, " << meandist << endl;
    inputs->stats_f << "meancnt, " << meancnt << endl;
    inputs->stats_f << "meanmiss, " << meanmiss << endl;
    inputs->stats_f << "meansamplemiss, " << meansamplemiss << endl;
    inputs->stats_f << "meanruntime, " << ((float)(clock()-t_start2))/CLOCKS_PER_SEC/inputs->numbruns << endl;
    inputs->stats_f << "numbxxgoalsfails, " << numbxxgoalfails << endl;
    inputs->stats_f.close();
    cout << "stats finished" << endl;
  }
  if (inputs->is_traj_out) {
    inputs->traj_f << "}";
    inputs->traj_f.close();
    cout << "traj finished" << endl;
  }
}
<|endoftext|>


<commit_before>7bdfec68-ad5c-11e7-a6c9-ac87a332f658<commit_msg>Stuff changed<commit_after>7c5172b8-ad5c-11e7-8322-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <stdio.h>
using namespace std;

#include "../header/Command.h"
#include "../header/Connector.h"
#include "../header/Command.h"
#include "../header/Andand.h"
#include "../header/Oror.h"
#include "../header/Semicolon.h"
#include "../header/Base.h"

int main() {
    vector<Command*> commands;
    vector<char> connectorTypes;
    string input;
    cout << "$ ";
    getline(cin, input);
    int prevIndex = 0;

    bool sharp = false;

    //Parse genji after getting execvpharah to work
    for (unsigned i = 0; i < input.size(); ++i) {
        if (input.at(i) == '#') {
            Command* comm = new Command(input.substr(prevIndex, i - prevIndex));
            commands.push_back(comm);
            sharp = true;
            prevIndex = i + 1;
        }
        if (input.at(i) == ';') {
            cout << input.substr(prevIndex, i - prevIndex) << endl;
            Command* comm = new Command(input.substr(prevIndex, i - prevIndex));
            commands.push_back(comm);
            connectorTypes.push_back(';');
            prevIndex = i + 1;
        }
        if (input.at(i) == '&') {
            if (i != input.size() - 1) {
                if (input.at(i + 1) == '&') {
                    cout << input.substr(prevIndex, i - prevIndex) << endl;
                    Command* comm = new Command(input.substr(prevIndex, i - prevIndex));
                    commands.push_back(comm);
                    connectorTypes.push_back('&');
                    prevIndex = i + 2;
                }
            }
        }
        if (input.at(i) == '|') {
            if (i != input.size() - 1) {
                if (input.at(i + 1) == '|') {
                    cout << input.substr(prevIndex, i - prevIndex) << endl;
                    Command* comm = new Command(input.substr(prevIndex, i - prevIndex));
                    commands.push_back(comm);
                    connectorTypes.push_back('|');
                    prevIndex = i + 2;
                }
            }
        }
        if (input.at(i) == ']') {
            Command* comm = new Command(input.substr(input.find('[', prevIndex), i - input.find('[', prevIndex)));
            commands.push_back(comm);
            connectorTypes.push_back(']');
            prevIndex = i + 1;
        }
    }
    if(!sharp) {
        cout << input.substr(prevIndex, input.size() - prevIndex) << endl;
        Command* last = new Command(input.substr(prevIndex, input.size() - prevIndex));
        commands.push_back(last);
    }

    int prevResult = commands.at(0)->execute();

    for(unsigned i = 0; i < connectorTypes.size(); ++i) {
        if(connectorTypes.at(i) == ';') {
            Semicolon* semi = new Semicolon(commands.at(i + 1), prevResult);
            prevResult = semi->execute();
        }
        else if(connectorTypes.at(i) == '&') {
            Andand* amper = new Andand(commands.at(i + 1), prevResult);
            prevResult = amper->execute();
        }
        else if(connectorTypes.at(i) == '|') {
            Oror* bar = new Oror(commands.at(i + 1), prevResult);
            prevResult = bar->execute();
        }
    }

    //zarya blackhole + pharah barrage = potg champ [Q ftw}]
    for(unsigned i = 0; i < commands.size(); ++i) {
        //cout << commands.at(i)->command[0] << endl;
        for(unsigned j = 0; j < commands.at(i)->size; ++j) {
            printf ("%s \n", commands.at(i)->command[j]);
        }
    }
    for(unsigned i = 0; i < connectorTypes.size(); ++i) {
        cout << connectorTypes.at(i) << endl;
    }

    return 0;
}<commit_msg>deleted main.cpp<commit_after><|endoftext|>


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

#include <iostream>
#include <getopt.h>
#include <vector>

#include "inc/stringutils.hpp"
#include "inc/config.hpp"

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

	static struct option long_options[] = {
		{"config", 1, 0, 'c'},
		{"query", 0, 0, 'q'},
		{NULL, 0, NULL, 0}
	};

	int option_index = 0;
	while ((arg_char = getopt_long(argc, argv, "c:", long_options, &option_index)) != -1)
		switch (arg_char)
		{
			case 0:
				std::cout << long_options[option_index].name << std::endl;
			case 'c':
				if (optarg) {
					// Do the staff with valid configuration parameters

					// Split configuration parameters using '.' full stop character
					std::vector<std::string> sections = jippi::StringUtils::split(optarg, '.');
					// We are going to set only one value at a time.
					// If there are more than one value, then
					// there is something wrong.
					if (sections.size() == 2) {
						jippi::Config *configuration = new jippi::Config(DEFAULT_CONFIG_FILE, DEFAULT_CONFIG_FILE_LOCATION);
						if (!configuration->foundConfigurationFile()) {
							configuration->storeDefaultConfigurationInFile();
						}
						std::string group = sections.at(0);
						std::string key = sections.at(1);
						configuration->readConfigurationFromFile();
						configuration->storeProperty(group, key, argv[optind]);
						configuration->writeConfigurationToFile();
					} else {
						std::cerr << "We've got wrong config command" << std::endl;
					}
				} else {
					// print help
				}

				break;
			case 'q':
				std::cout << "query" << std::endl;
				break;
			default:
				std::cout << arg_char << std::endl;
				if (optarg)
					std::cout << " with arguments: " << optarg << std::endl;
		}

	return 0;
}
<commit_msg>Remove memory leak from the main.cpp<commit_after>/*
 * Copyright 2013 Kamil Michalak <kmichalak8@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <iostream>
#include <getopt.h>
#include <vector>

#include "inc/stringutils.hpp"
#include "inc/config.hpp"

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

	static struct option long_options[] = {
		{"config", 1, 0, 'c'},
		{"query", 0, 0, 'q'},
		{NULL, 0, NULL, 0}
	};

	int option_index = 0;
	while ((arg_char = getopt_long(argc, argv, "c:", long_options, &option_index)) != -1)
		switch (arg_char)
		{
			case 0:
				std::cout << long_options[option_index].name << std::endl;
			case 'c':
				if (optarg) {
					// Do the staff with valid configuration parameters

					// Split configuration parameters using '.' full stop character
					std::vector<std::string> sections = jippi::StringUtils::split(optarg, '.');
					// We are going to set only one value at a time.
					// If there are more than one value, then
					// there is something wrong.
					if (sections.size() == 2) {
						jippi::Config *configuration = new jippi::Config(DEFAULT_CONFIG_FILE, DEFAULT_CONFIG_FILE_LOCATION);
						if (!configuration->foundConfigurationFile()) {
							configuration->storeDefaultConfigurationInFile();
						}
						std::string group = sections.at(0);
						std::string key = sections.at(1);
						configuration->readConfigurationFromFile();
						configuration->storeProperty(group, key, argv[optind]);
						configuration->writeConfigurationToFile();
						delete configuration;
					} else {
						std::cerr << "We've got wrong config command" << std::endl;
					}
				} else {
					// print help
				}

				break;
			case 'q':
				std::cout << "query" << std::endl;
				break;
			default:
				std::cout << arg_char << std::endl;
				if (optarg)
					std::cout << " with arguments: " << optarg << std::endl;
		}

	return 0;
}
<|endoftext|>


<commit_before>#include "SDL.h"

#include "resources/imageresource.h"

namespace Zabbr {

	/**
	 * Constructor.
	 *
	 * @param name The name of the image.
	 * @param surface The surface of the image.
	*/
	ImageResource::ImageResource(std::string name, SDL_Surface* surface)
	              : SDLSurfaceResource(name, surface) {
	}

	/**
	 * Destructor.
	*/
	ImageResource::~ImageResource() {
	}

	/**
	 * Opens an image.
	 *
	 * @param name the filename of the image.
	 *
	 * @throw ResourceNotLoadedException.
	*/
	ImageResource* ImageResource::open(std::string name) {
		SDL_Surface* temp;
		SDL_Surface* image;

		temp = SDL_LoadBMP(("../data/"+name).c_str());
		if (temp == NULL) {
			throw ResourceNotLoadedException(name, SDL_GetError());
		}

		image = SDL_DisplayFormat(temp);
		SDL_FreeSurface(temp);
		return new ImageResource(name, image);
	}
}
<commit_msg>Load images with SDL_image and make transparancy work<commit_after>#include "SDL.h"
#include "SDL_image.h"

#include "resources/imageresource.h"

namespace Zabbr {

	/**
	 * Constructor.
	 *
	 * @param name The name of the image.
	 * @param surface The surface of the image.
	*/
	ImageResource::ImageResource(std::string name, SDL_Surface* surface)
	              : SDLSurfaceResource(name, surface) {
	}

	/**
	 * Destructor.
	*/
	ImageResource::~ImageResource() {
	}

	/**
	 * Opens an image.
	 *
	 * @param name the filename of the image.
	 *
	 * @throw ResourceNotLoadedException.
	*/
	ImageResource* ImageResource::open(std::string name) {
		SDL_Surface* temp;
		SDL_Surface* image;

		temp = IMG_Load(("../data/"+name).c_str());
		if (temp == NULL) {
			throw ResourceNotLoadedException(name, IMG_GetError());
		}

		image = SDL_DisplayFormatAlpha(temp);
		SDL_FreeSurface(temp);
		return new ImageResource(name, image);
	}
}
<|endoftext|>


<commit_before>/*
 * Project name: Pang Game
 * Version 1
 * Student : Albert Eduard Merino Pulido
 */
#include <iostream>
#include <getopt.h>
#include <GL/glut.h>
#include "game.h"
#include "constants.h"
using namespace std;

void display();
void keyboard(unsigned char c, int x, int y);
void keyboardUp(unsigned char c, int x, int y);
void special(int key, int x, int y);
void specialUp(int key, int x, int y);
void idle();
void usage(char *);

const char * windowTitle = "Pang game - Merino";

Game game;
long last_t;

StrategyType Constants::strategyTypePlayer = HUMAN_AGENT;
StrategyType Constants::strategyTypeEnemy  = REFLEX_AGENT;
int main(int argc, char * argv[]){
    char quiet = 0;

    /* parse options */
    int option_index = 0, opt;
    static struct option loptions[] = {
        { "help",   no_argument,       0, 'h' },
        { "player", required_argument, 0, 'P' },
        { "enemy",  required_argument, 0, 'E' },
        { NULL,                     0, 0,   0 }
    };

    while (1) {
        opt = getopt_long(argc, argv, "hP:E:",
          loptions, &option_index);
        if (opt == -1) break;
        switch (opt) {
            case '0': break;
            case 'h':
                usage(argv[0]);
                break;
            case 'P':
                if (strcmp("human", optarg) == 0) Constants::strategyTypePlayer = HUMAN_AGENT;
                else if (strcmp("random", optarg) == 0) Constants::strategyTypePlayer = RANDOM_AGENT;
                else if (strcmp("reflex", optarg) == 0) Constants::strategyTypePlayer = REFLEX_AGENT;
                if (!quiet) cout << "Strategy Player : " << optarg << "\n";
                break;
            case 'E':
                if (strcmp("human", optarg) == 0) Constants::strategyTypeEnemy = HUMAN_AGENT;
                else if (strcmp("random", optarg) == 0) Constants::strategyTypeEnemy = RANDOM_AGENT;
                else if (strcmp("reflex", optarg) == 0) Constants::strategyTypeEnemy = REFLEX_AGENT;
                if (!quiet) cout << "Strategy Enemy : " << optarg << "\n";
                break;
        }
    }
    srand(time(NULL));
    Plane leftPlane   = Plane(Vector3(1, 0), Vector3(0, 0));
    Plane rightPlane  = Plane(Vector3(-1, 0), Vector3(Constants::DEFAULT_WIDTH, 0));
    Plane bottomPlane = Plane(Vector3(0, 1), Vector3(0, 0));
    game = Game(new PangScenario(leftPlane, rightPlane, bottomPlane,
          Constants::DEFAULT_WIDTH, Constants::DEFAULT_HEIGHT));
    game.startGame();
    last_t = 0;

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowPosition(50, 50);
    glutInitWindowSize(Constants::DEFAULT_WIDTH * Constants::PIXELS_PER_METER,
      Constants::DEFAULT_HEIGHT * Constants::PIXELS_PER_METER);
    glutCreateWindow(windowTitle);

    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutKeyboardUpFunc(keyboardUp);
    glutSpecialFunc(special);
    glutSpecialUpFunc(specialUp);
    glutIdleFunc(idle);

    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(0, Constants::DEFAULT_WIDTH, 0, Constants::DEFAULT_HEIGHT);
    glutMainLoop();

    return 0;
} // main

void display(){
    glClearColor(Color::background.red, Color::background.green,
      Color::background.blue, Color::background.alpha);
    glClear(GL_COLOR_BUFFER_BIT);

    game.getPangScenario()->draw();
    game.printScores(1, Constants::DEFAULT_HEIGHT * 0.95, 0);
    game.printScores(1, Constants::DEFAULT_HEIGHT * 0.9, 1);

    glutSwapBuffers();
}

void keyboard(unsigned char c, int x, int y){
    c = tolower(c); // Prevent upper case

    if (c == '-') game.getPangScenario()->shoot(PLAYER_1);
    else if (c == ' ') game.getPangScenario()->shoot(PLAYER_2);
    else if (c == 'r') game.getPangScenario()->reset();
    else if (c == 'p') game.pause();
    else if (c == 'a') game.getPangScenario()->move(PLAYER_2, LEFT);
    else if (c == 'd') game.getPangScenario()->move(PLAYER_2, RIGHT);
}

void keyboardUp(unsigned char c, int x, int y){
    c = tolower(c); // Prevent upper case

    if (c == 'a' || c == 'd') game.getPangScenario()->move(PLAYER_2, STOP);
}

void special(int key, int x, int y){
    switch (key) {
        case GLUT_KEY_UP:
            break;
        case GLUT_KEY_DOWN:
            break;
        case GLUT_KEY_LEFT:
            game.getPangScenario()->move(PLAYER_1, LEFT);
            break;
        case GLUT_KEY_RIGHT:
            game.getPangScenario()->move(PLAYER_1, RIGHT);
            break;
    }
    glutPostRedisplay();
}

void specialUp(int key, int x, int y){
    switch (key) {
        case GLUT_KEY_UP:
            break;
        case GLUT_KEY_DOWN:
            break;
        case GLUT_KEY_LEFT:
        case GLUT_KEY_RIGHT:
            game.getPangScenario()->move(PLAYER_1, STOP);
            break;
    }
    glutPostRedisplay();
}

void idle(){
    long t;

    t = glutGet(GLUT_ELAPSED_TIME);

    if (last_t == 0) {
        last_t = t;
    } else {
        game.integrate((t - last_t) / 1000.0);
        last_t = t;
    }

    glutPostRedisplay();
}

void usage(char * name){
    cout << "Usage: " << name << " [OPTIONS]" << endl
         << "\nHelp options:" << endl
         << "  -h, --help         Print this help message" << endl
         << "\nAgent options:" << endl
         << "  -P  --player       Select player strategy (Default Human)" << endl
         << "  -E  --enemy        Select enemy strategy (Default Reflex)" << endl
         << "  Options:" << endl
         << "    · reflex" << endl
         << "" << endl
         << "Note: Order is not important." << endl
         << "Examples:" << endl
         << "  " << name << endl
         << "  " << name << " -P reflex -E human" << endl
         << endl;
    exit(EXIT_SUCCESS);
}
<commit_msg>Created useful method changeStrategyType to change the strategy type for a player<commit_after>/*
 * Project name: Pang Game
 * Version 1
 * Student : Albert Eduard Merino Pulido
 */
#include <iostream>
#include <getopt.h>
#include <GL/glut.h>
#include "game.h"
#include "constants.h"
using namespace std;

void display();
void keyboard(unsigned char c, int x, int y);
void keyboardUp(unsigned char c, int x, int y);
void special(int key, int x, int y);
void specialUp(int key, int x, int y);
void idle();
void usage(char *);
void changeStrategyType(StrategyType * strategy, char * optarg);

const char * windowTitle = "Pang game - Merino";

Game game;
long last_t;

StrategyType Constants::strategyTypePlayer = HUMAN_AGENT;
StrategyType Constants::strategyTypeEnemy  = REFLEX_AGENT;
int main(int argc, char * argv[]){
    char quiet = 0;

    /* parse options */
    int option_index = 0, opt;
    static struct option loptions[] = {
        { "help",   no_argument,       0, 'h' },
        { "player", required_argument, 0, 'P' },
        { "enemy",  required_argument, 0, 'E' },
        { NULL,                     0, 0,   0 }
    };

    while (1) {
        opt = getopt_long(argc, argv, "hP:E:",
          loptions, &option_index);
        if (opt == -1) break;
        switch (opt) {
            case '0': break;
            case 'h':
                usage(argv[0]);
                break;
            case 'P':
                changeStrategyType(&Constants::strategyTypePlayer, optarg);
                if (!quiet) cout << "Strategy Player : " << optarg << "\n";
                break;
            case 'E':
                changeStrategyType(&Constants::strategyTypeEnemy, optarg);
                if (!quiet) cout << "Strategy Enemy : " << optarg << "\n";
                break;
        }
    }
    srand(time(NULL));
    Plane leftPlane   = Plane(Vector3(1, 0), Vector3(0, 0));
    Plane rightPlane  = Plane(Vector3(-1, 0), Vector3(Constants::DEFAULT_WIDTH, 0));
    Plane bottomPlane = Plane(Vector3(0, 1), Vector3(0, 0));
    game = Game(new PangScenario(leftPlane, rightPlane, bottomPlane,
          Constants::DEFAULT_WIDTH, Constants::DEFAULT_HEIGHT));
    game.startGame();
    last_t = 0;

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowPosition(50, 50);
    glutInitWindowSize(Constants::DEFAULT_WIDTH * Constants::PIXELS_PER_METER,
      Constants::DEFAULT_HEIGHT * Constants::PIXELS_PER_METER);
    glutCreateWindow(windowTitle);

    glutDisplayFunc(display);
    glutKeyboardFunc(keyboard);
    glutKeyboardUpFunc(keyboardUp);
    glutSpecialFunc(special);
    glutSpecialUpFunc(specialUp);
    glutIdleFunc(idle);

    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(0, Constants::DEFAULT_WIDTH, 0, Constants::DEFAULT_HEIGHT);
    glutMainLoop();

    return 0;
} // main

void display(){
    glClearColor(Color::background.red, Color::background.green,
      Color::background.blue, Color::background.alpha);
    glClear(GL_COLOR_BUFFER_BIT);

    game.getPangScenario()->draw();
    game.printScores(1, Constants::DEFAULT_HEIGHT * 0.95, 0);
    game.printScores(1, Constants::DEFAULT_HEIGHT * 0.9, 1);

    glutSwapBuffers();
}

void keyboard(unsigned char c, int x, int y){
    c = tolower(c); // Prevent upper case

    if (c == '-') game.getPangScenario()->shoot(PLAYER_1);
    else if (c == ' ') game.getPangScenario()->shoot(PLAYER_2);
    else if (c == 'r') game.getPangScenario()->reset();
    else if (c == 'p') game.pause();
    else if (c == 'a') game.getPangScenario()->move(PLAYER_2, LEFT);
    else if (c == 'd') game.getPangScenario()->move(PLAYER_2, RIGHT);
}

void keyboardUp(unsigned char c, int x, int y){
    c = tolower(c); // Prevent upper case

    if (c == 'a' || c == 'd') game.getPangScenario()->move(PLAYER_2, STOP);
}

void special(int key, int x, int y){
    switch (key) {
        case GLUT_KEY_UP:
            break;
        case GLUT_KEY_DOWN:
            break;
        case GLUT_KEY_LEFT:
            game.getPangScenario()->move(PLAYER_1, LEFT);
            break;
        case GLUT_KEY_RIGHT:
            game.getPangScenario()->move(PLAYER_1, RIGHT);
            break;
    }
    glutPostRedisplay();
}

void specialUp(int key, int x, int y){
    switch (key) {
        case GLUT_KEY_UP:
            break;
        case GLUT_KEY_DOWN:
            break;
        case GLUT_KEY_LEFT:
        case GLUT_KEY_RIGHT:
            game.getPangScenario()->move(PLAYER_1, STOP);
            break;
    }
    glutPostRedisplay();
}

void idle(){
    long t;

    t = glutGet(GLUT_ELAPSED_TIME);

    if (last_t == 0) {
        last_t = t;
    } else {
        game.integrate((t - last_t) / 1000.0);
        last_t = t;
    }

    glutPostRedisplay();
}

void usage(char * name){
    cout << "Usage: " << name << " [OPTIONS]" << endl
         << "\nHelp options:" << endl
         << "  -h, --help         Print this help message" << endl
         << "\nAgent options:" << endl
         << "  -P  --player       Select player strategy (Default Human)" << endl
         << "  -E  --enemy        Select enemy strategy (Default Reflex)" << endl
         << "  Options:" << endl
         << "    · reflex" << endl
         << "" << endl
         << "Note: Order is not important." << endl
         << "Examples:" << endl
         << "  " << name << endl
         << "  " << name << " -P reflex -E human" << endl
         << endl;
    exit(EXIT_SUCCESS);
}

void changeStrategyType(StrategyType * strategy, char * optarg){
    if (strcmp("human", optarg) == 0) (*strategy) = HUMAN_AGENT;
    else if (strcmp("random", optarg) == 0) (*strategy) = RANDOM_AGENT;
    else if (strcmp("reflex", optarg) == 0) (*strategy) = REFLEX_AGENT;
}
<|endoftext|>


<commit_before>e42e1066-ad58-11e7-a07d-ac87a332f658<commit_msg>my cat is cute<commit_after>e4a7323d-ad58-11e7-a607-ac87a332f658<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////
// main.cpp -- Test Main
// Date: Wed Nov 27 23:07:19 2013
///////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include <sys/stat.h>

#include "glue.hpp"
#include "utils.hpp"
#include "ansi-c-yacc.hpp"
#include "comp.hpp"

#include <iostream>
#include <istream>

int
main(int argc,char **argv) {
	std::string platform, version, machine;
	int ltoken;
	extern int yydebug;

	if ( argc > 1 )
		yydebug = 1;

	platform = uts_platform();
	version = uts_version();
	machine = uts_machine();

	std::cout << "Platform: " << platform << "\n"
		<< "Machine:  " << machine << "\n"
		<< "Version:  " << version << "\n";

	loadconfig();

	system("rm -fr ./staging");
	mkdir("./staging",0777);
	system("cp 0005.ads ./staging/.");
	system("cp 0005.adb ./staging/.");
	system("cp 0060.ads ./staging/.");
	system("cp 9999.ads ./staging/.");
	system("cp 9999.adb ./staging/.");

	comp_macros();
	comp_types();
	comp_systypes();
//	comp_funcs();

	emit_basic_types();
	emit_sys_types();
	emit_macros();
	emit_structs();
	emit_section2();

	system("cat ./staging/????.ads >posix.ads");
	system("cat ./staging/????.adb >posix.adb");

exit(0);

	while ( (ltoken = yylex()) != 0 ) {
		unsigned lno = lex_lineno();
		int id = lex_token();
		std::string& token = revsym[id];

		printf("%06u : %3d '%s' (%d)\n",
			lno,
			ltoken,
			token.c_str(),
			id);
	}
}

// End main.cpp
<commit_msg>Remove commented out func<commit_after>//////////////////////////////////////////////////////////////////////
// main.cpp -- Test Main
// Date: Wed Nov 27 23:07:19 2013
///////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include <sys/stat.h>

#include "glue.hpp"
#include "utils.hpp"
#include "ansi-c-yacc.hpp"
#include "comp.hpp"

#include <iostream>
#include <istream>

int
main(int argc,char **argv) {
	std::string platform, version, machine;
	int ltoken;
	extern int yydebug;

	if ( argc > 1 )
		yydebug = 1;

	platform = uts_platform();
	version = uts_version();
	machine = uts_machine();

	std::cout << "Platform: " << platform << "\n"
		<< "Machine:  " << machine << "\n"
		<< "Version:  " << version << "\n";

	loadconfig();

	system("rm -fr ./staging");
	mkdir("./staging",0777);
	system("cp 0005.ads ./staging/.");
	system("cp 0005.adb ./staging/.");
	system("cp 0060.ads ./staging/.");
	system("cp 9999.ads ./staging/.");
	system("cp 9999.adb ./staging/.");

	comp_macros();
	comp_types();
	comp_systypes();

	emit_basic_types();
	emit_sys_types();
	emit_macros();
	emit_structs();
	emit_section2();

	system("cat ./staging/????.ads >posix.ads");
	system("cat ./staging/????.adb >posix.adb");

exit(0);

	while ( (ltoken = yylex()) != 0 ) {
		unsigned lno = lex_lineno();
		int id = lex_token();
		std::string& token = revsym[id];

		printf("%06u : %3d '%s' (%d)\n",
			lno,
			ltoken,
			token.c_str(),
			id);
	}
}

// End main.cpp
<|endoftext|>


<commit_before>4db8c711-2748-11e6-8b35-e0f84713e7b8<commit_msg>Did a thing<commit_after>4dd18c85-2748-11e6-8868-e0f84713e7b8<|endoftext|>


<commit_before>c93a6f21-2747-11e6-8a87-e0f84713e7b8<commit_msg>No longer crashes if X<commit_after>c9472c6b-2747-11e6-bc43-e0f84713e7b8<|endoftext|>


<commit_before>361f1a33-2748-11e6-9637-e0f84713e7b8<commit_msg>add file<commit_after>3638ad28-2748-11e6-90bd-e0f84713e7b8<|endoftext|>


<commit_before>#include <cstdio>
#include <cinttypes>
#include <cstdint>
#include <array>

using namespace std;
/*
 * MEMO
 *  - 障害物はスコアに入らないので、スコアと障害物の両方を1として表すことはできない
 */

// -- Constant Values
// 石操作情報
constexpr uint8_t REVERSED = 1,     // これが立ってたら反転してる
  ROTATED_90 = 2,   // これが立ってたら90度回転
  ROTATED_180 = 4,  // これがry
  ROTATED_270 = 6;

// Type Declarations
using RawStone = std::array<std::array<char, 8>, 8>;
using RawField = std::array<std::array<char, 32>, 32>;

class Stone;
class Field;
class StoneManipulations;

// Variable Forward Declarations
extern Stone stones[256];

// Type Definitions
class Stone {
public:
  RawStone raw;
};

class Field {
private:
  const Stone* put_stones[256];
  STONE_MANIPULATION manipulations[256];
  uint16_t field_score = 0;
public:
  RawField raw;
public:
  void put_stone(const uint8_t n, STONE_MANIPULATION m) {
    put_stones[n] = &stones[n];
    manipulations[n] = m;
  }
  bool try_put_stone(const uint8_t n, int y, int x, STONE_MANIPULATION m);
  const uint16_t score() const { return field_score; };
};

class StoneManipulations {
  public:
    StoneManipulations(int8_t x, int8_t y, uint8_t rotated):
      x(x), y(y), rotated(rotated) {} // This is correct. Initialize members variable by arguments.
    int8_t x, y;
    uint8_t rotated;
};

// Member Functions
bool Field::try_put_stone(const uint8_t n, int displacement_y, int displacement_x, STONE_MANIPULATION m) {
  const RawStone& stone = stones[n].raw;
  RawField backup = raw;
  if (!(-7 <= displacement_y && displacement_y < 32 && -7 <= displacement_x && displacement_x < 32))  // 入力をVaridate
	  return false;
  switch (m) { // 害悪
    case ROTATED_90://90度反転 -> y終端でxインクリメント・x方向を反転(デクリメント)
      for (int x = 8; x < 0; --x) for (int y = 0; y > 0; ++y) {
        if (stone[y][x] == '1') {
          if (raw[y+displacement_y][x+displacement_x] != '0') {
            return false;
          } else if(raw[y+displacement_y +1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
        	continue;
          } else {
            raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
            ++field_score;
          }
        }
      }
      break;
    case ROTATED_180://180度回転 -> x,y方向を反転(デクリメント)
      for (int y = 8; y > 0; --y) for (int x = 8; x > 0; --x) {
        if (stone[y][x] == '1') {
         if (raw[y+displacement_y][x+displacement_x] != '0') {
            return false;
         } else if(raw[y+displacement_y -1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
           	continue;
         } else {
           raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
           ++field_score;
        }
       }
      }
      break;
    case ROTATED_270://270度回転 -> y終端でxインクリメント・y方向を反転(デクリメント)
      for (int x = 8; x > 0; ++x) for (int y = 8; y > 0; --y) {
        if (stone[y][x] == '1') {
        	if (raw[y+displacement_y][x+displacement_x] != '0') {
             return false;
            }else if(raw[y+displacement_y -1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
             continue;
            } else {
             raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
            ++field_score;
           }
         }
        }
      break;
    case REVERSED://反転 -> x方向をデクリメントに
    	for (int y = 0; y < 8; ++y) for (int x = 8; x > 0; --x) {
    	 if (stone[y][x] == '1') {
    	    if (raw[y+displacement_y][x+displacement_x] != '0') {
    	        return false;
    	    } else if(raw[y+displacement_y +1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
    	        continue;
    	    } else {
    	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
    	        ++field_score;
    	    }
    	  }
        }
    	break;
    case ROTATED_90 | REVERSED:
	//反転+90度回転 -> y終端でxデクリメント・y方向をデクリメントに
	   for (int x = 8; x > 0; --x) for (int y = 8; y > 0; --y) {
	    if (stone[y][x] == '1') {
	      if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	       } else if(raw[y+displacement_y -1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	       } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++field_score;
	        }
	     }
	   }
      break;
    case ROTATED_180 | REVERSED:
	//反転+180度回転 -> yデクリメント
	   for (int y = 8; y > 0; --y) for (int x = 0; x < 8; ++x) {
	    if (stone[y][x] == '1') {
	     if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	     } else if(raw[y+displacement_y -1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	     } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++field_score;
	     }
	    }
	   }
      break;
    case ROTATED_270 | REVERSED:
	//y終端でxインクリメント
	  for (int x = 0; x < 8; ++x) for (int y = 0; y < 8; ++y) {
	   if (stone[y][x] == '1') {
	    if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	    } else if(raw[y+displacement_y +1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	    } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++field_score;
	    }
	   }
	  }
      break;
    default: // Regard as a non-manipulated stone
      for (int y = 0; y < 8; ++y) for (int x = 0; x < 8; ++x) {
        if (stone[y][x] == '1') {
        	if (raw[y+displacement_y][x+displacement_x] != '0') {
        	   return false;
        } else if(raw[y+displacement_y +1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
        	   continue;
        } else {
        	   raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
        	    ++field_score;
        }
       }
      }
      break;
  }
  return true;
}

// Variable Declarations
Field max_score_field; // 最適な解があるField
Stone stones[256]; // 渡されるstoneを格納
uint16_t number_of_stones; // 渡されるstoneの数

// -- Function Declarations
void solve(Field f, uint8_t look_nth_stone);

void parse(Field*);
void parse_field(Field* f);
void parse_stone();

int main() {
  Field f;
//   get_problem_file();
  parse(&f);
  solve(f, 0);
  printf("%d\n", max_score_field.score());
  for (int y = 0; y < 32; ++y)  {
    for (int x = 0; x < 32; ++x) {
      printf("%c", max_score_field.raw[y][x]);
    }
    printf("\n");
  }
//   submit();
  return 0;
}

// -- Function Definitions

/**
 * solve
 *
 * 問題を解くぞい
 *
 * -- Args
 *  Field f: 現在のフィールドの状態
 *  uint8_t look_nth_stone: 何番の石を置こうとしているか
 *
 * -- Return
 *  void
 *
 * -- 副作用
 *  max_score_field
 */
void solve(Field f, uint8_t look_nth_stone) {

  if (look_nth_stone >= number_of_stones) { // 一番深いところでスコア更新
    if (f.score() > max_score_field.score()) { // より良い結果が出るならそれを最適解フィールドとして登録
      max_score_field = f;
    }
    return;
  }

  solve(f, look_nth_stone + 1); // 今回は石を置かなかった

  for (int i = 0; i < 8; ++i) { // 回転反転組み合わせを試す
    for (int y = -7; y < 32; ++y) for (int x = -7; x < 32; ++x) { // (32+8) * (32+8)のフィールドのどこかに置く
      if (f.try_put_stone(look_nth_stone, y, x, i))
        solve(f, look_nth_stone + 1);
    }
  }
}

/*
 * parse_field
 *
 * 入力からField部分をパースする
 * -- Args
 *  Field* f: パースした結果を格納するfield
 *
 * -- 副作用
 *  stdin
 */
void parse_field(Field* f) {
  for (int i = 0; i < 32; ++i) {
    fread(f->raw[i].data(), sizeof(char[32]), 1, stdin);
    getc(stdin); // CR
    getc(stdin); // LF
  }
}

/*
 * parse_stone
 *
 * 入力からStone部分をパースする
 *
 * -- 副作用
 *  stdin
 *  stones
 */
void parse_stone() {
  for (int i = 0; i < number_of_stones; ++i) for (int j = 0; j < 8; ++j) {
    fread(stones[i].raw[j].data(), sizeof(char[8]), 1, stdin);
    getc(stdin); // CR
    getc(stdin); // LF
  }
}

/**
 * parse
 *
 * 入力をパースする
 *
 * -- Args
 *  Field* f: パースした結果を格納するFieldのポインタ
 *
 * -- 副作用
 *  stdin
 *  stones
 */
void parse(Field* f) {
  parse_field(f);
  getc(stdin); // 改行読み捨て CR
  getc(stdin); // LF
  scanf("%" SCNu16 "¥n", &number_of_stones); // SCNu8 is placeholder for uint8_t declared in cinttypes
  for (int i = 0; i < number_of_stones; ++i) {
    parse_stone();
    getc(stdin); // 改行読み捨て CR
    getc(stdin); // LF
  }
}
<commit_msg>Changed to use StoneManipulations<commit_after>#include <cstdio>
#include <cinttypes>
#include <cstdint>
#include <array>

using namespace std;
/*
 * MEMO
 *  - 障害物はスコアに入らないので、スコアと障害物の両方を1として表すことはできない
 */

// -- Constant Values
// 石操作情報
constexpr uint8_t REVERSED = 1,     // これが立ってたら反転してる
  ROTATED_90 = 2,   // これが立ってたら90度回転
  ROTATED_180 = 4,  // これがry
  ROTATED_270 = 6;

// Type Declarations
using RawStone = std::array<std::array<char, 8>, 8>;
using RawField = std::array<std::array<char, 32>, 32>;

class StoneManipulations;
class Stone;
class Field;

// Variable Forward Declarations
extern Stone stones[256];

// Type Definitions

class StoneManipulations {
  public:
    StoneManipulations(){}
    StoneManipulations(int8_t x, int8_t y, uint8_t rotated):
      x(x), y(y), rotated(rotated) {} // This is correct. Initialize members variable by arguments.
    int8_t x = 0, y = 0;
    uint8_t rotated = 0;
};
class Stone {
public:
  RawStone raw;
};

class Field {
private:
  const Stone* put_stones[256];
  StoneManipulations manipulations[256];
  uint16_t field_score = 0;
public:
  RawField raw;
public:

  void put_stone(const uint8_t n, StoneManipulations m, uint8_t score) {
    put_stones[n] = &stones[n];
    manipulations[n] = m;
    field_score = score;
  }
  bool try_put_stone(const uint8_t n, StoneManipulations m);
  const uint16_t score() const { return field_score; };
};

// Member Functions
bool Field::try_put_stone(const uint8_t n, StoneManipulations m) {
  const RawStone& stone = stones[n].raw;
  uint8_t additional_score = 0;
  RawField backup = raw;
  int8_t displacement_x = m.x,
         displacement_y = m.y;
  if (!(-7 <= displacement_y && displacement_y < 32 && -7 <= displacement_x && displacement_x < 32))  // 入力をVaridate
	  return false;
  switch (m.rotated) { // 害悪
    case ROTATED_90://90度反転 -> y終端でxインクリメント・x方向を反転(デクリメント)
      for (int x = 8; x < 0; --x) for (int y = 0; y > 0; ++y) {
        if (stone[y][x] == '1') {
          if (raw[y+displacement_y][x+displacement_x] != '0') {
            return false;
          } else if(raw[y+displacement_y +1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
        	continue;
          } else {
            raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
            ++additional_score;
          }
        }
      }
      put_stone(n, m, additional_score);
      break;
    case ROTATED_180://180度回転 -> x,y方向を反転(デクリメント)
      for (int y = 8; y > 0; --y) for (int x = 8; x > 0; --x) {
        if (stone[y][x] == '1') {
         if (raw[y+displacement_y][x+displacement_x] != '0') {
            return false;
         } else if(raw[y+displacement_y -1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
           	continue;
         } else {
           raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
           ++additional_score;
        }
       }
      }
      put_stone(n, m, additional_score);
      break;
    case ROTATED_270://270度回転 -> y終端でxインクリメント・y方向を反転(デクリメント)
      for (int x = 8; x > 0; ++x) for (int y = 8; y > 0; --y) {
        if (stone[y][x] == '1') {
        	if (raw[y+displacement_y][x+displacement_x] != '0') {
             return false;
            }else if(raw[y+displacement_y -1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
             continue;
            } else {
             raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
            ++additional_score;
           }
         }
        }
      put_stone(n, m, additional_score);
      break;
    case REVERSED://反転 -> x方向をデクリメントに
    	for (int y = 0; y < 8; ++y) for (int x = 8; x > 0; --x) {
    	 if (stone[y][x] == '1') {
    	    if (raw[y+displacement_y][x+displacement_x] != '0') {
    	        return false;
    	    } else if(raw[y+displacement_y +1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
    	        continue;
    	    } else {
    	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
    	        ++additional_score;
    	    }
    	  }
        }
        put_stone(n, m, additional_score);
    	break;
    case ROTATED_90 | REVERSED:
	//反転+90度回転 -> y終端でxデクリメント・y方向をデクリメントに
	   for (int x = 8; x > 0; --x) for (int y = 8; y > 0; --y) {
	    if (stone[y][x] == '1') {
	      if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	       } else if(raw[y+displacement_y -1][x+displacement_x -1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	       } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++additional_score;
	        }
	     }
	   }
           put_stone(n, m, additional_score);
      break;
    case ROTATED_180 | REVERSED:
	//反転+180度回転 -> yデクリメント
	   for (int y = 8; y > 0; --y) for (int x = 0; x < 8; ++x) {
	    if (stone[y][x] == '1') {
	     if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	     } else if(raw[y+displacement_y -1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	     } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++additional_score;
	     }
	    }
	   }
           put_stone(n, m, additional_score);
      break;
    case ROTATED_270 | REVERSED:
	//y終端でxインクリメント
	  for (int x = 0; x < 8; ++x) for (int y = 0; y < 8; ++y) {
	   if (stone[y][x] == '1') {
	    if (raw[y+displacement_y][x+displacement_x] != '0') {
	        return false;
	    } else if(raw[y+displacement_y +1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
	        continue;
	    } else {
	        raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
	        ++additional_score;
	    }
	   }
	  }
          put_stone(n, m, additional_score);
      break;
    default: // Regard as a non-manipulated stone
      for (int y = 0; y < 8; ++y) for (int x = 0; x < 8; ++x) {
        if (stone[y][x] == '1') {
        	if (raw[y+displacement_y][x+displacement_x] != '0') {
        	   return false;
        } else if(raw[y+displacement_y +1][x+displacement_x +1] != '0'){//1つ先が空いてる(隣接してる)か
        	   continue;
        } else {
        	   raw[y+displacement_y][x+displacement_x] = '2'; // 2を石とするならば
        	    ++additional_score;
        }
       }
      }
      put_stone(n, m, additional_score);
      break;
  }
  return true;
}

// Variable Declarations
Field max_score_field; // 最適な解があるField
Stone stones[256]; // 渡されるstoneを格納
uint16_t number_of_stones; // 渡されるstoneの数

// -- Function Declarations
void solve(Field f, uint8_t look_nth_stone);

void parse(Field*);
void parse_field(Field* f);
void parse_stone();

int main() {
  Field f;
//   get_problem_file();
  parse(&f);
  solve(f, 0);
  printf("%d\n", max_score_field.score());
  for (int y = 0; y < 32; ++y)  {
    for (int x = 0; x < 32; ++x) {
      printf("%c", max_score_field.raw[y][x]);
    }
    printf("\n");
  }
//   submit();
  return 0;
}

// -- Function Definitions

/**
 * solve
 *
 * 問題を解くぞい
 *
 * -- Args
 *  Field f: 現在のフィールドの状態
 *  uint8_t look_nth_stone: 何番の石を置こうとしているか
 *
 * -- Return
 *  void
 *
 * -- 副作用
 *  max_score_field
 */
void solve(Field f, uint8_t look_nth_stone) {

  if (look_nth_stone >= number_of_stones) { // 一番深いところでスコア更新
    if (f.score() > max_score_field.score()) { // より良い結果が出るならそれを最適解フィールドとして登録
      max_score_field = f;
    }
    return;
  }

  solve(f, look_nth_stone + 1); // 今回は石を置かなかった

  for (int i = 0; i < 8; ++i) { // 回転反転組み合わせを試す
    for (int y = -7; y < 32; ++y) for (int x = -7; x < 32; ++x) { // (32+8) * (32+8)のフィールドのどこかに置く
      if (f.try_put_stone(look_nth_stone, StoneManipulations(x, y, i)))
        solve(f, look_nth_stone + 1);
    }
  }
}

/*
 * parse_field
 *
 * 入力からField部分をパースする
 * -- Args
 *  Field* f: パースした結果を格納するfield
 *
 * -- 副作用
 *  stdin
 */
void parse_field(Field* f) {
  for (int i = 0; i < 32; ++i) {
    fread(f->raw[i].data(), sizeof(char[32]), 1, stdin);
    getc(stdin); // CR
    getc(stdin); // LF
  }
}

/*
 * parse_stone
 *
 * 入力からStone部分をパースする
 *
 * -- 副作用
 *  stdin
 *  stones
 */
void parse_stone() {
  for (int i = 0; i < number_of_stones; ++i) for (int j = 0; j < 8; ++j) {
    fread(stones[i].raw[j].data(), sizeof(char[8]), 1, stdin);
    getc(stdin); // CR
    getc(stdin); // LF
  }
}

/**
 * parse
 *
 * 入力をパースする
 *
 * -- Args
 *  Field* f: パースした結果を格納するFieldのポインタ
 *
 * -- 副作用
 *  stdin
 *  stones
 */
void parse(Field* f) {
  parse_field(f);
  getc(stdin); // 改行読み捨て CR
  getc(stdin); // LF
  scanf("%" SCNu16 "¥n", &number_of_stones); // SCNu8 is placeholder for uint8_t declared in cinttypes
  for (int i = 0; i < number_of_stones; ++i) {
    parse_stone();
    getc(stdin); // 改行読み捨て CR
    getc(stdin); // LF
  }
}
<|endoftext|>


<commit_before>#include <time.h>
#include <unistd.h>

#include <cstdlib>
#include <fstream>
#include <map>

#include <QDebug>
#include <QDir>
#include <QTimer>
#include <QVBoxLayout>

#include "selfdrive/ui/installer/installer.h"
#include "selfdrive/ui/qt/util.h"
#include "selfdrive/ui/qt/qt_window.h"

std::string get_str(std::string const s) {
  std::string::size_type pos = s.find('?');
  assert(pos != std::string::npos);
  return s.substr(0, pos);
}

// Leave some extra space for the fork installer
const std::string GIT_URL = get_str("https://github.com/commaai/openpilot.git" "?                                                                ");
const std::string BRANCH_STR = get_str(BRANCH "?                                                                ");

#define GIT_SSH_URL "git@github.com:commaai/openpilot.git"
#define CONTINUE_PATH "/data/continue.sh"

const QString CACHE_PATH = "/data/openpilot.cache";

#define INSTALL_PATH "/data/openpilot"
#define TMP_INSTALL_PATH "/data/tmppilot"

extern const uint8_t str_continue[] asm("_binary_selfdrive_ui_installer_continue_" BRAND "_sh_start");
extern const uint8_t str_continue_end[] asm("_binary_selfdrive_ui_installer_continue_" BRAND "_sh_end");

bool time_valid() {
  time_t rawtime;
  time(&rawtime);

  struct tm * sys_time = gmtime(&rawtime);
  return (1900 + sys_time->tm_year) >= 2020;
}

void run(const char* cmd) {
  int err = std::system(cmd);
  assert(err == 0);
}

Installer::Installer(QWidget *parent) : QWidget(parent) {
  QVBoxLayout *layout = new QVBoxLayout(this);
  layout->setContentsMargins(150, 290, 150, 150);
  layout->setSpacing(0);

  QLabel *title = new QLabel(tr("Installing..."));
  title->setStyleSheet("font-size: 90px; font-weight: 600;");
  layout->addWidget(title, 0, Qt::AlignTop);

  layout->addSpacing(170);

  bar = new QProgressBar();
  bar->setRange(0, 100);
  bar->setTextVisible(false);
  bar->setFixedHeight(72);
  layout->addWidget(bar, 0, Qt::AlignTop);

  layout->addSpacing(30);

  val = new QLabel("0%");
  val->setStyleSheet("font-size: 70px; font-weight: 300;");
  layout->addWidget(val, 0, Qt::AlignTop);

  layout->addStretch();

  QObject::connect(&proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &Installer::cloneFinished);
  QObject::connect(&proc, &QProcess::readyReadStandardError, this, &Installer::readProgress);

  QTimer::singleShot(100, this, &Installer::doInstall);

  setStyleSheet(R"(
    * {
      font-family: Inter;
      color: white;
      background-color: black;
    }
    QProgressBar {
      border: none;
      background-color: #292929;
    }
    QProgressBar::chunk {
      background-color: #364DEF;
    }
  )");
}

void Installer::updateProgress(int percent) {
  bar->setValue(percent);
  val->setText(QString("%1%").arg(percent));
  update();
}

void Installer::doInstall() {
  // wait for valid time
  while (!time_valid()) {
    usleep(500 * 1000);
    qDebug() << "Waiting for valid time";
  }

  // cleanup previous install attemps
  run("rm -rf " TMP_INSTALL_PATH " " INSTALL_PATH);

  // do the install
  if (QDir(CACHE_PATH).exists()) {
    cachedFetch(CACHE_PATH);
  } else {
    freshClone();
  }
}

void Installer::freshClone() {
  qDebug() << "Doing fresh clone";
  proc.start("git", {"clone", "--progress", GIT_URL.c_str(), "-b", BRANCH_STR.c_str(),
                     "--depth=1", "--recurse-submodules", TMP_INSTALL_PATH});
}

void Installer::cachedFetch(const QString &cache) {
  qDebug() << "Fetching with cache: " << cache;

  run(QString("cp -rp %1 %2").arg(cache, TMP_INSTALL_PATH).toStdString().c_str());
  int err = chdir(TMP_INSTALL_PATH);
  assert(err == 0);
  run(("git remote set-branches --add origin " + BRANCH_STR).c_str());

  updateProgress(10);

  proc.setWorkingDirectory(TMP_INSTALL_PATH);
  proc.start("git", {"fetch", "--progress", "origin", BRANCH_STR.c_str()});
}

void Installer::readProgress() {
  const QVector<QPair<QString, int>> stages = {
    // prefix, weight in percentage
    {tr("Receiving objects: "), 91},
    {tr("Resolving deltas: "), 2},
    {tr("Updating files: "), 7},
  };

  auto line = QString(proc.readAllStandardError());

  int base = 0;
  for (const QPair kv : stages) {
    if (line.startsWith(kv.first)) {
      auto perc = line.split(kv.first)[1].split("%")[0];
      int p = base + int(perc.toFloat() / 100. * kv.second);
      updateProgress(p);
      break;
    }
    base += kv.second;
  }
}

void Installer::cloneFinished(int exitCode, QProcess::ExitStatus exitStatus) {
  qDebug() << "git finished with " << exitCode;
  assert(exitCode == 0);

  updateProgress(100);

  // ensure correct branch is checked out
  int err = chdir(TMP_INSTALL_PATH);
  assert(err == 0);
  run(("git checkout " + BRANCH_STR).c_str());
  run(("git reset --hard origin/" + BRANCH_STR).c_str());
  run("git submodule update --init");

  // move into place
  run("mv " TMP_INSTALL_PATH " " INSTALL_PATH);

#ifdef INTERNAL
  run("mkdir -p /data/params/d/");

  std::map<std::string, std::string> params = {
    {"SshEnabled", "1"},
    {"RecordFrontLock", "1"},
    {"GithubSshKeys", SSH_KEYS},
  };
  for (const auto& [key, value] : params) {
    std::ofstream param;
    param.open("/data/params/d/" + key);
    param << value;
    param.close();
  }
  run("cd " INSTALL_PATH " && "
      "git remote set-url origin --push " GIT_SSH_URL " && "
      "git config --replace-all remote.origin.fetch \"+refs/heads/*:refs/remotes/origin/*\"");
#endif

  // write continue.sh
  FILE *of = fopen("/data/continue.sh.new", "wb");
  assert(of != NULL);

  size_t num = str_continue_end - str_continue;
  size_t num_written = fwrite(str_continue, 1, num, of);
  assert(num == num_written);
  fclose(of);

  run("chmod +x /data/continue.sh.new");
  run("mv /data/continue.sh.new " CONTINUE_PATH);

  // wait for the installed software's UI to take over
  QTimer::singleShot(60 * 1000, &QCoreApplication::quit);
}

int main(int argc, char *argv[]) {
  initApp(argc, argv);
  QApplication a(argc, argv);
  Installer installer;
  setMainWindow(&installer);
  return a.exec();
}
<commit_msg>internal installer: set param for disable radar toggle<commit_after>#include <time.h>
#include <unistd.h>

#include <cstdlib>
#include <fstream>
#include <map>

#include <QDebug>
#include <QDir>
#include <QTimer>
#include <QVBoxLayout>

#include "selfdrive/ui/installer/installer.h"
#include "selfdrive/ui/qt/util.h"
#include "selfdrive/ui/qt/qt_window.h"

std::string get_str(std::string const s) {
  std::string::size_type pos = s.find('?');
  assert(pos != std::string::npos);
  return s.substr(0, pos);
}

// Leave some extra space for the fork installer
const std::string GIT_URL = get_str("https://github.com/commaai/openpilot.git" "?                                                                ");
const std::string BRANCH_STR = get_str(BRANCH "?                                                                ");

#define GIT_SSH_URL "git@github.com:commaai/openpilot.git"
#define CONTINUE_PATH "/data/continue.sh"

const QString CACHE_PATH = "/data/openpilot.cache";

#define INSTALL_PATH "/data/openpilot"
#define TMP_INSTALL_PATH "/data/tmppilot"

extern const uint8_t str_continue[] asm("_binary_selfdrive_ui_installer_continue_" BRAND "_sh_start");
extern const uint8_t str_continue_end[] asm("_binary_selfdrive_ui_installer_continue_" BRAND "_sh_end");

bool time_valid() {
  time_t rawtime;
  time(&rawtime);

  struct tm * sys_time = gmtime(&rawtime);
  return (1900 + sys_time->tm_year) >= 2020;
}

void run(const char* cmd) {
  int err = std::system(cmd);
  assert(err == 0);
}

Installer::Installer(QWidget *parent) : QWidget(parent) {
  QVBoxLayout *layout = new QVBoxLayout(this);
  layout->setContentsMargins(150, 290, 150, 150);
  layout->setSpacing(0);

  QLabel *title = new QLabel(tr("Installing..."));
  title->setStyleSheet("font-size: 90px; font-weight: 600;");
  layout->addWidget(title, 0, Qt::AlignTop);

  layout->addSpacing(170);

  bar = new QProgressBar();
  bar->setRange(0, 100);
  bar->setTextVisible(false);
  bar->setFixedHeight(72);
  layout->addWidget(bar, 0, Qt::AlignTop);

  layout->addSpacing(30);

  val = new QLabel("0%");
  val->setStyleSheet("font-size: 70px; font-weight: 300;");
  layout->addWidget(val, 0, Qt::AlignTop);

  layout->addStretch();

  QObject::connect(&proc, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &Installer::cloneFinished);
  QObject::connect(&proc, &QProcess::readyReadStandardError, this, &Installer::readProgress);

  QTimer::singleShot(100, this, &Installer::doInstall);

  setStyleSheet(R"(
    * {
      font-family: Inter;
      color: white;
      background-color: black;
    }
    QProgressBar {
      border: none;
      background-color: #292929;
    }
    QProgressBar::chunk {
      background-color: #364DEF;
    }
  )");
}

void Installer::updateProgress(int percent) {
  bar->setValue(percent);
  val->setText(QString("%1%").arg(percent));
  update();
}

void Installer::doInstall() {
  // wait for valid time
  while (!time_valid()) {
    usleep(500 * 1000);
    qDebug() << "Waiting for valid time";
  }

  // cleanup previous install attemps
  run("rm -rf " TMP_INSTALL_PATH " " INSTALL_PATH);

  // do the install
  if (QDir(CACHE_PATH).exists()) {
    cachedFetch(CACHE_PATH);
  } else {
    freshClone();
  }
}

void Installer::freshClone() {
  qDebug() << "Doing fresh clone";
  proc.start("git", {"clone", "--progress", GIT_URL.c_str(), "-b", BRANCH_STR.c_str(),
                     "--depth=1", "--recurse-submodules", TMP_INSTALL_PATH});
}

void Installer::cachedFetch(const QString &cache) {
  qDebug() << "Fetching with cache: " << cache;

  run(QString("cp -rp %1 %2").arg(cache, TMP_INSTALL_PATH).toStdString().c_str());
  int err = chdir(TMP_INSTALL_PATH);
  assert(err == 0);
  run(("git remote set-branches --add origin " + BRANCH_STR).c_str());

  updateProgress(10);

  proc.setWorkingDirectory(TMP_INSTALL_PATH);
  proc.start("git", {"fetch", "--progress", "origin", BRANCH_STR.c_str()});
}

void Installer::readProgress() {
  const QVector<QPair<QString, int>> stages = {
    // prefix, weight in percentage
    {tr("Receiving objects: "), 91},
    {tr("Resolving deltas: "), 2},
    {tr("Updating files: "), 7},
  };

  auto line = QString(proc.readAllStandardError());

  int base = 0;
  for (const QPair kv : stages) {
    if (line.startsWith(kv.first)) {
      auto perc = line.split(kv.first)[1].split("%")[0];
      int p = base + int(perc.toFloat() / 100. * kv.second);
      updateProgress(p);
      break;
    }
    base += kv.second;
  }
}

void Installer::cloneFinished(int exitCode, QProcess::ExitStatus exitStatus) {
  qDebug() << "git finished with " << exitCode;
  assert(exitCode == 0);

  updateProgress(100);

  // ensure correct branch is checked out
  int err = chdir(TMP_INSTALL_PATH);
  assert(err == 0);
  run(("git checkout " + BRANCH_STR).c_str());
  run(("git reset --hard origin/" + BRANCH_STR).c_str());
  run("git submodule update --init");

  // move into place
  run("mv " TMP_INSTALL_PATH " " INSTALL_PATH);

#ifdef INTERNAL
  run("mkdir -p /data/params/d/");

  std::map<std::string, std::string> params = {
    {"SshEnabled", "1"},
    {"RecordFrontLock", "1"},
    {"DisableRadar_Allow", "1"},
    {"GithubSshKeys", SSH_KEYS},
  };
  for (const auto& [key, value] : params) {
    std::ofstream param;
    param.open("/data/params/d/" + key);
    param << value;
    param.close();
  }
  run("cd " INSTALL_PATH " && "
      "git remote set-url origin --push " GIT_SSH_URL " && "
      "git config --replace-all remote.origin.fetch \"+refs/heads/*:refs/remotes/origin/*\"");
#endif

  // write continue.sh
  FILE *of = fopen("/data/continue.sh.new", "wb");
  assert(of != NULL);

  size_t num = str_continue_end - str_continue;
  size_t num_written = fwrite(str_continue, 1, num, of);
  assert(num == num_written);
  fclose(of);

  run("chmod +x /data/continue.sh.new");
  run("mv /data/continue.sh.new " CONTINUE_PATH);

  // wait for the installed software's UI to take over
  QTimer::singleShot(60 * 1000, &QCoreApplication::quit);
}

int main(int argc, char *argv[]) {
  initApp(argc, argv);
  QApplication a(argc, argv);
  Installer installer;
  setMainWindow(&installer);
  return a.exec();
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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 "chrome/browser/chromeos/external_cookie_handler.h"

#include <set>
#include <vector>

#include "base/basictypes.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
#include "net/base/cookie_options.h"
#include "net/base/cookie_store.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace chromeos {

typedef testing::Test ExternalCookieHandlerTest;

static const std::string cookie1 = "coookie1\n";
static const std::string cookie2 = "coookie2\n";
static const std::string cookie3 = "coookie3";

class MockCookieStore : public net::CookieStore {
 public:
  MockCookieStore() : expected_url_(ExternalCookieHandler::kGoogleAccountsUrl) {
    cookies_.insert(cookie1);
    cookies_.insert(cookie2);
    cookies_.insert(cookie3);
  }
  virtual ~MockCookieStore() {}

  virtual bool SetCookie(const GURL& url, const std::string& cookie_line) {
    EXPECT_TRUE(false);
    return true;
  }
  virtual bool SetCookieWithOptions(const GURL& url,
                                    const std::string& cookie_line,
                                    const net::CookieOptions& options) {
    EXPECT_FALSE(options.exclude_httponly());
    EXPECT_EQ(expected_url_, url);
    std::set<std::string>::iterator it;
    it = cookies_.find(cookie_line);
    bool has_cookie = cookies_.end() != it;
    if (has_cookie)
      cookies_.erase(it);
    return has_cookie;
  }

  virtual bool SetCookieWithCreationTime(const GURL& url,
                                         const std::string& cookie_line,
                                         const base::Time& creation_time) {
    EXPECT_TRUE(false);
    return true;
  }
  virtual bool SetCookieWithCreationTimeWithOptions(
                                         const GURL& url,
                                         const std::string& cookie_line,
                                         const base::Time& creation_time,
                                         const net::CookieOptions& options) {
    EXPECT_TRUE(false);
    return true;
  }

  virtual void SetCookies(const GURL& url,
                          const std::vector<std::string>& cookies) {
    EXPECT_TRUE(false);
  }
  virtual void SetCookiesWithOptions(const GURL& url,
                                     const std::vector<std::string>& cookies,
                                     const net::CookieOptions& options) {
    EXPECT_TRUE(false);
  }

  virtual std::string GetCookies(const GURL& url) {
    EXPECT_TRUE(false);
    return std::string();
  }
  virtual std::string GetCookiesWithOptions(const GURL& url,
                                            const net::CookieOptions& options) {
    EXPECT_TRUE(false);
    return std::string();
  }

  virtual void DeleteCookie(const GURL& url,
                            const std::string& cookie_name) {
    EXPECT_TRUE(false);
  }

 private:
  std::set<std::string> cookies_;
  const GURL expected_url_;

  DISALLOW_EVIL_CONSTRUCTORS(MockCookieStore);
};

TEST_F(ExternalCookieHandlerTest, MockCookieStoreSanityTest) {
  GURL url(ExternalCookieHandler::kGoogleAccountsUrl);
  // Need to use a scoped_refptr here because net::CookieStore extends
  // base::RefCountedThreadSafe<> in base/ref_counted.h.
  scoped_refptr<MockCookieStore> cookie_store(new MockCookieStore);
  net::CookieOptions options;
  options.set_include_httponly();
  EXPECT_TRUE(cookie_store->SetCookieWithOptions(url, cookie1, options));
  EXPECT_TRUE(cookie_store->SetCookieWithOptions(url, cookie2, options));
  EXPECT_TRUE(cookie_store->SetCookieWithOptions(url, cookie3, options));
  EXPECT_FALSE(cookie_store->SetCookieWithOptions(url, cookie1, options));
  EXPECT_FALSE(cookie_store->SetCookieWithOptions(url, cookie2, options));
  EXPECT_FALSE(cookie_store->SetCookieWithOptions(url, cookie3, options));
}

class MockReader : public PipeReader {
 public:
  explicit MockReader(const std::vector<std::string>& cookies)
      : data_(cookies) {
  }

  std::string Read(const uint32 bytes_to_read) {
    std::string to_return;
    if (!data_.empty()) {
      to_return = data_.back();
      data_.pop_back();
    }
    return to_return;
  }
 private:
  std::vector<std::string> data_;
};

TEST_F(ExternalCookieHandlerTest, SuccessfulReadTest) {
  GURL url(ExternalCookieHandler::kGoogleAccountsUrl);

  scoped_refptr<MockCookieStore> cookie_store(new MockCookieStore);

  std::vector<std::string> cookies;
  cookies.push_back(cookie3);
  cookies.push_back(cookie2);
  cookies.push_back(cookie1);
  MockReader *reader = new MockReader(cookies);

  ExternalCookieHandler handler(reader);  // takes ownership.
  EXPECT_TRUE(handler.HandleCookies(cookie_store.get()));
}

TEST_F(ExternalCookieHandlerTest, SuccessfulSlowReadTest) {
  GURL url(ExternalCookieHandler::kGoogleAccountsUrl);

  scoped_refptr<MockCookieStore> cookie_store(new MockCookieStore);

  std::vector<std::string> cookies;
  cookies.push_back(cookie3);
  cookies.push_back(cookie2.substr(2));
  cookies.push_back(cookie2.substr(0, 2));
  cookies.push_back(cookie1);
  MockReader *reader = new MockReader(cookies);

  ExternalCookieHandler handler(reader);  // takes ownership.
  EXPECT_TRUE(handler.HandleCookies(cookie_store.get()));
}

}  // namespace chromeos
<commit_msg>Fix ChromiumOS build.<commit_after>// Copyright (c) 2009 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 "chrome/browser/chromeos/external_cookie_handler.h"

#include <set>
#include <vector>

#include "base/basictypes.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
#include "net/base/cookie_options.h"
#include "net/base/cookie_store.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace chromeos {

typedef testing::Test ExternalCookieHandlerTest;

static const std::string cookie1 = "coookie1\n";
static const std::string cookie2 = "coookie2\n";
static const std::string cookie3 = "coookie3";

class MockCookieStore : public net::CookieStore {
 public:
  MockCookieStore() : expected_url_(ExternalCookieHandler::kGoogleAccountsUrl) {
    cookies_.insert(cookie1);
    cookies_.insert(cookie2);
    cookies_.insert(cookie3);
  }
  virtual ~MockCookieStore() {}

  virtual bool SetCookieWithOptions(const GURL& url,
                                    const std::string& cookie_line,
                                    const net::CookieOptions& options) {
    EXPECT_FALSE(options.exclude_httponly());
    EXPECT_EQ(expected_url_, url);
    std::set<std::string>::iterator it;
    it = cookies_.find(cookie_line);
    bool has_cookie = cookies_.end() != it;
    if (has_cookie)
      cookies_.erase(it);
    return has_cookie;
  }

  virtual std::string GetCookiesWithOptions(const GURL& url,
                                            const net::CookieOptions& options) {
    EXPECT_TRUE(false);
    return std::string();
  }

  virtual void DeleteCookie(const GURL& url,
                            const std::string& cookie_name) {
    EXPECT_TRUE(false);
  }

  virtual CookieMonster* GetCookieMonster() { return NULL; }

 private:
  std::set<std::string> cookies_;
  const GURL expected_url_;

  DISALLOW_EVIL_CONSTRUCTORS(MockCookieStore);
};

TEST_F(ExternalCookieHandlerTest, MockCookieStoreSanityTest) {
  GURL url(ExternalCookieHandler::kGoogleAccountsUrl);
  // Need to use a scoped_refptr here because net::CookieStore extends
  // base::RefCountedThreadSafe<> in base/ref_counted.h.
  scoped_refptr<MockCookieStore> cookie_store(new MockCookieStore);
  net::CookieOptions options;
  options.set_include_httponly();
  EXPECT_TRUE(cookie_store->SetCookieWithOptions(url, cookie1, options));
  EXPECT_TRUE(cookie_store->SetCookieWithOptions(url, cookie2, options));
  EXPECT_TRUE(cookie_store->SetCookieWithOptions(url, cookie3, options));
  EXPECT_FALSE(cookie_store->SetCookieWithOptions(url, cookie1, options));
  EXPECT_FALSE(cookie_store->SetCookieWithOptions(url, cookie2, options));
  EXPECT_FALSE(cookie_store->SetCookieWithOptions(url, cookie3, options));
}

class MockReader : public PipeReader {
 public:
  explicit MockReader(const std::vector<std::string>& cookies)
      : data_(cookies) {
  }

  std::string Read(const uint32 bytes_to_read) {
    std::string to_return;
    if (!data_.empty()) {
      to_return = data_.back();
      data_.pop_back();
    }
    return to_return;
  }
 private:
  std::vector<std::string> data_;
};

TEST_F(ExternalCookieHandlerTest, SuccessfulReadTest) {
  GURL url(ExternalCookieHandler::kGoogleAccountsUrl);

  scoped_refptr<MockCookieStore> cookie_store(new MockCookieStore);

  std::vector<std::string> cookies;
  cookies.push_back(cookie3);
  cookies.push_back(cookie2);
  cookies.push_back(cookie1);
  MockReader *reader = new MockReader(cookies);

  ExternalCookieHandler handler(reader);  // takes ownership.
  EXPECT_TRUE(handler.HandleCookies(cookie_store.get()));
}

TEST_F(ExternalCookieHandlerTest, SuccessfulSlowReadTest) {
  GURL url(ExternalCookieHandler::kGoogleAccountsUrl);

  scoped_refptr<MockCookieStore> cookie_store(new MockCookieStore);

  std::vector<std::string> cookies;
  cookies.push_back(cookie3);
  cookies.push_back(cookie2.substr(2));
  cookies.push_back(cookie2.substr(0, 2));
  cookies.push_back(cookie1);
  MockReader *reader = new MockReader(cookies);

  ExternalCookieHandler handler(reader);  // takes ownership.
  EXPECT_TRUE(handler.HandleCookies(cookie_store.get()));
}

}  // namespace chromeos
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <string>

extern "C" {
    void* cvopen(const char* path);
    void cvclose(void* context);
    int cvcapture(void* context, void* buffer, size_t width, size_t height);
}

#include "opencv2/opencv.hpp"

void* cvopen(const char* path) {
    cv::VideoCapture* context;
    if (path) {
        context = new cv::VideoCapture(std::string(path));
    } else {
        context = new cv::VideoCapture(0);
    }
    return reinterpret_cast<void*>(context);
}

void cvclose(void* context) {
    cv::VideoCapture* cap = reinterpret_cast<cv::VideoCapture*>(context);
    delete cap;
}

static void describe_image(const char* stage, const cv::Mat& mat) {
    fprintf(stderr, "%s: %d x %d\n", stage, mat.size().width, mat.size().height);
}

int cvcapture(void* context, void* buffer, size_t width, size_t height) {
    cv::VideoCapture* cap = reinterpret_cast<cv::VideoCapture*>(context);
    cap->set(CV_CAP_PROP_FRAME_WIDTH, width);
    cap->set(CV_CAP_PROP_FRAME_HEIGHT, height);
    cap->set(CV_CAP_PROP_FOURCC, CV_FOURCC('B', 'G', 'R', 3));

    if (cap->get(CV_CAP_PROP_FRAME_WIDTH) != (double)width) {
        fprintf(stderr, "Incorrect width set on cap: %f\n", cap->get(CV_CAP_PROP_FRAME_WIDTH));
        return 0;
    }

    if (cap->get(CV_CAP_PROP_FRAME_HEIGHT) != (double)height) {
        fprintf(stderr, "Incorrect height set on cap: %f\n", cap->get(CV_CAP_PROP_FRAME_HEIGHT));
        return 0;
    }

    cv::Mat colour_image, greyscale_image, denoised_image;

    if (!cap->isOpened()) {
        return 0;
    }

    (*cap) >> colour_image;
    describe_image("colour", colour_image);
    cv::cvtColor(colour_image, greyscale_image, cv::COLOR_BGR2GRAY);
    describe_image("greyscale", greyscale_image);
    cv::medianBlur(greyscale_image, denoised_image, 3);
    describe_image("denoised", denoised_image);
    if (!denoised_image.isContinuous()) {
        return 0;
    }
    int died_horribly = 0;
    if (denoised_image.size().width != width) {
        fprintf(
            stderr,
            "Width mismatch: %d expected, %d actual\n",
            width,
            denoised_image.size().width
        );
        died_horribly = 1;
    }
    if (denoised_image.size().height != height) {
        fprintf(
            stderr,
            "Height mismatch: %d expected, %d actual\n",
            height,
            denoised_image.size().height
        );
        died_horribly = 1;
    }
    if (died_horribly) {
        return 0;
    }
    memcpy(
        buffer,
        denoised_image.ptr(),
        width * height
    );
    return 1;
}
<commit_msg>Drop debugging code<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <string>

extern "C" {
    void* cvopen(const char* path);
    void cvclose(void* context);
    int cvcapture(void* context, void* buffer, size_t width, size_t height);
}

#include "opencv2/opencv.hpp"

void* cvopen(const char* path) {
    cv::VideoCapture* context;
    if (path) {
        context = new cv::VideoCapture(std::string(path));
    } else {
        context = new cv::VideoCapture(0);
    }
    return reinterpret_cast<void*>(context);
}

void cvclose(void* context) {
    cv::VideoCapture* cap = reinterpret_cast<cv::VideoCapture*>(context);
    delete cap;
}

int cvcapture(void* context, void* buffer, size_t width, size_t height) {
    cv::VideoCapture* cap = reinterpret_cast<cv::VideoCapture*>(context);
    cap->set(CV_CAP_PROP_FRAME_WIDTH, width);
    cap->set(CV_CAP_PROP_FRAME_HEIGHT, height);
    cap->set(CV_CAP_PROP_FOURCC, CV_FOURCC('B', 'G', 'R', 3));

    if (cap->get(CV_CAP_PROP_FRAME_WIDTH) != (double)width) {
        fprintf(stderr, "Incorrect width set on cap: %f\n", cap->get(CV_CAP_PROP_FRAME_WIDTH));
        return 0;
    }

    if (cap->get(CV_CAP_PROP_FRAME_HEIGHT) != (double)height) {
        fprintf(stderr, "Incorrect height set on cap: %f\n", cap->get(CV_CAP_PROP_FRAME_HEIGHT));
        return 0;
    }

    cv::Mat colour_image, greyscale_image, denoised_image;

    if (!cap->isOpened()) {
        return 0;
    }

    (*cap) >> colour_image;
    cv::cvtColor(colour_image, greyscale_image, cv::COLOR_BGR2GRAY);
    cv::medianBlur(greyscale_image, denoised_image, 3);
    if (!denoised_image.isContinuous()) {
        return 0;
    }
    int died_horribly = 0;
    if (denoised_image.size().width != width) {
        fprintf(
            stderr,
            "Width mismatch: %d expected, %d actual\n",
            width,
            denoised_image.size().width
        );
        died_horribly = 1;
    }
    if (denoised_image.size().height != height) {
        fprintf(
            stderr,
            "Height mismatch: %d expected, %d actual\n",
            height,
            denoised_image.size().height
        );
        died_horribly = 1;
    }
    if (died_horribly) {
        return 0;
    }
    memcpy(
        buffer,
        denoised_image.ptr(),
        width * height
    );
    return 1;
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(FUNCTIONLANG_HEADER_GUARD_1357924680)
#define FUNCTIONLANG_HEADER_GUARD_1357924680

// Base header file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

#include <vector>

#include <XalanDOM/XalanElement.hpp>
#include <XalanDOM/XalanNode.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

// Base class header file...
#include <XPath/Function.hpp>

#include <XPath/XObject.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPathExecutionContext.hpp>

/**
 * XPath implementation of "lang" function.
 */
//
// These are all inline, even though
// there are virtual functions, because we expect that they will only be
// needed by the XPath class.
class XALAN_XPATH_EXPORT FunctionLang : public Function
{
public:

	// These methods are inherited from Function ...

	virtual XObject*
	execute(
			XPathExecutionContext&			executionContext,
			XalanNode*						context,
			int								/* opPos */,
			const XObjectArgVectorType&		args)
	{
		if (args.size() != 1)
		{
			executionContext.error("The lang() function takes one argument!",
								   context);
		}

		const XalanNode*		parent = context;

		bool					fMatch = false;

		const XalanDOMString	lang(args[0]->str());

		while(0 != parent)
		{
			if(XalanNode::ELEMENT_NODE == parent->getNodeType())
			{
				const XalanElement* const	theElementNode =
					static_cast<const XalanElement*>(parent);

				const XalanDOMString		langVal =
					theElementNode->getAttribute("xml:lang");

				if(0 != length(langVal))
				{
					if(startsWith(toLowerCase(langVal), toLowerCase(lang)))
					{
						const unsigned int	valLen = length(lang);

						if(length(langVal) == valLen ||
						   charAt(langVal, valLen) == '-')
						{
							fMatch = true;

							break;
						}
					}
				}
			}

			parent = executionContext.getParentOfNode(*parent);
		}

		return executionContext.getXObjectFactory().createBoolean(fMatch);
	}

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
	virtual Function*
#else
	virtual FunctionLang*
#endif
	clone() const
	{
		return new FunctionLang(*this);
	}

private:

	// Not implemented...
	FunctionLang&
	operator=(const FunctionLang&);

	bool
	operator==(const FunctionLang&) const;
};

#endif	// FUNCTIONLANG_HEADER_GUARD_1357924680
<commit_msg>Added XALAN_STATIC_UCODE_STRING to constant.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(FUNCTIONLANG_HEADER_GUARD_1357924680)
#define FUNCTIONLANG_HEADER_GUARD_1357924680

// Base header file.  Must be first.
#include <XPath/XPathDefinitions.hpp>

#include <vector>

#include <XalanDOM/XalanElement.hpp>
#include <XalanDOM/XalanNode.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>

// Base class header file...
#include <XPath/Function.hpp>

#include <XPath/XObject.hpp>
#include <XPath/XObjectFactory.hpp>
#include <XPath/XPathExecutionContext.hpp>

/**
 * XPath implementation of "lang" function.
 */
//
// These are all inline, even though
// there are virtual functions, because we expect that they will only be
// needed by the XPath class.
class XALAN_XPATH_EXPORT FunctionLang : public Function
{
public:

	// These methods are inherited from Function ...

	virtual XObject*
	execute(
			XPathExecutionContext&			executionContext,
			XalanNode*						context,
			int								/* opPos */,
			const XObjectArgVectorType&		args)
	{
		if (args.size() != 1)
		{
			executionContext.error("The lang() function takes one argument!",
								   context);
		}

		const XalanNode*		parent = context;

		bool					fMatch = false;

		const XalanDOMString	lang(args[0]->str());

		while(0 != parent)
		{
			if(XalanNode::ELEMENT_NODE == parent->getNodeType())
			{
				const XalanElement* const	theElementNode =
					static_cast<const XalanElement*>(parent);

				const XalanDOMString		langVal =
					theElementNode->getAttribute(XALAN_STATIC_UCODE_STRING("xml:lang"));

				if(0 != length(langVal))
				{
					if(startsWith(toLowerCase(langVal), toLowerCase(lang)))
					{
						const unsigned int	valLen = length(lang);

						if(length(langVal) == valLen ||
						   charAt(langVal, valLen) == '-')
						{
							fMatch = true;

							break;
						}
					}
				}
			}

			parent = executionContext.getParentOfNode(*parent);
		}

		return executionContext.getXObjectFactory().createBoolean(fMatch);
	}

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
	virtual Function*
#else
	virtual FunctionLang*
#endif
	clone() const
	{
		return new FunctionLang(*this);
	}

private:

	// Not implemented...
	FunctionLang&
	operator=(const FunctionLang&);

	bool
	operator==(const FunctionLang&) const;
};

#endif	// FUNCTIONLANG_HEADER_GUARD_1357924680
<|endoftext|>