<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <iostream>
#include <fstream>

#include <minizinc/model.hh>
#include <minizinc/parser.hh>
#include <minizinc/prettyprinter.hh>
#include <minizinc/typecheck.hh>
#include <minizinc/astexception.hh>
#include <minizinc/hash.hh>
#include <minizinc/eval_par.hh>
#include <minizinc/builtins.hh>
#include <minizinc/file_utils.hh>

using namespace MiniZinc;
using namespace std;

int main(int argc, char** argv) {
  string filename;

  string flag_output_file;

  bool flag_output_comments = true;
  bool flag_output_flush = true;
  string solfile;
  int flag_ignore_lines = 0;
  istream& solstream = cin;

  string solution_separator = "----------";
  string unsatisfiable_msg  = "=====UNSATISFIABLE=====";
  string unbounded_msg      = "=====UNBOUNDED=====";
  string unknown_msg        = "=====UNKNOWN=====";
  string search_complete_msg= "==========";

  vector<string> includePaths;
  string std_lib_dir;
  if (char* MZNSTDLIBDIR = getenv("MZN_STDLIB_DIR")) {
    std_lib_dir = string(MZNSTDLIBDIR);
  }

  if (argc < 2)
    goto error;

  GC::init();

  for (int i=1; i<argc; i++) {
    if (string(argv[i])==string("--version")) {
      std::cout << "NICTA MiniZinc solution printing tool, version "
      << MZN_VERSION_MAJOR << "." << MZN_VERSION_MINOR << "." << MZN_VERSION_PATCH << std::endl;
      std::cout << "Copyright (C) 2014 Monash University and NICTA" << std::endl;
      std::exit(EXIT_SUCCESS);
    }
    if (string(argv[i])==string("-h") || string(argv[i])==string("--help")) {
        goto error;
    } else if (string(argv[i])=="-o" || string(argv[i])=="--output-to-file") {
      i++;
      if (i==argc)
        goto error;
      flag_output_file = argv[i];
    } else if (string(argv[i])=="--stdlib-dir") {
      i++;
      if (i==argc)
        goto error;
      std_lib_dir = argv[i];
    } else if (string(argv[i])=="--no-flush-output") {
      flag_output_flush = false;
    } else if (string(argv[i])=="--no-output-comments") {
      flag_output_comments = false;
    } else if (string(argv[i])=="-i" ||
               string(argv[i])=="--ignore-lines" ||
               string(argv[i])=="--ignore-leading-lines") {
      ++i;
      if (i==argc)
        goto error;
      flag_ignore_lines = atoi(argv[i]);
    } else if (string(argv[i])=="--soln-sep" ||
               string(argv[i])=="--soln-separator" ||
               string(argv[i])=="--solution-separator") {
      ++i;
      if (i==argc)
        goto error;
      solution_separator = string(argv[i]);
    } else if (string(argv[i])=="--unsat-msg" ||
               string(argv[i])=="--unsatisfiable-msg") {
      ++i;
      if (i==argc)
        goto error;
      unsatisfiable_msg = string(argv[i]);
    } else if (string(argv[i])=="--unbounded-msg") {
      ++i;
      if (i==argc)
        goto error;
      unbounded_msg = string(argv[i]);
    } else if (string(argv[i])=="--unknown-msg") {
      ++i;
      if (i==argc)
        goto error;
      unknown_msg = string(argv[i]);
    } else if (string(argv[i])=="--search-complete-msg") {
      ++i;
      if (i==argc)
        goto error;
      search_complete_msg = string(argv[i]);
    } else {
      filename = argv[i++];
      if (filename.length()<=4 ||
          filename.substr(filename.length()-4,string::npos) != ".ozn") {
        std::cerr << "Invalid .ozn file " << filename << "." << std::endl;
        goto error;
      }
    }
  }

  if (std_lib_dir=="") {
    std::string mypath = FileUtils::progpath();
    if (!mypath.empty()) {
      if (FileUtils::file_exists(mypath+"/share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/share/minizinc";
      } else if (FileUtils::file_exists(mypath+"/../share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/../share/minizinc";
      } else if (FileUtils::file_exists(mypath+"/../../share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/../../share/minizinc";
      }
    }
  }

  if (std_lib_dir=="") {
    std::cerr << "Error: unknown minizinc standard library directory.\n"
    << "Specify --stdlib-dir on the command line or set the\n"
    << "MZN_STDLIB_DIR environment variable.\n";
    std::exit(EXIT_FAILURE);
  }

  includePaths.push_back(std_lib_dir+"/std/");

  {
    if (Model* outputm = parse(filename, std::vector<std::string>(), includePaths, false,
                               std::cerr)) {
      try {
        std::vector<TypeError> typeErrors;
        MiniZinc::typecheck(outputm,typeErrors);
        MiniZinc::registerBuiltins(outputm);

        typedef pair<VarDecl*,Expression*> DE;
        ASTStringMap<DE>::t declmap;
        Expression* outputExpr = NULL;
        for (unsigned int i=0; i<outputm->size(); i++) {
          if (VarDeclI* vdi = (*outputm)[i]->dyn_cast<VarDeclI>()) {
            declmap.insert(pair<ASTString,DE>(vdi->e()->id()->v(),DE(vdi->e(),vdi->e()->e())));
          } else if (OutputI* oi = (*outputm)[i]->dyn_cast<OutputI>()) {
            outputExpr = oi->e();
          }
        }

        //ostream& fout(flag_output_file.empty() ? std::cout : new fstream(flag_output_file));
        fstream file_ostream;
        if (!flag_output_file.empty())
            file_ostream.open(flag_output_file, std::fstream::out);
        ostream& fout = flag_output_file.empty() ? std::cout : file_ostream;

        string solution;
        string comments;
        for (;;) {
          if (solstream.good()) {
            string line;
            getline(solstream, line);
            if (flag_ignore_lines > 0) {
              flag_ignore_lines--;
              continue;
            }
            if (line=="----------") {
              if (outputExpr != NULL) {
                for (unsigned int i=0; i<outputm->size(); i++) {
                  if (VarDeclI* vdi = (*outputm)[i]->dyn_cast<VarDeclI>()) {
                    ASTStringMap<DE>::t::iterator it = declmap.find(vdi->e()->id()->v());
                    vdi->e()->e(it->second.second);
                    vdi->e()->evaluated(false);
                  }
                }
                Model* sm = parseFromString(solution, "solution.szn", includePaths, true, cerr);
                for (unsigned int i=0; i<sm->size(); i++) {
                  if (AssignI* ai = (*sm)[i]->dyn_cast<AssignI>()) {
                    ASTStringMap<DE>::t::iterator it = declmap.find(ai->id());
                    if (it==declmap.end()) {
                      cerr << "Error: unexpected identifier " << ai->id() << " in output\n";
                      exit(EXIT_FAILURE);
                    }
                    ai->e()->type(it->second.first->type());
                    ai->decl(it->second.first);
                    typecheck(outputm, ai);
                    if (Call* c = ai->e()->dyn_cast<Call>()) {
                      // This is an arrayXd call, make sure we get the right builtin
                      assert(c->args()[c->args().size()-1]->isa<ArrayLit>());
                      for (unsigned int i=0; i<c->args().size(); i++)
                        c->args()[i]->type(Type::parsetint());
                      c->args()[c->args().size()-1]->type(it->second.first->type());
                      c->decl(outputm->matchFn(c));
                    }
                    it->second.first->e(ai->e());
                  }
                }

                GCLock lock;
                ArrayLit* al = eval_array_lit(outputExpr);
                std::string os;
                for (unsigned int i=0; i<al->v().size(); i++) {
                  std::string s = eval_string(al->v()[i]);
                  if (!s.empty()) {
                    os = s;
                    fout << os;
                    if (flag_output_flush)
                      fout.flush();
                  }
                }
                if (!os.empty() && os[os.size()-1] != '\n')
                  fout << std::endl;
                  if (flag_output_flush)
                    fout.flush();
              }
              fout << comments;
              fout << solution_separator << std::endl;
              if (flag_output_flush)
                fout.flush();
              solution = "";
              comments = "";
            } else if (line=="==========") {
              fout << search_complete_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNSATISFIABLE=====") {
              fout << unsatisfiable_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNBOUNDED=====") {
              fout << unbounded_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNKNOWN=====") {
              fout << unknown_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else {
              solution += line+"\n";
              size_t comment_pos = line.find('%');
              if (comment_pos != string::npos) {
                comments += line.substr(comment_pos);
                comments += "\n";
              }
            }
          } else {
            break;
          }
        }
        fout << comments;
        if (flag_output_flush)
          fout.flush();
      } catch (LocationException& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        std::cerr << e.loc() << std::endl;
        exit(EXIT_FAILURE);
      } catch (Exception& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        exit(EXIT_FAILURE);
      }
      delete outputm;
    }
  }

  return 0;

error:
  std::cerr << "Usage: "<< argv[0]
            << " [<options>] <model>.ozn" << std::endl
            << std::endl
            << "Options:" << std::endl
            << "  --help, -h\n    Print this help message." << std::endl
            << "  --version\n    Print version information." << std::endl
            << "  -o <file>, --output-to-file <file>\n    Filename for generated output." << std::endl
            << "  --stdlib-dir <dir>\n    Path to MiniZinc standard library directory." << std::endl
            << "  --no-output-comments\n    Do not print comments in the FlatZinc solution stream." << std::endl
            << "  --no-flush-output\n    Don't flush output stream after every line." << std::endl
            << "  -i <n>, --ignore-lines <n>, --ignore-leading-lines <n>\n    Ignore the first <n> lines in the FlatZinc solution stream." << std::endl
            << "  --soln-sep <s>, --soln-separator <s>, --solution-separator <s>\n    Specify the string used to separate solutions.\n    The default is to use the FlatZinc solution separator,\n    \"----------\"." << std::endl
            << "  --unsat-msg <msg>, --unsatisfiable-msg <msg>\n    Specify the message to print if the model instance is\n    unsatisfiable.\n    The default is to print \"=====UNSATISFIABLE=====\"." << std::endl
            << "  --unbounded-msg <msg>\n    Specify the message to print if the objective of the\n    model instance is unbounded.\n    The default is to print \"=====UNBOUNDED=====\"." << std::endl
            << "  --unknown-msg <msg>\n    Specify the message to print if search terminates without\n    the entire search space having been explored and no\n    solution has been found.\n    The default is to print \"=====UNKNOWN=====\"." << std::endl
            << "  --search-complete-msg <msg>\n    Specify the message to print if search terminates having\n    explored the entire search space.\n    The default is to print \"==========\"." << std::endl
  ;

  exit(EXIT_FAILURE);
}
<commit_msg>Make solns2out compile with older libstdc++<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#include <iostream>
#include <fstream>

#include <minizinc/model.hh>
#include <minizinc/parser.hh>
#include <minizinc/prettyprinter.hh>
#include <minizinc/typecheck.hh>
#include <minizinc/astexception.hh>
#include <minizinc/hash.hh>
#include <minizinc/eval_par.hh>
#include <minizinc/builtins.hh>
#include <minizinc/file_utils.hh>

using namespace MiniZinc;
using namespace std;

int main(int argc, char** argv) {
  string filename;

  string flag_output_file;

  bool flag_output_comments = true;
  bool flag_output_flush = true;
  string solfile;
  int flag_ignore_lines = 0;
  istream& solstream = cin;

  string solution_separator = "----------";
  string unsatisfiable_msg  = "=====UNSATISFIABLE=====";
  string unbounded_msg      = "=====UNBOUNDED=====";
  string unknown_msg        = "=====UNKNOWN=====";
  string search_complete_msg= "==========";

  vector<string> includePaths;
  string std_lib_dir;
  if (char* MZNSTDLIBDIR = getenv("MZN_STDLIB_DIR")) {
    std_lib_dir = string(MZNSTDLIBDIR);
  }

  if (argc < 2)
    goto error;

  GC::init();

  for (int i=1; i<argc; i++) {
    if (string(argv[i])==string("--version")) {
      std::cout << "NICTA MiniZinc solution printing tool, version "
      << MZN_VERSION_MAJOR << "." << MZN_VERSION_MINOR << "." << MZN_VERSION_PATCH << std::endl;
      std::cout << "Copyright (C) 2014 Monash University and NICTA" << std::endl;
      std::exit(EXIT_SUCCESS);
    }
    if (string(argv[i])==string("-h") || string(argv[i])==string("--help")) {
        goto error;
    } else if (string(argv[i])=="-o" || string(argv[i])=="--output-to-file") {
      i++;
      if (i==argc)
        goto error;
      flag_output_file = argv[i];
    } else if (string(argv[i])=="--stdlib-dir") {
      i++;
      if (i==argc)
        goto error;
      std_lib_dir = argv[i];
    } else if (string(argv[i])=="--no-flush-output") {
      flag_output_flush = false;
    } else if (string(argv[i])=="--no-output-comments") {
      flag_output_comments = false;
    } else if (string(argv[i])=="-i" ||
               string(argv[i])=="--ignore-lines" ||
               string(argv[i])=="--ignore-leading-lines") {
      ++i;
      if (i==argc)
        goto error;
      flag_ignore_lines = atoi(argv[i]);
    } else if (string(argv[i])=="--soln-sep" ||
               string(argv[i])=="--soln-separator" ||
               string(argv[i])=="--solution-separator") {
      ++i;
      if (i==argc)
        goto error;
      solution_separator = string(argv[i]);
    } else if (string(argv[i])=="--unsat-msg" ||
               string(argv[i])=="--unsatisfiable-msg") {
      ++i;
      if (i==argc)
        goto error;
      unsatisfiable_msg = string(argv[i]);
    } else if (string(argv[i])=="--unbounded-msg") {
      ++i;
      if (i==argc)
        goto error;
      unbounded_msg = string(argv[i]);
    } else if (string(argv[i])=="--unknown-msg") {
      ++i;
      if (i==argc)
        goto error;
      unknown_msg = string(argv[i]);
    } else if (string(argv[i])=="--search-complete-msg") {
      ++i;
      if (i==argc)
        goto error;
      search_complete_msg = string(argv[i]);
    } else {
      filename = argv[i++];
      if (filename.length()<=4 ||
          filename.substr(filename.length()-4,string::npos) != ".ozn") {
        std::cerr << "Invalid .ozn file " << filename << "." << std::endl;
        goto error;
      }
    }
  }

  if (std_lib_dir=="") {
    std::string mypath = FileUtils::progpath();
    if (!mypath.empty()) {
      if (FileUtils::file_exists(mypath+"/share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/share/minizinc";
      } else if (FileUtils::file_exists(mypath+"/../share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/../share/minizinc";
      } else if (FileUtils::file_exists(mypath+"/../../share/minizinc/std/builtins.mzn")) {
        std_lib_dir = mypath+"/../../share/minizinc";
      }
    }
  }

  if (std_lib_dir=="") {
    std::cerr << "Error: unknown minizinc standard library directory.\n"
    << "Specify --stdlib-dir on the command line or set the\n"
    << "MZN_STDLIB_DIR environment variable.\n";
    std::exit(EXIT_FAILURE);
  }

  includePaths.push_back(std_lib_dir+"/std/");

  {
    if (Model* outputm = parse(filename, std::vector<std::string>(), includePaths, false,
                               std::cerr)) {
      try {
        std::vector<TypeError> typeErrors;
        MiniZinc::typecheck(outputm,typeErrors);
        MiniZinc::registerBuiltins(outputm);

        typedef pair<VarDecl*,Expression*> DE;
        ASTStringMap<DE>::t declmap;
        Expression* outputExpr = NULL;
        for (unsigned int i=0; i<outputm->size(); i++) {
          if (VarDeclI* vdi = (*outputm)[i]->dyn_cast<VarDeclI>()) {
            declmap.insert(pair<ASTString,DE>(vdi->e()->id()->v(),DE(vdi->e(),vdi->e()->e())));
          } else if (OutputI* oi = (*outputm)[i]->dyn_cast<OutputI>()) {
            outputExpr = oi->e();
          }
        }

        //ostream& fout(flag_output_file.empty() ? std::cout : new fstream(flag_output_file));
        fstream file_ostream;
        if (!flag_output_file.empty())
            file_ostream.open(flag_output_file.c_str(), std::fstream::out);
        ostream& fout = flag_output_file.empty() ? std::cout : file_ostream;

        string solution;
        string comments;
        for (;;) {
          if (solstream.good()) {
            string line;
            getline(solstream, line);
            if (flag_ignore_lines > 0) {
              flag_ignore_lines--;
              continue;
            }
            if (line=="----------") {
              if (outputExpr != NULL) {
                for (unsigned int i=0; i<outputm->size(); i++) {
                  if (VarDeclI* vdi = (*outputm)[i]->dyn_cast<VarDeclI>()) {
                    ASTStringMap<DE>::t::iterator it = declmap.find(vdi->e()->id()->v());
                    vdi->e()->e(it->second.second);
                    vdi->e()->evaluated(false);
                  }
                }
                Model* sm = parseFromString(solution, "solution.szn", includePaths, true, cerr);
                for (unsigned int i=0; i<sm->size(); i++) {
                  if (AssignI* ai = (*sm)[i]->dyn_cast<AssignI>()) {
                    ASTStringMap<DE>::t::iterator it = declmap.find(ai->id());
                    if (it==declmap.end()) {
                      cerr << "Error: unexpected identifier " << ai->id() << " in output\n";
                      exit(EXIT_FAILURE);
                    }
                    ai->e()->type(it->second.first->type());
                    ai->decl(it->second.first);
                    typecheck(outputm, ai);
                    if (Call* c = ai->e()->dyn_cast<Call>()) {
                      // This is an arrayXd call, make sure we get the right builtin
                      assert(c->args()[c->args().size()-1]->isa<ArrayLit>());
                      for (unsigned int i=0; i<c->args().size(); i++)
                        c->args()[i]->type(Type::parsetint());
                      c->args()[c->args().size()-1]->type(it->second.first->type());
                      c->decl(outputm->matchFn(c));
                    }
                    it->second.first->e(ai->e());
                  }
                }

                GCLock lock;
                ArrayLit* al = eval_array_lit(outputExpr);
                std::string os;
                for (unsigned int i=0; i<al->v().size(); i++) {
                  std::string s = eval_string(al->v()[i]);
                  if (!s.empty()) {
                    os = s;
                    fout << os;
                    if (flag_output_flush)
                      fout.flush();
                  }
                }
                if (!os.empty() && os[os.size()-1] != '\n')
                  fout << std::endl;
                  if (flag_output_flush)
                    fout.flush();
              }
              fout << comments;
              fout << solution_separator << std::endl;
              if (flag_output_flush)
                fout.flush();
              solution = "";
              comments = "";
            } else if (line=="==========") {
              fout << search_complete_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNSATISFIABLE=====") {
              fout << unsatisfiable_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNBOUNDED=====") {
              fout << unbounded_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else if(line=="=====UNKNOWN=====") {
              fout << unknown_msg << std::endl;
              if (flag_output_flush)
                fout.flush();
            } else {
              solution += line+"\n";
              size_t comment_pos = line.find('%');
              if (comment_pos != string::npos) {
                comments += line.substr(comment_pos);
                comments += "\n";
              }
            }
          } else {
            break;
          }
        }
        fout << comments;
        if (flag_output_flush)
          fout.flush();
      } catch (LocationException& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        std::cerr << e.loc() << std::endl;
        exit(EXIT_FAILURE);
      } catch (Exception& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        exit(EXIT_FAILURE);
      }
      delete outputm;
    }
  }

  return 0;

error:
  std::cerr << "Usage: "<< argv[0]
            << " [<options>] <model>.ozn" << std::endl
            << std::endl
            << "Options:" << std::endl
            << "  --help, -h\n    Print this help message." << std::endl
            << "  --version\n    Print version information." << std::endl
            << "  -o <file>, --output-to-file <file>\n    Filename for generated output." << std::endl
            << "  --stdlib-dir <dir>\n    Path to MiniZinc standard library directory." << std::endl
            << "  --no-output-comments\n    Do not print comments in the FlatZinc solution stream." << std::endl
            << "  --no-flush-output\n    Don't flush output stream after every line." << std::endl
            << "  -i <n>, --ignore-lines <n>, --ignore-leading-lines <n>\n    Ignore the first <n> lines in the FlatZinc solution stream." << std::endl
            << "  --soln-sep <s>, --soln-separator <s>, --solution-separator <s>\n    Specify the string used to separate solutions.\n    The default is to use the FlatZinc solution separator,\n    \"----------\"." << std::endl
            << "  --unsat-msg <msg>, --unsatisfiable-msg <msg>\n    Specify the message to print if the model instance is\n    unsatisfiable.\n    The default is to print \"=====UNSATISFIABLE=====\"." << std::endl
            << "  --unbounded-msg <msg>\n    Specify the message to print if the objective of the\n    model instance is unbounded.\n    The default is to print \"=====UNBOUNDED=====\"." << std::endl
            << "  --unknown-msg <msg>\n    Specify the message to print if search terminates without\n    the entire search space having been explored and no\n    solution has been found.\n    The default is to print \"=====UNKNOWN=====\"." << std::endl
            << "  --search-complete-msg <msg>\n    Specify the message to print if search terminates having\n    explored the entire search space.\n    The default is to print \"==========\"." << std::endl
  ;

  exit(EXIT_FAILURE);
}
<|endoftext|>


<commit_before>#include <iostream>

inline double speed(double distance, double time)
{
    return distance * time;
}

int main (int argc, char* argv[])
{
    double distance;
    double time;
    double average_speed;

    std::cout << "Enter the distance in meters: ";
    std::cin >> distance;

    std::cout << "Enter the time of movement in seconds: ";
    std::cin >> time;

    average_speed = speed(distance,time);

    std::cout << "The average speed of the object is: " << average_speed << "m/s" <<std::endl;

}
<commit_msg>created function read double. closes #61<commit_after>#include <iostream>

inline double speed(double distance, double time)
{
    return (distance/time);
}

double read_double(std::string prompt )
{
    double distance;

    std::cout << prompt << " : ";
    std::cin >> distance;

    return distance;
}

double read_double_time(std::string prompt)
{
    double time;
    std::cout << prompt << ":";
    std::cin >> time;

    return time;
}

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

    double average_speed;
    double time;
    double distance;

    distance = read_double("Enter distance in meters");
    time = read_double("Enter time in seconds");
    average_speed = speed(distance,time);

    std::cout << "The average speed of the object is: " << average_speed << "m/s" <<std::endl;

}
<|endoftext|>


<commit_before>#include "Actor.hpp"

std::map<std::string, std::shared_ptr<RenderModel>> Actor::s_modelDictionary;

Actor::Actor(const std::string& actorName) : m_desc(actorName) {
	assert(actorName.compare("") != 0);
	try {
		// Construct model if it has not been constructed yet
		if(s_modelDictionary.count(m_desc.renderModel) == 0) {
			s_modelDictionary.emplace(
			  m_desc.renderModel, std::make_shared<RenderModel>(m_desc.renderModel));
		}
		m_renderModel = s_modelDictionary.find(m_desc.renderModel)->second;
	} catch(const std::exception& exception) {
		g_logger->write(Logger::LOG_ERROR, exception.what());
		throw std::runtime_error("Failed to load RenderModel");
	}

	// Consult input schema file and create bindings
	if(m_desc.inputModel.compare("") != 0) {
		try {
			const std::string inputSchemaName = m_desc.inputModel + ".pro";
			std::string       keyPred         = m_desc.inputModel + "_bindKeys";
			PlCall("pd_consult", PlTerm(inputSchemaName.c_str()));
			PlCall("b_setval", PlTermv("pd_input", &m_inputModel));
			PlCall(keyPred.c_str(), NULL);
			PlCall("pd_bindMouse", PlTerm((&m_desc.inputModel)->c_str()));
			PlCall("b_setval", PlTermv("pd_input", static_cast<long>(NULL)));
		} catch(const PlException& exception) {
			g_logger->write(Logger::LOG_ERROR, static_cast<char*>(exception));
		}
	}
}

Actor::~Actor() {
	// Remove model from dictionary if no Actor is using it
	if(m_desc.renderModel.compare("") != 0 &&
	   s_modelDictionary.find(m_desc.renderModel)->second.unique()) {
		s_modelDictionary.erase(m_desc.renderModel);
	}
}

/**
 * Called once per cycle. By default does nothing, but can be overriden to
 * progress animations, respond to collisions, etc.
 *
 * TODO: Allow user definition via scripting
 *
 * @param [in] duration   Time in milliseconds since the last update
 */
// void Actor::update(std::chrono::milliseconds duration) {}

/* Draws the actor's render model to the active frame buffer
 *
 * @param [in] viewMatrix        The matrix used to transform the model respective to a camera's viewpoint
 * @param [in] projectionMatrix  The matrix used to project the model from 3D/4D world space to 2D screen space
 */
void Actor::draw(Shader& shader) {
	if(m_renderModel == nullptr) return;

	glm::mat4 modelMatrix = m_spatialModel.matrix();

	shader.setModelMatrix(modelMatrix);

	shader.updateNormalMatrix();

	m_renderModel->draw(shader);
}

void Actor::processInput(GLFWwindow& window) {
	PlCall("b_setval", PlTermv("pd_spatial", &m_spatialModel));
	PlCall("b_setval", PlTermv("pd_input", &m_inputModel));
	m_inputModel.update(window);
	PlCall("b_setval", PlTermv("pd_spatial", static_cast<long>(NULL)));
	PlCall("b_setval", PlTermv("pd_input", static_cast<long>(NULL)));
}

ActorDescription::ActorDescription(const std::string& actorName) {
	std::string        contents = readFile(ACTOR_DIR + actorName + ".actr");
	std::istringstream ss(contents);
	std::getline(ss, renderModel);
	std::getline(ss, inputModel);
}
<commit_msg>Pass of making render model if it's not defined in the actor description file<commit_after>#include "Actor.hpp"

std::map<std::string, std::shared_ptr<RenderModel>> Actor::s_modelDictionary;

Actor::Actor(const std::string& actorName) : m_desc(actorName) {
	if(m_desc.renderModel.compare("") != 0) {
		try {
			// Construct model if it has not been constructed yet
			if(s_modelDictionary.count(m_desc.renderModel) == 0) {
				s_modelDictionary.emplace(
				  m_desc.renderModel,
				  std::make_shared<RenderModel>(m_desc.renderModel));
			}
			m_renderModel = s_modelDictionary.find(m_desc.renderModel)->second;
		} catch(const std::exception& exception) {
			g_logger->write(Logger::LOG_ERROR, exception.what());
			throw std::runtime_error("Failed to load RenderModel");
		}
	}

	// Consult input schema file and create bindings
	if(m_desc.inputModel.compare("") != 0) {
		try {
			const std::string inputSchemaName = m_desc.inputModel + ".pro";
			std::string       keyPred         = m_desc.inputModel + "_bindKeys";
			PlCall("pd_consult", PlTerm(inputSchemaName.c_str()));
			PlCall("b_setval", PlTermv("pd_input", &m_inputModel));
			PlCall(keyPred.c_str(), NULL);
			PlCall("pd_bindMouse", PlTerm((&m_desc.inputModel)->c_str()));
			PlCall("b_setval", PlTermv("pd_input", static_cast<long>(NULL)));
		} catch(const PlException& exception) {
			g_logger->write(Logger::LOG_ERROR, static_cast<char*>(exception));
		}
	}
}

Actor::~Actor() {
	// Remove model from dictionary if no Actor is using it
	if(m_desc.renderModel.compare("") != 0 &&
	   s_modelDictionary.find(m_desc.renderModel)->second.unique()) {
		s_modelDictionary.erase(m_desc.renderModel);
	}
}

/**
 * Called once per cycle. By default does nothing, but can be overriden to
 * progress animations, respond to collisions, etc.
 *
 * TODO: Allow user definition via scripting
 *
 * @param [in] duration   Time in milliseconds since the last update
 */
// void Actor::update(std::chrono::milliseconds duration) {}

/* Draws the actor's render model to the active frame buffer
 *
 * @param [in] viewMatrix        The matrix used to transform the model respective to a camera's viewpoint
 * @param [in] projectionMatrix  The matrix used to project the model from 3D/4D world space to 2D screen space
 */
void Actor::draw(Shader& shader) {
	if(m_renderModel == nullptr) return;

	glm::mat4 modelMatrix = m_spatialModel.matrix();

	shader.setModelMatrix(modelMatrix);

	shader.updateNormalMatrix();

	m_renderModel->draw(shader);
}

void Actor::processInput(GLFWwindow& window) {
	PlCall("b_setval", PlTermv("pd_spatial", &m_spatialModel));
	PlCall("b_setval", PlTermv("pd_input", &m_inputModel));
	m_inputModel.update(window);
	PlCall("b_setval", PlTermv("pd_spatial", static_cast<long>(NULL)));
	PlCall("b_setval", PlTermv("pd_input", static_cast<long>(NULL)));
}

ActorDescription::ActorDescription(const std::string& actorName) {
	assert(actorName.compare("") != 0);
	std::string        contents = readFile(ACTOR_DIR + actorName + ".actr");
	std::istringstream ss(contents);
	std::getline(ss, renderModel);
	std::getline(ss, inputModel);
}
<|endoftext|>


<commit_before>#include "Enemy.h"

#include "EStateIdle.h"
#include "EStatePatrolling.h"
#include "EStateAerial.h"
#include "EStateCurious.h"
#include "EStateAlert.h"

double Enemy::px = 0.0;
double Enemy::py = 0.0;
double Enemy::alertRange = 300.0;
double Enemy::curiousRange = 600.0;

Enemy::Enemy(const double x_, const double y_, Sprite* const sprite_, const bool patrol_,
    const double patrolLength_) :

	DynamicEntity(x_, y_, sprite_),
    patrolX(100.0),
    left(true),
    originalX(x_),
    patrol(patrol_),
    patrolLength(patrolLength_),
	currentState(nullptr),
	statesMap()
{
	initializeStates();

    this->speed = 0.7;

    if(this->patrol){
        this->currentState = this->statesMap.at(PATROLLING);
    }
    else{
        this->currentState = this->statesMap.at(IDLE);
    }
    this->currentState->enter();
}

Enemy::~Enemy(){
	if(this->currentState != nullptr){
        this->currentState->exit();
    }

    destroyStates();
}

void Enemy::update(const double dt_){
    this->currentState->update();
    updatePosition(dt_);
}

void Enemy::render(const double cameraX_, const double cameraY_){
    if(this->sprite != nullptr){
        const double dx = this->x - cameraX_;
        const double dy = this->y - cameraY_;
        this->sprite->render(dx, dy);
    }
}

void Enemy::initializeStates(){
    // Initialize all the states in Enemy here.
    this->statesMap.emplace(IDLE, new EStateIdle(this));
    this->statesMap.emplace(CURIOUS, new EStateCurious(this));
    this->statesMap.emplace(PATROLLING, new EStatePatrolling(this));
    this->statesMap.emplace(ALERT, new EStateAlert(this));
    this->statesMap.emplace(AERIAL, new EStateAerial(this));
}

void Enemy::destroyStates(){
	// Delete all the states in Enemy here.
    std::map<EStates, StateEnemy*>::const_iterator it;
    for(it = this->statesMap.begin(); it != this->statesMap.end(); it++){
        delete it->second;
    }
}

void Enemy::changeState(const EStates state_){
    this->currentState->exit();
    this->currentState = this->statesMap.at(state_);
    this->currentState->enter();
}

void Enemy::handleCollision(std::array<bool, CollisionSide::SOLID_TOTAL> detections_){}
<commit_msg>Began developing collision for enemy<commit_after>#include "Enemy.h"

#include "EStateIdle.h"
#include "EStatePatrolling.h"
#include "EStateAerial.h"
#include "EStateCurious.h"
#include "EStateAlert.h"

double Enemy::px = 0.0;
double Enemy::py = 0.0;
double Enemy::alertRange = 300.0;
double Enemy::curiousRange = 600.0;

Enemy::Enemy(const double x_, const double y_, Sprite* const sprite_, const bool patrol_,
    const double patrolLength_) :

	DynamicEntity(x_, y_, sprite_),
    patrolX(100.0),
    left(true),
    originalX(x_),
    patrol(patrol_),
    patrolLength(patrolLength_),
	currentState(nullptr),
	statesMap()
{
	initializeStates();

    this->speed = 0.7;

    if(this->patrol){
        this->currentState = this->statesMap.at(PATROLLING);
    }
    else{
        this->currentState = this->statesMap.at(IDLE);
    }
    this->currentState->enter();
}

Enemy::~Enemy(){
	if(this->currentState != nullptr){
        this->currentState->exit();
    }

    destroyStates();
}

void Enemy::update(const double dt_){
    this->currentState->update();
    updatePosition(dt_);
    std::array<bool, CollisionSide::SOLID_TOTAL> detections = detectCollision();
    handleCollision(detections);
}

void Enemy::render(const double cameraX_, const double cameraY_){
    if(this->sprite != nullptr){
        const double dx = this->x - cameraX_;
        const double dy = this->y - cameraY_;
        this->sprite->render(dx, dy);
    }
}

void Enemy::initializeStates(){
    // Initialize all the states in Enemy here.
    this->statesMap.emplace(IDLE, new EStateIdle(this));
    this->statesMap.emplace(CURIOUS, new EStateCurious(this));
    this->statesMap.emplace(PATROLLING, new EStatePatrolling(this));
    this->statesMap.emplace(ALERT, new EStateAlert(this));
    this->statesMap.emplace(AERIAL, new EStateAerial(this));
}

void Enemy::destroyStates(){
	// Delete all the states in Enemy here.
    std::map<EStates, StateEnemy*>::const_iterator it;
    for(it = this->statesMap.begin(); it != this->statesMap.end(); it++){
        delete it->second;
    }
}

void Enemy::changeState(const EStates state_){
    this->currentState->exit();
    this->currentState = this->statesMap.at(state_);
    this->currentState->enter();
}

void Enemy::handleCollision(std::array<bool, CollisionSide::SOLID_TOTAL> detections_){
    if(detections_.at(CollisionSide::SOLID_TOP)){
        if((int)this->y%64 > 0){
            this->y += 64 -(int)this->y%64 + 1;
            this->vy = 0.0;
        }
    }
    if(detections_.at(CollisionSide::SOLID_BOTTOM)){
        if(this->currentState == this->statesMap.at(EStates::AERIAL)){
            this->y -= (int)(this->y + this->height)%64 - 1;
            this->vy = 0.0;
            changeState(EStates::PATROLLING);
        }
    }
    else{
        if(this->currentState != this->statesMap.at(EStates::AERIAL)){
            changeState(EStates::AERIAL);
        }
    }
    if(detections_.at(CollisionSide::SOLID_LEFT)){
        this->x -= (int)(this->x + this->width)%64 + 1;
        this->vx = 0.0;
    }
    if(detections_.at(CollisionSide::SOLID_RIGHT)){

//      std::cout << (int)this->x%64 << "\n";
        if((int)this->x%64 > 0){
            this->x += (64 - (int)this->x%64) + 1;
            this->vx = 0.0;
        }
    }
}
<|endoftext|>


<commit_before>#ifndef BEDGE
#define BEDGE

#include <utility>
#include "BVect.hpp"
#include "DominanceStatus.hpp"

class BEdge {
  private:
    BVect _a;
    BVect _b;
    bool _aClosed;
    bool _bClosed;
    bool _point;
  public:
    BEdge() : _aClosed(false), _bClosed(false), _point(false) {}
    BEdge (BVect a, BVect b, bool aC = true, bool bC = true) : _a(a), _b(b), _point(a==b), _aClosed(_point || aC), _bClosed(_point || bC) {}
    BEdge (BVect a) : _a(a), _b(a), _aClosed(true), _bClosed(true), _point(true) {}
    BVect leftPoint() const {return _a;}
    BVect rightPoint() const {return _b;}
    bool isAPoint() const {return _point;}
    bool isEmpty() const {return (!_aClosed && !_bClosed);}
    bool isLeftOpen() const {return !_aClosed;}
    bool isRightOpen() const {return !_bClosed;}
    bool isLeftClose() const {return _aClosed;}
    bool isRightClose() const {return _bClosed;}
    bool isInA1AreaOf(const BEdge& be) const {
      return (this->rightPoint().isInA1AreaOf(be.leftPoint()));
    }
    bool isInA2AreaOf(const BEdge& be) const {
      return be.isInA1AreaOf(*this);
    }
    std::pair<double, double> computeLambdasWithPoint(const BVect& bv) const {
      std::pair<double, double> lambdas;
      if (this->leftPoint().z1() <= bv.z1() && bv.z1() <= this->rightPoint().z1())
        lambdas.first = ((this->rightPoint().z1() - bv.z1()) / ( this->rightPoint().z1() - this->leftPoint().z1()));
      else lambdas.first = 1;
      if (this->rightPoint().z2() <= bv.z2() && bv.z2() <= this->leftPoint().z2())
        lambdas.second = ((bv.z2() - this->rightPoint().z2()) / ( this->leftPoint().z2() - this->rightPoint().z2()));
      else lambdas.second = 0;
      return lambdas;
    }
    std::pair<BVect, BVect> computeProjWithPoint(const BVect& bv) const {
      std::pair<BVect, BVect> projections;
      if (this->leftPoint().z1() <= bv.z1() && bv.z1() <= this->rightPoint().z1()) {
        double lambda = ((this->rightPoint().z1() - bv.z1()) / ( this->rightPoint().z1() - this->leftPoint().z1()));
        BVect p(this->leftPoint(), this->rightPoint(), lambda);
        projections.first = BVect(bv.z1(), p.z2(), p.x());
      } else {
        projections.first = this->leftPoint();
      }
      if (this->rightPoint().z2() <= bv.z2() && bv.z2() <= this->leftPoint().z2()) {
        double lambda = ((bv.z2() - this->rightPoint().z2()) / ( this->leftPoint().z2() - this->rightPoint().z2()));
        BVect p(this->leftPoint(), this->rightPoint(), lambda);
        projections.second = BVect(p.z1(), bv.z2(), p.x());
      } else {
        projections.second = this->rightPoint();
      }
      return projections;
    }
    DominanceStatus compareWithPoint(const BEdge& be, BEdge& tleft, BEdge& tright) const {
      if (this->isInA1AreaOf(be) || this->isInA2AreaOf(be))
        return DominanceStatus::NO_DOM;
      BVect bv = be.leftPoint();
      if (this->leftPoint().weaklyDominates(bv) && this->rightPoint().weaklyDominates(bv))
        return DominanceStatus::A_DOM_B;
      if (bv.weaklyDominates(this->leftPoint()) && bv.weaklyDominates(this->rightPoint()))
        return DominanceStatus::B_DOM_A;
      std::pair<BVect, BVect> projs = computeProjWithPoint(bv);
      BVect proj1 = projs.first;
      BVect proj2 = projs.second;
      if (proj1.weaklyDominates(bv))
        return DominanceStatus::A_DOM_B;
      else {
        if (proj1 != this->leftPoint())
          tleft = BEdge(this->leftPoint(), proj1);
        if (proj2 != this->rightPoint())
          tright = BEdge(proj2, this->rightPoint());
        return DominanceStatus::B_PART_DOM_A;
      }
    }
    bool intersect(const BEdge& be, BVect& i1, BVect& i2) const {
      double Az1 = this->rightPoint().z1();
      double Az2 = this->rightPoint().z2();
      double Cz1 = be.rightPoint().z1();
      double Cz2 = be.rightPoint().z2();
      double Iz1 = this->leftPoint().z1() - Az1;
      double Iz2 = this->leftPoint().z2() - Az2;
      double Jz1 = be.leftPoint().z1() - Cz1;
      double Jz2 = be.leftPoint().z2() - Cz2;
      double lambda = (Iz2*Cz1 - Iz2*Az1 - Iz1*Cz2 + Iz1*Az2) / (Iz1*Jz2 - Iz2*Jz1);
      double mu  = (Jz2*Cz1 - Jz2*Az1 - Jz1*Cz2 + Jz1*Az2) / (Iz1*Jz2 - Iz2*Jz1);
      if (0 < lambda && lambda < 1 && 0 < mu && mu < 1) {
        i1 = BVect(this->leftPoint(), this->rightPoint(), mu);
        i2 = BVect(be.leftPoint(), be.rightPoint(), lambda);
        return true;
      } else {
        return false;
      }
    }
    DominanceStatus compareLeftEdges(const BEdge& t, const BEdge& b) {
      if (t.leftPoint().weaklyDominates(b.leftPoint()))
        return DominanceStatus::A_DOM_B;
      else if (t.leftPoint().isInA1AreaOf(b.leftPoint())) {
        std::pair<BVect, BVect> projs = t.computeProjWithPoint(b.leftPoint());
        BVect proj1 = projs.first;
        BVect proj2 = projs.second;
        if (b.leftPoint().dominates(proj1)) {
          *this = BEdge(t.leftPoint(), proj1);
          return DominanceStatus::B_PART_DOM_A;
        } else {
          return DominanceStatus::A_DOM_B;
        }
      } else {
        return invert(this->compareLeftEdges(b, t));
      }
    }
    DominanceStatus compareRightEdges(const BEdge& t, const BEdge& b) {
      if (t.rightPoint().weaklyDominates(b.rightPoint()))
        return DominanceStatus::A_DOM_B;
      else if (t.rightPoint().isInA2AreaOf(b.rightPoint())) {
        std::pair<BVect, BVect> projs = t.computeProjWithPoint(b.rightPoint());
        BVect proj1 = projs.first;
        BVect proj2 = projs.second;
        if (b.rightPoint().dominates(proj2)) {
          *this = BEdge(proj2, t.rightPoint());
          return DominanceStatus::B_PART_DOM_A;
        } else {
          return DominanceStatus::A_DOM_B;
        }
      } else {
        return invert(this->compareRightEdges(b, t));
      }
    }
    DominanceStatus compareWith(const BEdge& be, BEdge& tleft, BEdge& tright, BEdge& beleft, BEdge& beright) const {
      if (this->isAPoint() && be.isAPoint()) {
        if (this->leftPoint().dominates(be.leftPoint()))
          return DominanceStatus::A_DOM_B;
        else if (be.leftPoint().dominates(this->leftPoint()))
          return DominanceStatus::B_DOM_A;
        else return DominanceStatus::NO_DOM;
      } else if (this->isAPoint()) {
        return invert(be.compareWithPoint(*this, tleft, tright));
      } else if (be.isAPoint()) {
        return this->compareWithPoint(be, beleft, beright);
      } else {
        BVect intThis;
        BVect intBe;
        if (this->intersect(be, intThis, intBe)) {
          tleft = BEdge(this->leftPoint(), intThis);
          tright = BEdge(intThis, this->rightPoint());
          beleft = BEdge(be.leftPoint(), intBe);
          beright = BEdge(intBe, be.rightPoint());
          BEdge restLeft;
          BEdge restRight;
          DominanceStatus left = restLeft.compareLeftEdges(tleft, beleft);
          if (left == DominanceStatus::A_PART_DOM_B)
            beleft = restLeft;
          else if (left == DominanceStatus::B_PART_DOM_A)
            tleft = restLeft;
          DominanceStatus right = restRight.compareRightEdges(tright, beright);
          if (right == DominanceStatus::A_PART_DOM_B)
            beright = restRight;
          else if (right == DominanceStatus::B_PART_DOM_A)
            tright = restRight;
          return DominanceStatus::MUTUAL_DOM;
        } else {
          if (this->isInA1AreaOf(be) || this->isInA2AreaOf(be))
            return DominanceStatus::NO_DOM;
          std::pair<BVect, BVect> projb1 = this->computeProjWithPoint(be.leftPoint());
          BVect proj1bleft = projb1.first;
          BVect proj2bleft = projb1.second;
          std::pair<BVect, BVect> projb2 = this->computeProjWithPoint(be.rightPoint());
          BVect proj1bright = projb2.first;
          BVect proj2bright = projb2.second;
          std::pair<BVect, BVect> projt1 = be.computeProjWithPoint(this->leftPoint());
          BVect proj1tleft = projt1.first;
          BVect proj2tleft = projt1.second;
          std::pair<BVect, BVect> projt2 = be.computeProjWithPoint(this->rightPoint());
          BVect proj1tright = projt2.first;
          BVect proj2tright = projt2.second;
          bool adomb = false;
          bool bdoma = false;
          bool apartdomb = false;
          bool bpartdoma = false;
          if (be.leftPoint().weaklyDominates(proj1bleft)) {
            bdoma = true;
            if (proj1bleft != this->leftPoint()) {
              tleft = BEdge(this->leftPoint(), proj1bleft);
              bpartdoma = true;
            }
          }
          if (be.rightPoint().weaklyDominates(proj2bright)) {
            bdoma = true;
            if (proj2bright != this->rightPoint()) {
              tright = BEdge(proj2bright, this->rightPoint());
              bpartdoma = true;
            }
          }
          if (proj2bleft.weaklyDominates(be.leftPoint())) {
            adomb = true;
          }
          if (proj1bright.weaklyDominates(be.rightPoint())) {
            adomb = true;
          }
          if (this->leftPoint().weaklyDominates(proj1tleft)) {
            adomb = true;
            if (proj1tleft != be.leftPoint()) {
              beleft = BEdge(be.leftPoint(), proj1tleft);
              apartdomb = true;
            }
          }
          if (this->rightPoint().weaklyDominates(proj2tright)) {
            adomb = true;
            if (proj2tright != be.rightPoint()) {
              beright = BEdge(proj2tright, be.rightPoint());
              apartdomb = true;
            }
          }
          if (proj2tleft.weaklyDominates(this->leftPoint())) {
            bdoma = true;
          }
          if (proj1tright.weaklyDominates(this->rightPoint())) {
            bdoma = true;
          }
          if (adomb && bdoma)
            return DominanceStatus::MUTUAL_DOM;
          if (apartdomb)
            return DominanceStatus::A_PART_DOM_B;
          if (adomb)
            return DominanceStatus::A_DOM_B;
          if (bpartdoma)
            return DominanceStatus::B_PART_DOM_A;
          if (bdoma)
            return DominanceStatus::B_DOM_A;
          return DominanceStatus::NO_DOM;
        }
      }
    }
};

#endif
<commit_msg>BEdge: Add << ostream operator<commit_after>#ifndef BEDGE
#define BEDGE

#include <utility>
#include <iostream>
#include "BVect.hpp"
#include "DominanceStatus.hpp"

class BEdge {
  private:
    BVect _a;
    BVect _b;
    bool _aClosed;
    bool _bClosed;
    bool _point;
  public:
    BEdge() : _aClosed(false), _bClosed(false), _point(false) {}
    BEdge (BVect a, BVect b, bool aC = true, bool bC = true) : _a(a), _b(b), _point(a==b), _aClosed(_point || aC), _bClosed(_point || bC) {}
    BEdge (BVect a) : _a(a), _b(a), _aClosed(true), _bClosed(true), _point(true) {}
    BVect leftPoint() const {return _a;}
    BVect rightPoint() const {return _b;}
    bool isAPoint() const {return _point;}
    bool isEmpty() const {return (!_aClosed && !_bClosed);}
    bool isLeftOpen() const {return !_aClosed;}
    bool isRightOpen() const {return !_bClosed;}
    bool isLeftClose() const {return _aClosed;}
    bool isRightClose() const {return _bClosed;}
    bool isInA1AreaOf(const BEdge& be) const {
      return (this->rightPoint().isInA1AreaOf(be.leftPoint()));
    }
    bool isInA2AreaOf(const BEdge& be) const {
      return be.isInA1AreaOf(*this);
    }
    std::pair<double, double> computeLambdasWithPoint(const BVect& bv) const {
      std::pair<double, double> lambdas;
      if (this->leftPoint().z1() <= bv.z1() && bv.z1() <= this->rightPoint().z1())
        lambdas.first = ((this->rightPoint().z1() - bv.z1()) / ( this->rightPoint().z1() - this->leftPoint().z1()));
      else lambdas.first = 1;
      if (this->rightPoint().z2() <= bv.z2() && bv.z2() <= this->leftPoint().z2())
        lambdas.second = ((bv.z2() - this->rightPoint().z2()) / ( this->leftPoint().z2() - this->rightPoint().z2()));
      else lambdas.second = 0;
      return lambdas;
    }
    std::pair<BVect, BVect> computeProjWithPoint(const BVect& bv) const {
      std::pair<BVect, BVect> projections;
      if (this->leftPoint().z1() <= bv.z1() && bv.z1() <= this->rightPoint().z1()) {
        double lambda = ((this->rightPoint().z1() - bv.z1()) / ( this->rightPoint().z1() - this->leftPoint().z1()));
        BVect p(this->leftPoint(), this->rightPoint(), lambda);
        projections.first = BVect(bv.z1(), p.z2(), p.x());
      } else {
        projections.first = this->leftPoint();
      }
      if (this->rightPoint().z2() <= bv.z2() && bv.z2() <= this->leftPoint().z2()) {
        double lambda = ((bv.z2() - this->rightPoint().z2()) / ( this->leftPoint().z2() - this->rightPoint().z2()));
        BVect p(this->leftPoint(), this->rightPoint(), lambda);
        projections.second = BVect(p.z1(), bv.z2(), p.x());
      } else {
        projections.second = this->rightPoint();
      }
      return projections;
    }
    DominanceStatus compareWithPoint(const BEdge& be, BEdge& tleft, BEdge& tright) const {
      if (this->isInA1AreaOf(be) || this->isInA2AreaOf(be))
        return DominanceStatus::NO_DOM;
      BVect bv = be.leftPoint();
      if (this->leftPoint().weaklyDominates(bv) && this->rightPoint().weaklyDominates(bv))
        return DominanceStatus::A_DOM_B;
      if (bv.weaklyDominates(this->leftPoint()) && bv.weaklyDominates(this->rightPoint()))
        return DominanceStatus::B_DOM_A;
      std::pair<BVect, BVect> projs = computeProjWithPoint(bv);
      BVect proj1 = projs.first;
      BVect proj2 = projs.second;
      if (proj1.weaklyDominates(bv))
        return DominanceStatus::A_DOM_B;
      else {
        if (proj1 != this->leftPoint())
          tleft = BEdge(this->leftPoint(), proj1);
        if (proj2 != this->rightPoint())
          tright = BEdge(proj2, this->rightPoint());
        return DominanceStatus::B_PART_DOM_A;
      }
    }
    bool intersect(const BEdge& be, BVect& i1, BVect& i2) const {
      double Az1 = this->rightPoint().z1();
      double Az2 = this->rightPoint().z2();
      double Cz1 = be.rightPoint().z1();
      double Cz2 = be.rightPoint().z2();
      double Iz1 = this->leftPoint().z1() - Az1;
      double Iz2 = this->leftPoint().z2() - Az2;
      double Jz1 = be.leftPoint().z1() - Cz1;
      double Jz2 = be.leftPoint().z2() - Cz2;
      double lambda = (Iz2*Cz1 - Iz2*Az1 - Iz1*Cz2 + Iz1*Az2) / (Iz1*Jz2 - Iz2*Jz1);
      double mu  = (Jz2*Cz1 - Jz2*Az1 - Jz1*Cz2 + Jz1*Az2) / (Iz1*Jz2 - Iz2*Jz1);
      if (0 < lambda && lambda < 1 && 0 < mu && mu < 1) {
        i1 = BVect(this->leftPoint(), this->rightPoint(), mu);
        i2 = BVect(be.leftPoint(), be.rightPoint(), lambda);
        return true;
      } else {
        return false;
      }
    }
    DominanceStatus compareLeftEdges(const BEdge& t, const BEdge& b) {
      if (t.leftPoint().weaklyDominates(b.leftPoint()))
        return DominanceStatus::A_DOM_B;
      else if (t.leftPoint().isInA1AreaOf(b.leftPoint())) {
        std::pair<BVect, BVect> projs = t.computeProjWithPoint(b.leftPoint());
        BVect proj1 = projs.first;
        BVect proj2 = projs.second;
        if (b.leftPoint().dominates(proj1)) {
          *this = BEdge(t.leftPoint(), proj1);
          return DominanceStatus::B_PART_DOM_A;
        } else {
          return DominanceStatus::A_DOM_B;
        }
      } else {
        return invert(this->compareLeftEdges(b, t));
      }
    }
    DominanceStatus compareRightEdges(const BEdge& t, const BEdge& b) {
      if (t.rightPoint().weaklyDominates(b.rightPoint()))
        return DominanceStatus::A_DOM_B;
      else if (t.rightPoint().isInA2AreaOf(b.rightPoint())) {
        std::pair<BVect, BVect> projs = t.computeProjWithPoint(b.rightPoint());
        BVect proj1 = projs.first;
        BVect proj2 = projs.second;
        if (b.rightPoint().dominates(proj2)) {
          *this = BEdge(proj2, t.rightPoint());
          return DominanceStatus::B_PART_DOM_A;
        } else {
          return DominanceStatus::A_DOM_B;
        }
      } else {
        return invert(this->compareRightEdges(b, t));
      }
    }
    DominanceStatus compareWith(const BEdge& be, BEdge& tleft, BEdge& tright, BEdge& beleft, BEdge& beright) const {
      if (this->isAPoint() && be.isAPoint()) {
        if (this->leftPoint().dominates(be.leftPoint()))
          return DominanceStatus::A_DOM_B;
        else if (be.leftPoint().dominates(this->leftPoint()))
          return DominanceStatus::B_DOM_A;
        else return DominanceStatus::NO_DOM;
      } else if (this->isAPoint()) {
        return invert(be.compareWithPoint(*this, tleft, tright));
      } else if (be.isAPoint()) {
        return this->compareWithPoint(be, beleft, beright);
      } else {
        BVect intThis;
        BVect intBe;
        if (this->intersect(be, intThis, intBe)) {
          tleft = BEdge(this->leftPoint(), intThis);
          tright = BEdge(intThis, this->rightPoint());
          beleft = BEdge(be.leftPoint(), intBe);
          beright = BEdge(intBe, be.rightPoint());
          BEdge restLeft;
          BEdge restRight;
          DominanceStatus left = restLeft.compareLeftEdges(tleft, beleft);
          if (left == DominanceStatus::A_PART_DOM_B)
            beleft = restLeft;
          else if (left == DominanceStatus::B_PART_DOM_A)
            tleft = restLeft;
          DominanceStatus right = restRight.compareRightEdges(tright, beright);
          if (right == DominanceStatus::A_PART_DOM_B)
            beright = restRight;
          else if (right == DominanceStatus::B_PART_DOM_A)
            tright = restRight;
          return DominanceStatus::MUTUAL_DOM;
        } else {
          if (this->isInA1AreaOf(be) || this->isInA2AreaOf(be))
            return DominanceStatus::NO_DOM;
          std::pair<BVect, BVect> projb1 = this->computeProjWithPoint(be.leftPoint());
          BVect proj1bleft = projb1.first;
          BVect proj2bleft = projb1.second;
          std::pair<BVect, BVect> projb2 = this->computeProjWithPoint(be.rightPoint());
          BVect proj1bright = projb2.first;
          BVect proj2bright = projb2.second;
          std::pair<BVect, BVect> projt1 = be.computeProjWithPoint(this->leftPoint());
          BVect proj1tleft = projt1.first;
          BVect proj2tleft = projt1.second;
          std::pair<BVect, BVect> projt2 = be.computeProjWithPoint(this->rightPoint());
          BVect proj1tright = projt2.first;
          BVect proj2tright = projt2.second;
          bool adomb = false;
          bool bdoma = false;
          bool apartdomb = false;
          bool bpartdoma = false;
          if (be.leftPoint().weaklyDominates(proj1bleft)) {
            bdoma = true;
            if (proj1bleft != this->leftPoint()) {
              tleft = BEdge(this->leftPoint(), proj1bleft);
              bpartdoma = true;
            }
          }
          if (be.rightPoint().weaklyDominates(proj2bright)) {
            bdoma = true;
            if (proj2bright != this->rightPoint()) {
              tright = BEdge(proj2bright, this->rightPoint());
              bpartdoma = true;
            }
          }
          if (proj2bleft.weaklyDominates(be.leftPoint())) {
            adomb = true;
          }
          if (proj1bright.weaklyDominates(be.rightPoint())) {
            adomb = true;
          }
          if (this->leftPoint().weaklyDominates(proj1tleft)) {
            adomb = true;
            if (proj1tleft != be.leftPoint()) {
              beleft = BEdge(be.leftPoint(), proj1tleft);
              apartdomb = true;
            }
          }
          if (this->rightPoint().weaklyDominates(proj2tright)) {
            adomb = true;
            if (proj2tright != be.rightPoint()) {
              beright = BEdge(proj2tright, be.rightPoint());
              apartdomb = true;
            }
          }
          if (proj2tleft.weaklyDominates(this->leftPoint())) {
            bdoma = true;
          }
          if (proj1tright.weaklyDominates(this->rightPoint())) {
            bdoma = true;
          }
          if (adomb && bdoma)
            return DominanceStatus::MUTUAL_DOM;
          if (apartdomb)
            return DominanceStatus::A_PART_DOM_B;
          if (adomb)
            return DominanceStatus::A_DOM_B;
          if (bpartdoma)
            return DominanceStatus::B_PART_DOM_A;
          if (bdoma)
            return DominanceStatus::B_DOM_A;
          return DominanceStatus::NO_DOM;
        }
      }
    }
    friend ostream& operator << (ostream& s, const BEdge& be) {
      s << "[" << be.leftPoint() << ", " << be.rightPoint() << "]";
      return s;
    }
};

#endif
<|endoftext|>


<commit_before>//
// Common abstract class for Visualization Library.  Maintains debug
// flag, reference counting, modified time, and other common
// functions/parameters.
//

#ifndef __vlObject_h
#define __vlObject_h

#include <iostream.h>
#include "TimeSt.hh"
//
// Common #defines / parameters
//

//
// Class definition
//

class vlObject
{
public:
  vlObject();
  virtual ~vlObject();
  void Register(const void* p) {this->RefCount++;};
  void UnRegister(const void* p) {if (--this->RefCount <= 0) delete this;};
  int  GetRefCount() {return this->RefCount;};
  void DebugOn();
  void DebugOff();
  int GetDebug();
  vlTimeStamp Mtime; // Keep track of modification time
  void Modified() {Mtime.Modified();};

protected:
  int Debug;       // Enable debug messages

private:
  int RefCount;    // Number of uses of this object by other objects

};

#endif

<commit_msg>Now includes SetGet.hh and defined GetClassName()<commit_after>//
// Common abstract class for Visualization Library.  Maintains debug
// flag, reference counting, modified time, and other common
// functions/parameters.
//

#ifndef __vlObject_h
#define __vlObject_h

#include <iostream.h>
#include "TimeSt.hh"
#include "SetGet.hh"

//
// Common #defines / parameters
//

//
// Class definition
//

class vlObject
{
public:
  vlObject();
  virtual ~vlObject();
  void Register(const void* p) {this->RefCount++;};
  void UnRegister(const void* p) {if (--this->RefCount <= 0) delete this;};
  int  GetRefCount() {return this->RefCount;};
  void DebugOn();
  void DebugOff();
  int GetDebug();
  vlTimeStamp Mtime; // Keep track of modification time
  void Modified() {Mtime.Modified();};
  virtual char *GetClassName() {return "vlObject";};

protected:
  int Debug;       // Enable debug messages

private:
  int RefCount;    // Number of uses of this object by other objects

};

#endif

<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Library
  Module:    ProbeF.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
// .NAME vlProbeFilter - compute data values at specified point locations
// .SECTION Description
// vlProbeFilter is a filter that computes point attributes (e.g., scalars,
// vectors, etc.) at point positions in the input. The point positions
// are obtained from the points in the source object.

#ifndef __vlProbeFilter_h
#define __vlProbeFilter_h

#include "DS2DSF.hh"

class vlProbeFilter : public vlDataSetToDataSetFilter
{
public:
  vlProbeFilter();
  ~vlProbeFilter();
  char *GetClassName() {return "vlProbeFilter";};
  void PrintSelf(ostream& os, vlIndent indent);

  void Update();
  void Initialize();

  // Description:
  // Specify the point locations used to probe input. Any geometry
  // can be used.
  vlSetObjectMacro(Source,vlDataSet);
  vlGetObjectMacro(Source,vlDataSet);

protected:
  void Execute();
  vlDataSet *Source;

};

#endif

<commit_msg>temp fix of undefined methods<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    ProbeF.hh
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
// .NAME vlProbeFilter - compute data values at specified point locations
// .SECTION Description
// vlProbeFilter is a filter that computes point attributes (e.g., scalars,
// vectors, etc.) at point positions in the input. The point positions
// are obtained from the points in the source object.

#ifndef __vlProbeFilter_h
#define __vlProbeFilter_h

#include "DS2DSF.hh"

class vlProbeFilter : public vlDataSetToDataSetFilter
{
public:
  // vlProbeFilter();
  // ~vlProbeFilter();
  char *GetClassName() {return "vlProbeFilter";};
  // void PrintSelf(ostream& os, vlIndent indent);

  void Update();
  void Initialize();

  // Description:
  // Specify the point locations used to probe input. Any geometry
  // can be used.
  vlSetObjectMacro(Source,vlDataSet);
  vlGetObjectMacro(Source,vlDataSet);

protected:
  void Execute();
  vlDataSet *Source;

};

#endif

<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexVB.cxx
 ** Lexer for Visual Basic and VBScript.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static int classifyWordVB(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {

	char s[100];
	bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.') ||
		(styler[start] == '&' && tolower(styler[start+1]) == 'h');
	unsigned int i;
	for (i = 0; i < end - start + 1 && i < 30; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
	}
	s[i] = '\0';
	char chAttr = SCE_C_DEFAULT;
	if (wordIsNumber)
		chAttr = SCE_C_NUMBER;
	else {
		if (strcmp(s, "rem") == 0)
			chAttr = SCE_C_COMMENTLINE;
		else if (keywords.InList(s))
			chAttr = SCE_C_WORD;
	}
	styler.ColourTo(end, chAttr);
	if (chAttr == SCE_C_COMMENTLINE)
		return SCE_C_COMMENTLINE;
	else
		return SCE_C_DEFAULT;
}

static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle,
                           WordList *keywordlists[], Accessor &styler) {

	WordList &keywords = *keywordlists[0];

	styler.StartAt(startPos);

	int visibleChars = 0;
	int state = initStyle;
	char chNext = styler[startPos];
	styler.StartSegment(startPos);
	int lengthDoc = startPos + length;
	for (int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			i += 1;
			continue;
		}

		if (ch == '\r' || ch == '\n') {
			// End of line
			if (state == SCE_C_COMMENTLINE || state == SCE_C_PREPROCESSOR) {
				styler.ColourTo(i - 1, state);
				state = SCE_C_DEFAULT;
			}
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;

		if (state == SCE_C_DEFAULT) {
			if (iswordstart(ch)) {
				styler.ColourTo(i - 1, state);
				state = SCE_C_WORD;
			} else if (ch == '\'') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_COMMENTLINE;
			} else if (ch == '\"') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_STRING;
			} else if (ch == '#' && visibleChars == 1) {
				// Preprocessor commands are alone on their line
				styler.ColourTo(i - 1, state);
				state = SCE_C_PREPROCESSOR;
			} else if (ch == '&' && tolower(chNext) == 'h') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_WORD;
			} else if (isoperator(ch)) {
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_C_OPERATOR);
			}
		} else if (state == SCE_C_WORD) {
			if (!iswordchar(ch)) {
				state = classifyWordVB(styler.GetStartSegment(), i - 1, keywords, styler);
				if (state == SCE_C_DEFAULT) {
					if (ch == '\'') {
						state = SCE_C_COMMENTLINE;
					} else if (ch == '\"') {
						state = SCE_C_STRING;
					} else if (isoperator(ch)) {
						styler.ColourTo(i - 1, state);
						styler.ColourTo(i, SCE_C_OPERATOR);
					}
				}
			}
		} else {
			if (state == SCE_C_STRING) {
				// VB doubles quotes to preserve them
				if (ch == '\"') {
					styler.ColourTo(i, state);
					state = SCE_C_DEFAULT;
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			}
			if (state == SCE_C_DEFAULT) {    // One of the above succeeded
				if (ch == '\'') {
					state = SCE_C_COMMENTLINE;
				} else if (ch == '\"') {
					state = SCE_C_STRING;
				} else if (iswordstart(ch)) {
					state = SCE_C_WORD;
				}
			}
		}
	}
	styler.ColourTo(lengthDoc, state);
}

LexerModule lmVB(SCLEX_VB, ColouriseVBDoc, "vb");
<commit_msg>Folding added by Willy Devaux.<commit_after>// Scintilla source code edit control
/** @file LexVB.cxx
 ** Lexer for Visual Basic and VBScript.
 **/
// Copyright 1998-2001 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>

#include "Platform.h"

#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"

static int classifyWordVB(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler) {

	char s[100];
	bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.') ||
		(styler[start] == '&' && tolower(styler[start+1]) == 'h');
	unsigned int i;
	for (i = 0; i < end - start + 1 && i < 30; i++) {
		s[i] = static_cast<char>(tolower(styler[start + i]));
	}
	s[i] = '\0';
	char chAttr = SCE_C_DEFAULT;
	if (wordIsNumber)
		chAttr = SCE_C_NUMBER;
	else {
		if (strcmp(s, "rem") == 0)
			chAttr = SCE_C_COMMENTLINE;
		else if (keywords.InList(s))
			chAttr = SCE_C_WORD;
	}
	styler.ColourTo(end, chAttr);
	if (chAttr == SCE_C_COMMENTLINE)
		return SCE_C_COMMENTLINE;
	else
		return SCE_C_DEFAULT;
}

static bool IsVBComment(Accessor &styler, int pos, int len) {
	return len>0 && styler[pos]=='\'';
}

static void ColouriseVBDoc(unsigned int startPos, int length, int initStyle,
                           WordList *keywordlists[], Accessor &styler) {

	WordList &keywords = *keywordlists[0];

	styler.StartAt(startPos);

	int visibleChars = 0;
	int state = initStyle;
	char chNext = styler[startPos];
	styler.StartSegment(startPos);
	int lengthDoc = startPos + length;
	for (int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);

		if (styler.IsLeadByte(ch)) {
			chNext = styler.SafeGetCharAt(i + 2);
			i += 1;
			continue;
		}

		if (ch == '\r' || ch == '\n') {
			// End of line
			if (state == SCE_C_COMMENTLINE || state == SCE_C_PREPROCESSOR) {
				styler.ColourTo(i - 1, state);
				state = SCE_C_DEFAULT;
			}
			visibleChars = 0;
		}
		if (!isspacechar(ch))
			visibleChars++;

		if (state == SCE_C_DEFAULT) {
			if (iswordstart(ch)) {
				styler.ColourTo(i - 1, state);
				state = SCE_C_WORD;
			} else if (ch == '\'') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_COMMENTLINE;
			} else if (ch == '\"') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_STRING;
			} else if (ch == '#' && visibleChars == 1) {
				// Preprocessor commands are alone on their line
				styler.ColourTo(i - 1, state);
				state = SCE_C_PREPROCESSOR;
			} else if (ch == '&' && tolower(chNext) == 'h') {
				styler.ColourTo(i - 1, state);
				state = SCE_C_WORD;
			} else if (isoperator(ch)) {
				styler.ColourTo(i - 1, state);
				styler.ColourTo(i, SCE_C_OPERATOR);
			}
		} else if (state == SCE_C_WORD) {
			if (!iswordchar(ch)) {
				state = classifyWordVB(styler.GetStartSegment(), i - 1, keywords, styler);
				if (state == SCE_C_DEFAULT) {
					if (ch == '\'') {
						state = SCE_C_COMMENTLINE;
					} else if (ch == '\"') {
						state = SCE_C_STRING;
					} else if (isoperator(ch)) {
						styler.ColourTo(i - 1, state);
						styler.ColourTo(i, SCE_C_OPERATOR);
					}
				}
			}
		} else {
			if (state == SCE_C_STRING) {
				// VB doubles quotes to preserve them
				if (ch == '\"') {
					styler.ColourTo(i, state);
					state = SCE_C_DEFAULT;
					i++;
					ch = chNext;
					chNext = styler.SafeGetCharAt(i + 1);
				}
			}
			if (state == SCE_C_DEFAULT) {    // One of the above succeeded
				if (ch == '\'') {
					state = SCE_C_COMMENTLINE;
				} else if (ch == '\"') {
					state = SCE_C_STRING;
				} else if (iswordstart(ch)) {
					state = SCE_C_WORD;
				}
			}
		}
	}
	styler.ColourTo(lengthDoc, state);
}

static void FoldVBDoc(unsigned int startPos, int length, int initStyle,
						   WordList *[], Accessor &styler) {
	int lengthDoc = startPos + length;

	// Backtrack to previous line in case need to fix its fold status
	int lineCurrent = styler.GetLine(startPos);
	if (startPos > 0) {
		if (lineCurrent > 0) {
			lineCurrent--;
			startPos = styler.LineStart(lineCurrent);
			if (startPos == 0)
				initStyle = SCE_P_DEFAULT;
			else
				initStyle = styler.StyleAt(startPos-1);
		}
	}
	int state = initStyle & 31;
	int spaceFlags = 0;
	int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsVBComment);
	if ((state == SCE_P_TRIPLE) || (state == SCE_P_TRIPLEDOUBLE))
		indentCurrent |= SC_FOLDLEVELWHITEFLAG;
	char chNext = styler[startPos];
	for (int i = startPos; i < lengthDoc; i++) {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styler.StyleAt(i) & 31;

		if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc)) {
			int lev = indentCurrent;
			int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsVBComment);
			if ((style == SCE_P_TRIPLE) || (style== SCE_P_TRIPLEDOUBLE))
				indentNext |= SC_FOLDLEVELWHITEFLAG;
			if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
				// Only non whitespace lines can be headers
				if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK)) {
					lev |= SC_FOLDLEVELHEADERFLAG;
				} else if (indentNext & SC_FOLDLEVELWHITEFLAG) {
					// Line after is blank so check the next - maybe should continue further?
					int spaceFlags2 = 0;
					int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsVBComment);
					if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK)) {
						lev |= SC_FOLDLEVELHEADERFLAG;
					}
				}
			}
			indentCurrent = indentNext;
			styler.SetLevel(lineCurrent, lev);
			lineCurrent++;
		}
	}
}

LexerModule lmVB(SCLEX_VB, ColouriseVBDoc, "vb", FoldVBDoc);
<|endoftext|>


<commit_before>#include "StateMachine.h"

#include <regex>
#include <algorithm>
#include <iostream>
#include <map>

struct Nil   {};

typedef corvid::Machine<
  char,
  Nil
> LexerMachine;

struct Start;
struct Integer;
struct Identifier;

template <char A>        struct Literal;

const char* keyword_if = "if";

struct Start : public LexerMachine::State {
  Start(LexerMachine* pMachine)
    : LexerMachine::State(pMachine) {
  }

  void onEvent (char c) {
    std::cout << "Start " << c << std::endl;
    if (c == '(') {
      getMachine()->transition<Literal<'('>>();
    }
    if (std::isdigit(c)) {
      getMachine()->transition<Integer>();
    }
    if (std::isalpha(c)) {
      getMachine()->transition<Identifier>();
    }
  }
};

// [0-9]
struct Integer : public LexerMachine::State {
  Integer(LexerMachine* pMachine) : LexerMachine::State(pMachine) {}
  void onEvent (char c) {
    std::cout << "Integer " << c << std::endl;
  }
};

// [a-z]...
struct Identifier : public LexerMachine::State {
  Identifier(LexerMachine* pMachine) : LexerMachine::State(pMachine) {}
  void onEvent (char c) {
    if (std::islower(c)) {
      std::cout << "lower " << c << std::endl;
    }
  }
};

// A
template <char A>
struct Literal : public LexerMachine::State {
  Literal(LexerMachine* pMachine) : LexerMachine::State(pMachine) {}
  void onEvent (char c) {
    std::cout << "Literal<A> " << c << std::endl;
    //getMachine()->yield(A);
  }
};

struct Lexer : public LexerMachine {
  Lexer(const std::string& s)
    : LexerMachine()
    , begin(s.begin())
    , end(s.end()) {
  }

  std::vector<int> tokenize() {
    tokens.clear();
    skip();
    while (begin != end) {
      dispatch(*begin++);
      skip();
    }
    return tokens;
  }

  void skip() {
    while (begin != end && std::isspace(*begin)) { begin++; }
  }

  void yield(int i) {
    tokens.push_back(i);
  }

  std::vector<int>            tokens;
  std::string::const_iterator begin;
  std::string::const_iterator end;
};

int main () {
  std::cout << "Lexer Test" << std::endl;
  // a+(b|c)
  typedef std::string Input;
  typedef std::string Token;
  typedef std::string State;
  typedef std::map<Input, State>       Transitions;
  typedef std::map<State, Transitions> States;
  typedef std::tuple<State, States>    Machine;

  auto fsm = States({
    { "even", {
      {"\e", "-"},
      {"0",  "even"},
      {"1",  "odd"},
      {"\a", "even"},
    }},
    { "odd",  {
      {"\e", "-"},
      {"1",  "even"},
      {"0",  "odd"},
      {"\a", "odd"},
    }},
  });

  auto fsm_exec = [](Machine& m, Input input) {
    auto& state  = std::get<0>(m);
    auto& states = std::get<1>(m);
    state = states.at(state).at(input);
    std::cout << "input = " << input << ", state = " << state << std::endl;
  };

  auto fsm_accept = [](Machine& m) -> Token {
    auto& state  = std::get<0>(m);
    auto& states = std::get<1>(m);
    return states.at(state).at("\a");
  };

  try {
    Machine m = {"even", fsm};
    fsm_exec(m, "0");
    fsm_exec(m, "1");
    fsm_exec(m, "1");
    fsm_exec(m, "1");
    fsm_exec(m, "1");
    fsm_exec(m, "1");
    fsm_exec(m, "0");
    std::cout << " yield = " << fsm_accept(m) << std::endl;

    auto text = std::string("if (acb * V), aw: + a34_");
    Lexer lexer(text);
    lexer.transition<Start>();
    auto tokens = lexer.tokenize();
    for (auto t : tokens) {
      std::cout << "token: " << t << std::endl;
    }
  } catch (std::exception& e) {
    std::cout << "error: " << e.what() << std::endl;
  }
}
<commit_msg>broken<commit_after>#include "StateMachine.h"

#include <regex>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <map>
#include <list>

int main () {
  std::cout << "Lexer Test" << std::endl;
  typedef std::string                       Input;
  typedef std::string                       Token;
  typedef std::string                       State;

  typedef std::map<Input, std::list<State>> NfaTransitions;
  typedef std::map<State, NfaTransitions>   NfaStates;
  typedef std::tuple<State, NfaStates, std::list<State>>    Nfa;

  typedef std::map<Input, State>            DfaTransitions;
  typedef std::map<State, DfaTransitions>   DfaStates;
  typedef std::tuple<State, DfaStates>      Dfa;

  auto fsm = DfaStates({
    { "even", {
      {"0",  "even"},
      {"1",  "odd"},
      {"\a", "even"},
    }},
    { "odd",  {
      {"1",  "even"},
      {"0",  "odd"},
      {"\a", "odd"},
    }},
  });

  auto dfa_exec = [](Dfa& m, Input input) {
    auto& state  = std::get<0>(m);
    auto& states = std::get<1>(m);
    state = states.at(state).at(input);
    std::cout << "input = " << input << ", state = " << state << std::endl;
  };

  auto dfa_accept = [](Dfa& m) -> Token {
    auto& state  = std::get<0>(m);
    auto& states = std::get<1>(m);
    return states.at(state).at("\a");
  };

  auto re_namespace = [](const Nfa& nfa, const std::string& name) -> Nfa {
    NfaStates states;
    auto& nstate  = std::get<0>(nfa);
    auto& nstates = std::get<1>(nfa);
    auto& naccept = std::get<2>(nfa);
    for (auto s : nstates) {
      for (auto t : s.second) {
        states[name+s.first][t.first] = {};
        for (auto u : t.second) {
          states[name+s.first][t.first].push_back(name + u);
        }
      }
    }
    std::list<State> accept;
    for (auto a : naccept) {
      accept.push_back(name + a);
    }
    return Nfa(name + nstate, states, accept);
  };

  auto re_symbol = [](std::string sym) -> Nfa {
    auto states = NfaStates({
      { "0", {
        {sym,  {"1"}},
      }},
      { "1",  {
        {},
      }}
    });

    return Nfa("0", states, {"1"});
  };

  auto re_union = [&](const Nfa& a, const Nfa& b) -> Nfa {
    auto re_a   = re_namespace(a, "a.");
    auto re_b   = re_namespace(b, "b.");

    auto& a_state  = std::get<0>(re_a);
    auto& a_states = std::get<1>(re_a);
    auto& a_accept = std::get<2>(re_a);
    auto& b_state  = std::get<0>(re_b);
    auto& b_states = std::get<1>(re_b);
    auto& b_accept = std::get<2>(re_b);

    auto states = NfaStates({
      { "0", {
        {},
      }},
      { "1",  {
        {},
      }}
    });

    // Epsilon transitions
    states["0"][""] = {a_state, b_state};
    for (auto a : a_accept) {
      states[a][""] = {"1"};
    }
    for (auto b : b_accept) {
      states[b][""] = {"1"};
    }

    // Subexpressions
    for (auto s : a_states) {
      states[s.first] = s.second;
    }
    for (auto s : b_states) {
      states[s.first] = s.second;
    }

    return Nfa("0", states, {"1"});
  };

  auto re = re_union(re_symbol("cat"), re_union(re_symbol("dog"), re_symbol("bird")));
  // print stuff
  std::cout << "\n\n NFA: " << std::endl;
  for (auto s : std::get<1>(re)) {
    std::cout << s.first << std::endl;
    for (auto t : s.second) {
      std::cout << "  " << std::setw(6) << t.first << ": ";
      for (auto d : t.second) {
          std::cout << d <<  "  " ;
      }
      std::cout << std::endl;
    }
  }

  // http://www.cs.may.ie/staff/jpower/Courses/Previous/parsing/node9.html
  auto closure = [](const Nfa& nfa, const State& state) -> std::list<State> {
    std::list<State> states;
    const auto& nstate  = std::get<0>(nfa);
    const auto& nstates = std::get<1>(nfa);
    const auto& naccept = std::get<2>(nfa);
    // The e-closure function takes a state and returns the set of states reachable
    // from it based on (one or more) e-transitions. Note that this will always
    // include the state tself. We should be able to get from a state to any state
    // in its e-closure without consuming any input.
    states.push_back(state);
    auto state_transitions = std::get<1>(nfa)[state];
    return states;
  };

  auto move = [](const Nfa& nfa, const State& state, Input input) -> std::list<State> {
    std::list<State> states;
    // The function move takes a state and a character, and returns the set of
    // states reachable by one transition on this character.

    return states;
  };

  auto nfa_to_dfa = [](const Nfa& nfa) -> Dfa {
    Dfa dfa;
    // 1. Create the start state of the DFA by taking the e-closure of the start state
    //    of the NFA.
    // 2. Perform the following for the new DFA state:
    //    For each possible input symbol:
    //    1. Apply move to the newly-created state and the input symbol; this will return
    //       a set of states.
    //    2. Apply the e-closure to this set of states, possibly resulting in a new set.
    //
    // This set of NFA states will be a single state in the DFA.
    // 3. Each time we generate a new DFA state, we must apply step 2 to it. The process
    //    is complete when applying step 2 does not yield any new states.
    // 4. The finish states of the DFA are those which contain any of the finish states
    //    of the NFA.

    return dfa;
  };

  auto re_dfa = nfa_to_dfa(re);
  std::cout << "\n\n DFA: " << std::endl;
  for (auto s : std::get<1>(re_dfa)) {
    std::cout << s.first << std::endl;
    for (auto t : s.second) {
      std::cout << "  " << std::setw(6) << t.first << ": ";
      for (auto d : t.second) {
          std::cout << d <<  "  " ;
      }
      std::cout << std::endl;
    }
  }

  try {
  /*
    Dfa m = {"even", fsm};
    dfa_exec(m, "0");
    dfa_exec(m, "1");
    dfa_exec(m, "1");
    dfa_exec(m, "1");
    dfa_exec(m, "1");
    dfa_exec(m, "1");
    dfa_exec(m, "0");
    std::cout << " yield = " << dfa_accept(m) << std::endl;
  */
  } catch (std::exception& e) {
    std::cout << "error: " << e.what() << std::endl;
  }
}
<|endoftext|>


<commit_before>/**
 * @file		cossb.hpp
 * @brief		COSSB Header
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 6. 9
 * @details
 */

#ifndef _COSSB_HEADER_HPP_
#define _COSSB_HEADER_HPP_

#if defined(__unix__) || defined(__gnu_linux__) || defined(linux) || defined(__linux__)

#include "version.hpp"
#include "errorcode.hpp"
#include "typedef.hpp"
#include "macro.hpp"
#include "manager.hpp"
#include "broker.hpp"
#include "config.hpp"
#include "log.hpp"
#include "instance.hpp"

#include "util/pid.h"
#endif

#endif
<commit_msg>edit headerfile<commit_after>/**
 * @file		cossb.hpp
 * @brief		COSSB Header
 * @author		Byunghun Hwang<bhhwang@nsynapse.com>
 * @date 		2015. 6. 9
 * @details
 */

#ifndef _COSSB_HEADER_HPP_
#define _COSSB_HEADER_HPP_

#if defined(__unix__) || defined(__gnu_linux__) || defined(linux) || defined(__linux__)

#include "version.hpp"
#include "errorcode.hpp"
#include "typedef.hpp"
#include "macro.hpp"
#include "manager.hpp"
#include "broker.hpp"
#include "config.hpp"
#include "instance.hpp"

#include "util/pid.h"
#endif

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <sqlite3.h>
#include <string>
#include <cstring>
#include <map>
#include <sstream>
#include "ReadGzip.h"
using namespace std;
#include "MBTileReader.h"
#include "vector_tile20/vector_tile.pb.h"

#include <string>
#include <sstream>
#include <vector>

using namespace std;

// http://stackoverflow.com/a/236803/4288232
void strsplit(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

string FeatureTypeToStr(::vector_tile::Tile_GeomType type)
{
	if(type == ::vector_tile::Tile_GeomType_UNKNOWN)
		return "Unknown";
	if(type == ::vector_tile::Tile_GeomType_POINT)
		return "Point";
	if(type == ::vector_tile::Tile_GeomType_LINESTRING)
		return "LineString";
	if(type == ::vector_tile::Tile_GeomType_POLYGON)
		return "Polygon";
	return "Unknown type";
}

int main(int argc, char **argv)
{
	class MBTileReader mbTileReader("cairo_egypt.mbtiles");

	cout << "name:" << mbTileReader.GetMetadata("name") << endl;
	cout << "type:" << mbTileReader.GetMetadata("type") << endl;
	string version = mbTileReader.GetMetadata("version");
	cout << "version:" << version << endl;
	vector<string> versionSplit;
	strsplit(version, '.', versionSplit);
	vector<int> versionInts;
	for (int i=0;i<versionSplit.size();i++) versionInts.push_back(atoi(versionSplit[i].c_str()));
	cout << "description:" << mbTileReader.GetMetadata("description") << endl;
	string format = mbTileReader.GetMetadata("format");
	cout << "format:" << format << endl;
	cout << "bounds:" << mbTileReader.GetMetadata("bounds") << endl;

	if(0) //Get metadata fields
	{
		std::vector<std::string> fieldNames;
		mbTileReader.GetMetadataFields(fieldNames);
		for(unsigned i=0;i<fieldNames.size();i++) cout << fieldNames[i] << endl;
	}

	if(0) //Get list of tiles
	{
		TileInfoRows tileInfoRows;
		mbTileReader.ListTiles(tileInfoRows);
		for(unsigned i=0;i < tileInfoRows.size(); i++)
		{
			for(size_t j=0; j < tileInfoRows[i].size(); j++)
				cout << tileInfoRows[i][j] << ",";
			cout << endl;
		}
	}

	string blob;
	mbTileReader.GetTile(14,9618,9611,blob);

	if(format == "pbf" && versionInts[0] == 2)
	{
		std::stringbuf buff;
		buff.sputn(blob.c_str(), blob.size());
		DecodeGzip dec(buff);

		string tileData;

		char tmp[1024];
		while(dec.in_avail())
		{
			streamsize bytes = dec.sgetn(tmp, 1024);
			tileData.append(tmp, bytes);
		}

		vector_tile::Tile tile;
		cout << "ParseFromString: " << tile.ParseFromString(tileData) << endl;
		cout << "Num layers: " << tile.layers_size() << endl;

		for(int layerNum = 0; layerNum < tile.layers_size(); layerNum++)
		{
			const ::vector_tile::Tile_Layer &layer = tile.layers(layerNum);
			cout << "layer version: " << layer.version() << endl;
			cout << "layer name: " << layer.name() << endl;
			cout << "layer extent: " << layer.extent() << endl;
			cout << "layer keys_size(): " << layer.keys_size() << endl;
			cout << "layer values_size(): " << layer.values_size() << endl;
			cout << "layer features_size(): " << layer.features_size() << endl;

			for(int featureNum = 0; featureNum < layer.features_size(); featureNum++)
			{
				const ::vector_tile::Tile_Feature &feature =layer.features(featureNum);
				cout << featureNum << "," << feature.type() << "," << FeatureTypeToStr(feature.type()) << endl;
			}
		}
	}
}

<commit_msg>Decode tags<commit_after>#include <iostream>
#include <sqlite3.h>
#include <string>
#include <cstring>
#include <map>
#include <sstream>
#include "ReadGzip.h"
using namespace std;
#include "MBTileReader.h"
#include "vector_tile20/vector_tile.pb.h"

#include <string>
#include <sstream>
#include <vector>

using namespace std;

// http://stackoverflow.com/a/236803/4288232
void strsplit(const string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
}

string FeatureTypeToStr(::vector_tile::Tile_GeomType type)
{
	if(type == ::vector_tile::Tile_GeomType_UNKNOWN)
		return "Unknown";
	if(type == ::vector_tile::Tile_GeomType_POINT)
		return "Point";
	if(type == ::vector_tile::Tile_GeomType_LINESTRING)
		return "LineString";
	if(type == ::vector_tile::Tile_GeomType_POLYGON)
		return "Polygon";
	return "Unknown type";
}

string ValueToStr(const ::vector_tile::Tile_Value &value)
{
	if(value.has_string_value())
		return value.string_value();
	if(value.has_float_value())
	{
		stringstream ss;
		ss << value.float_value();
		return ss.str();
	}
	if(value.has_double_value())
	{
		stringstream ss;
		ss << value.double_value();
		return ss.str();
	}
	if(value.has_int_value())
	{
		stringstream ss;
		ss << value.int_value();
		return ss.str();
	}
	if(value.has_uint_value())
	{
		stringstream ss;
		ss << value.uint_value();
		return ss.str();
	}
	if(value.has_sint_value())
	{
		stringstream ss;
		ss << value.sint_value();
		return ss.str();
	}
	if(value.has_bool_value())
	{
		stringstream ss;
		ss << value.bool_value();
		return ss.str();
	}
	return "Error: Unknown value type";
}

int main(int argc, char **argv)
{
	class MBTileReader mbTileReader("cairo_egypt.mbtiles");

	cout << "name:" << mbTileReader.GetMetadata("name") << endl;
	cout << "type:" << mbTileReader.GetMetadata("type") << endl;
	string version = mbTileReader.GetMetadata("version");
	cout << "version:" << version << endl;
	vector<string> versionSplit;
	strsplit(version, '.', versionSplit);
	vector<int> versionInts;
	for (int i=0;i<versionSplit.size();i++) versionInts.push_back(atoi(versionSplit[i].c_str()));
	cout << "description:" << mbTileReader.GetMetadata("description") << endl;
	string format = mbTileReader.GetMetadata("format");
	cout << "format:" << format << endl;
	cout << "bounds:" << mbTileReader.GetMetadata("bounds") << endl;

	if(0) //Get metadata fields
	{
		std::vector<std::string> fieldNames;
		mbTileReader.GetMetadataFields(fieldNames);
		for(unsigned i=0;i<fieldNames.size();i++) cout << fieldNames[i] << endl;
	}

	if(0) //Get list of tiles
	{
		TileInfoRows tileInfoRows;
		mbTileReader.ListTiles(tileInfoRows);
		for(unsigned i=0;i < tileInfoRows.size(); i++)
		{
			for(size_t j=0; j < tileInfoRows[i].size(); j++)
				cout << tileInfoRows[i][j] << ",";
			cout << endl;
		}
	}

	string blob;
	mbTileReader.GetTile(14,9618,9611,blob);

	if(format == "pbf" && versionInts[0] == 2)
	{
		std::stringbuf buff;
		buff.sputn(blob.c_str(), blob.size());
		DecodeGzip dec(buff);

		string tileData;

		char tmp[1024];
		while(dec.in_avail())
		{
			streamsize bytes = dec.sgetn(tmp, 1024);
			tileData.append(tmp, bytes);
		}

		vector_tile::Tile tile;
		cout << "ParseFromString: " << tile.ParseFromString(tileData) << endl;
		cout << "Num layers: " << tile.layers_size() << endl;

		for(int layerNum = 0; layerNum < tile.layers_size(); layerNum++)
		{
			const ::vector_tile::Tile_Layer &layer = tile.layers(layerNum);
			cout << "layer version: " << layer.version() << endl;
			cout << "layer name: " << layer.name() << endl;
			cout << "layer extent: " << layer.extent() << endl;
			cout << "layer keys_size(): " << layer.keys_size() << endl;
			cout << "layer values_size(): " << layer.values_size() << endl;
			cout << "layer features_size(): " << layer.features_size() << endl;

			for(int featureNum = 0; featureNum < layer.features_size(); featureNum++)
			{
				const ::vector_tile::Tile_Feature &feature =layer.features(featureNum);
				cout << featureNum << "," << feature.type() << "," << FeatureTypeToStr(feature.type()) << endl;
				for(int tagNum = 0; tagNum < feature.tags_size(); tagNum+=2)
				{
					cout << layer.keys(feature.tags(tagNum)) << "=";
					const ::vector_tile::Tile_Value &value = layer.values(feature.tags(tagNum+1));
					cout << ValueToStr(value) << endl;
				}
			}
		}

	}
}

<|endoftext|>


<commit_before>#include "Lia/list/basics.hpp"
#include "Lia/list/folds.hpp"
#include <vector>
#include <string>
#include <cassert>

void basic_test() {
    std::vector<int> v = {1,2,3,4,5,6,7,8,9,10,11};
    assert(lia::head(v) == 1 && "head");
    assert(lia::last(v) == 11 && "last");
    assert(lia::null(v) == false && "null");
    assert(lia::length(v) == 11 && "length");
    assert((lia::tail(std::vector<int>{1,2,3,4}) == std::vector<int>{2,3,4}) && "tail");
    assert((v == std::vector<int>{1,2,3,4,5,6,7,8,9,10,11}) && "const-correctness");
    assert((lia::append(std::vector<int>{1,2,3},std::vector<int>{4,5,6}) == std::vector<int>{1,2,3,4,5,6}) && "append");
    assert((lia::append(std::string("one"), std::string("two")) == "onetwo") && "append(str)");
}

void transform_test() {
    std::vector<int> v = {1,2,3,4,5};
    assert((lia::map(v, [](int x) { return x > 4;}) == std::vector<bool>{false,false,false,false,true}) && "map");
    assert((lia::reverse(v) == std::vector<int>{5,4,3,2,1}) && "reverse");
    assert((lia::intersperse(v, 0) == std::vector<int>{1,0,2,0,3,0,4,0,5}) && "intersperse");
    assert((lia::subsequences(std::vector<int>{1,2,3,4}).size() == 16) && "subsequences");
    assert((lia::permutations(std::vector<int>{1,2,3,4}).size() == 24) && "permutations");
    assert((v == std::vector<int>{1,2,3,4,5}) && "const-correctness");
}

void fold_test() {
    std::vector<int> v = {1,2,3,4,5,6,7,8,9,10};
    auto b = lia::concat(std::vector<std::vector<int>>{{1,2,3},{4,5,6,7,8,9,10}});
    assert(lia::foldl(v, [](int x, int y) { return x + y; }, 0) == lia::sum(v) && "foldl or foldl1");
    assert(lia::foldr(v, [](int x, int y) { return x * y; }, 1) == lia::product(v) && "foldr or foldl1");
    assert(lia::foldr1(std::vector<int>{4,5,6,7,8,9,10}, [](int x, int y) { return x * y; }) == 604800 && "foldr1");
    assert(lia::all(std::vector<bool>{1,1,1,1,1,1,1,1}) && "all(bool)");
    assert(lia::all(std::vector<int>{6,7,8,9,10,11}, [](int x) { return x > 5; }) && "all(pred)");
    assert(lia::any(std::vector<bool>{0,0,0,1,0,1,0,0}) && "any(bool)");
    assert(lia::any(std::vector<int>{4,5,11,9,8}, [](int x) { return x == 5; }) && "any(pred)");
    assert(lia::minimum(std::vector<int>{99,11,11,10}) == 10 && "minimum");
    assert(lia::maximum(std::vector<int>{99,11,11,10}) == 99 && "maximum");
    assert(lia::concat(std::vector<std::string>{"Hello", "World"}) == "HelloWorld" && "concat(str)");
    assert(b == v && "concat");
}

int main() {
    basic_test();
    transform_test();
    fold_test();
}<commit_msg>Added concatMap test<commit_after>#include "Lia/list/basics.hpp"
#include "Lia/list/folds.hpp"
#include <vector>
#include <string>
#include <cassert>

void basic_test() {
    std::vector<int> v = {1,2,3,4,5,6,7,8,9,10,11};
    assert(lia::head(v) == 1 && "head");
    assert(lia::last(v) == 11 && "last");
    assert(lia::null(v) == false && "null");
    assert(lia::length(v) == 11 && "length");
    assert((lia::tail(std::vector<int>{1,2,3,4}) == std::vector<int>{2,3,4}) && "tail");
    assert((v == std::vector<int>{1,2,3,4,5,6,7,8,9,10,11}) && "const-correctness");
    assert((lia::append(std::vector<int>{1,2,3},std::vector<int>{4,5,6}) == std::vector<int>{1,2,3,4,5,6}) && "append");
    assert((lia::append(std::string("one"), std::string("two")) == "onetwo") && "append(str)");
}

void transform_test() {
    std::vector<int> v = {1,2,3,4,5};
    assert((lia::map(v, [](int x) { return x > 4;}) == std::vector<bool>{false,false,false,false,true}) && "map");
    assert((lia::reverse(v) == std::vector<int>{5,4,3,2,1}) && "reverse");
    assert((lia::intersperse(v, 0) == std::vector<int>{1,0,2,0,3,0,4,0,5}) && "intersperse");
    assert((lia::subsequences(std::vector<int>{1,2,3,4}).size() == 16) && "subsequences");
    assert((lia::permutations(std::vector<int>{1,2,3,4}).size() == 24) && "permutations");
    assert((v == std::vector<int>{1,2,3,4,5}) && "const-correctness");
}

void fold_test() {
    std::vector<int> v = {1,2,3,4,5,6,7,8,9,10};
    auto a = std::vector<std::vector<int>>{{1,2,3},{4,5,6,7,8,9,10}};
    auto b = lia::concat(a);
    assert(lia::foldl(v, [](int x, int y) { return x + y; }, 0) == lia::sum(v) && "foldl or foldl1");
    assert(lia::foldr(v, [](int x, int y) { return x * y; }, 1) == lia::product(v) && "foldr or foldl1");
    assert(lia::foldr1(std::vector<int>{4,5,6,7,8,9,10}, [](int x, int y) { return x * y; }) == 604800 && "foldr1");
    assert(lia::all(std::vector<bool>{1,1,1,1,1,1,1,1}) && "all(bool)");
    assert(lia::all(std::vector<int>{6,7,8,9,10,11}, [](int x) { return x > 5; }) && "all(pred)");
    assert(lia::any(std::vector<bool>{0,0,0,1,0,1,0,0}) && "any(bool)");
    assert(lia::any(std::vector<int>{4,5,11,9,8}, [](int x) { return x == 5; }) && "any(pred)");
    assert(lia::minimum(std::vector<int>{99,11,11,10}) == 10 && "minimum");
    assert(lia::maximum(std::vector<int>{99,11,11,10}) == 99 && "maximum");
    assert(lia::concat(std::vector<std::string>{"Hello", "World"}) == "HelloWorld" && "concat(str)");
    assert(b == v && "concat");
    auto c = lia::map(a, [](const std::vector<int>& i) { return lia::append(i, std::vector<int>{1,2,3}); });
    auto w = lia::concat(c);
    assert(lia::concatMap(a, [](const std::vector<int>& i) { return lia::append(i, std::vector<int>{1,2,3});}) == w && "concatMap");
}

int main() {
    basic_test();
    transform_test();
    fold_test();
}<|endoftext|>